@zenflux/core 0.1.12 → 0.1.13

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.
Files changed (48) hide show
  1. package/package.json +3 -4
  2. package/src/bases/controller-base.ts +0 -96
  3. package/src/bases/index.ts +0 -6
  4. package/src/bases/initialize-base.ts +0 -32
  5. package/src/bases/object-base.ts +0 -55
  6. package/src/clients/http.ts +0 -152
  7. package/src/command-bases/command-base.ts +0 -82
  8. package/src/command-bases/command-internal.ts +0 -11
  9. package/src/command-bases/command-public.ts +0 -12
  10. package/src/command-bases/command-restful.ts +0 -55
  11. package/src/command-bases/index.ts +0 -8
  12. package/src/errors/command-already-registered.ts +0 -13
  13. package/src/errors/command-not-found.ts +0 -12
  14. package/src/errors/controller-already-registered.ts +0 -13
  15. package/src/errors/controller-already-set.ts +0 -13
  16. package/src/errors/error-with-metadata.ts +0 -14
  17. package/src/errors/force-method-implementation.ts +0 -15
  18. package/src/errors/index-public.ts +0 -1
  19. package/src/errors/index.ts +0 -10
  20. package/src/exports-index.ts +0 -13
  21. package/src/exports.ts +0 -58
  22. package/src/index.ts +0 -18
  23. package/src/interfaces/commands.ts +0 -17
  24. package/src/interfaces/config.ts +0 -23
  25. package/src/interfaces/index.ts +0 -8
  26. package/src/interfaces/logger.ts +0 -19
  27. package/src/interfaces/restful.ts +0 -23
  28. package/src/managers/commands.ts +0 -268
  29. package/src/managers/controllers.ts +0 -40
  30. package/src/managers/export.ts +0 -30
  31. package/src/managers/index.ts +0 -8
  32. package/src/managers/internal.ts +0 -11
  33. package/src/managers/restful.ts +0 -117
  34. package/src/modules/debugger.ts +0 -89
  35. package/src/modules/event-bus/event-bus.ts +0 -204
  36. package/src/modules/logger/config.ts +0 -44
  37. package/src/modules/logger/implementation.ts +0 -287
  38. package/src/modules/logger/index.ts +0 -2
  39. package/src/modules/logger/logger-browser-infra.ts +0 -344
  40. package/src/modules/logger/types/picocolors.d.ts +0 -15
  41. package/src/modules/logger/utils/index.ts +0 -3
  42. package/src/modules/logger/utils/object.ts +0 -19
  43. package/src/modules/logger/utils/rgb.ts +0 -34
  44. package/src/modules/mcp-server/mcp-server.ts +0 -139
  45. package/src/modules/mcp-server/mcp-service.ts +0 -80
  46. package/src/modules/service/service-base.ts +0 -55
  47. package/src/modules/service/service-locator.ts +0 -205
  48. package/src/modules/service/service-with-dependencies-base.ts +0 -51
@@ -1,344 +0,0 @@
1
- /**
2
- * @author Leonid Vinikov <leonidvinikov@gmail.com>
3
- * @description a logger for web browser.
4
- *
5
- * TODO:
6
- * - Add dark/light switch for chrome devtools.
7
- * - https://stackoverflow.com/questions/41961037/is-there-a-way-to-detect-if-chromes-devtools-are-using-dark-mode
8
- * - Maybe 'zenflux-logging` should be chrome extension.
9
- */
10
- import { ObjectBase } from "../../bases/object-base";
11
-
12
- import { getHexColorDelta, reduceCircularReferences } from "./utils";
13
-
14
- import type * as interfaces from "../../interfaces";
15
-
16
- // TODO: Should by dynamic/configure-able.
17
- const MAX_MAPPING_RECURSIVE_DEPTH = 4,
18
- UNKNOWN_CALLER_NAME = "anonymous function",
19
- MAX_COLOR_ATTEMPTS = 25, // Stop color generation from looping forever when palette is saturated.
20
- FALLBACK_PALETTE = [
21
- "#EF4444", // red-500
22
- "#F59E0B", // amber-500
23
- "#10B981", // emerald-500
24
- "#3B82F6", // blue-500
25
- "#6366F1", // indigo-500
26
- "#EC4899", // pink-500
27
- "#8B5CF6", // violet-500
28
- "#14B8A6", // teal-500
29
- "#F97316", // orange-500
30
- "#A855F7", // purple-500
31
- "#22D3EE", // cyan-400
32
- "#84CC16", // lime-500
33
- ]; // Predefined distinct colors for guaranteed fallback.
34
-
35
- // TODO: Should by dynamic/configure-able.
36
- Error.stackTraceLimit = 50;
37
-
38
- export abstract class LoggerBrowserInfra extends ObjectBase {
39
- public static mappers: Function[] = [];
40
- public static mapperDepth = 0;
41
-
42
- public static colorsOwners: { [ key: string ]: string } = {};
43
- public static colorsUsed: string[] = [];
44
-
45
- public defaultStyle: string[];
46
-
47
- protected readonly owner: ObjectBase | typeof ObjectBase | string;
48
-
49
- protected args: {
50
- repeatedly: boolean;
51
- };
52
-
53
- protected color: string;
54
-
55
- private outputHandler: Function = console.log;
56
-
57
- public static getName() {
58
- return "ZenFlux/Logging/Modules/LoggerBrowserInfra";
59
- }
60
-
61
- /**
62
- * Reset logger globals.
63
- */
64
- public static reset() {
65
- LoggerBrowserInfra.mappers = [];
66
- LoggerBrowserInfra.mapperDepth = 0;
67
- LoggerBrowserInfra.colorsUsed = [];
68
- LoggerBrowserInfra.colorsOwners = {};
69
- }
70
-
71
- /**
72
- * Creates a custom mapper for a specific class type.
73
- *
74
- * The mapper is a callback function that can modify or enhance objects mapping.
75
- */
76
- public static createObjectMapper( callback: Function ) {
77
- LoggerBrowserInfra.mappers.push( callback );
78
- }
79
-
80
- /**
81
- * Gets mapped version of the object by using custom created object mapper.
82
- */
83
- public static useObjectMapper( obj: object, shouldHandleChildren = true ) {
84
- if ( ! obj || Array.isArray( obj ) || "object" !== typeof obj ) {
85
- return obj;
86
- }
87
-
88
- LoggerBrowserInfra.mapperDepth++;
89
-
90
- // Result will lose typeof(obj), instanceOf will not work, now based on callback.
91
- let result = { ... obj } as { [ key: string ]: any };
92
-
93
- // Run all mappers.
94
- LoggerBrowserInfra.mappers.forEach( ( mapper ) => {
95
- result = mapper( obj ) || result;
96
- } );
97
-
98
- // Prevent infinite recursive.
99
- if ( LoggerBrowserInfra.mapperDepth >= MAX_MAPPING_RECURSIVE_DEPTH ) {
100
- LoggerBrowserInfra.mapperDepth--;
101
- return result;
102
- }
103
-
104
- // Children handling.
105
- if ( shouldHandleChildren && result ) {
106
- Object.entries( result ).forEach( ( [ key, value ] ) => {
107
- result[ key ] = this.useObjectMapper( value, true );
108
- } );
109
- }
110
-
111
- LoggerBrowserInfra.mapperDepth--;
112
-
113
- return result;
114
- }
115
-
116
- public constructor( owner: ObjectBase | typeof ObjectBase | string, args = {} ) {
117
- super();
118
-
119
- this.args = {
120
- repeatedly: false,
121
-
122
- ... args,
123
- };
124
-
125
- this.owner = owner;
126
-
127
- this.initialize();
128
- }
129
-
130
- protected getOwnerName() {
131
- if ( typeof this.owner === "string" ) {
132
- return this.owner;
133
- }
134
-
135
- if ( this.owner instanceof ObjectBase ) {
136
- return this.owner.getName();
137
- }
138
-
139
- if ( this.owner && typeof ( this.owner as typeof ObjectBase ).getName === "function" ) {
140
- return ( this.owner as typeof ObjectBase ).getName();
141
- }
142
-
143
- return "UnknownOwner";
144
- }
145
-
146
- protected initialize() {
147
- const ownerName = this.getOwnerName();
148
-
149
- if ( this.args.repeatedly && LoggerBrowserInfra.colorsOwners[ ownerName ] ) {
150
- this.color = LoggerBrowserInfra.colorsOwners[ ownerName ];
151
- } else {
152
- this.color = this.getRandomColor();
153
-
154
- LoggerBrowserInfra.colorsUsed.push( this.color );
155
- }
156
-
157
- LoggerBrowserInfra.colorsOwners[ ownerName ] = this.color;
158
-
159
- this.defaultStyle = [
160
- "color: grey;font-size:7px",
161
- "display: block",
162
- `color: ${ this.color }`,
163
- "color: grey",
164
- "font-weight: bold",
165
- "color: #607D8B",
166
- "font-size: 16px;color: red;font-weight:800",
167
- ];
168
- }
169
-
170
- public output( ... args: any ) {
171
- this.outputHandler.apply( this, args );
172
- }
173
-
174
- protected setOutputHandler( outputHandler: Function ) {
175
- this.outputHandler = outputHandler;
176
- }
177
-
178
- protected printFunctionNotify( prefix: string, caller: interfaces.TCaller, output: any ) {
179
- const callerName = this.getCallerName( caller );
180
-
181
- this.output.apply(
182
- this,
183
- [ `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c() ${ output }%c` ].concat(
184
- this.defaultStyle
185
- )
186
- );
187
- }
188
-
189
- protected printObjectEfficient( prefix: string, caller: interfaces.TCaller, params: string|object ) {
190
- params = Object.assign( {}, params );
191
-
192
- if ( typeof params === "string" ) {
193
- this.printInLineString( prefix, caller, params );
194
-
195
- return;
196
- }
197
-
198
- if ( Object.keys( params ).length === 1 ) {
199
- const key = Object.keys( params )[ 0 ];
200
- let value = Object.values( params )[ 0 ];
201
-
202
- // TODO: Check is repeated logic, handle it.
203
- if ( "object" === typeof value ) {
204
- this.printInNextLineObject( prefix, caller, key, value || {} );
205
- } else if ( "function" === typeof value ) {
206
- this.printInLineFunction( prefix, caller, key, value );
207
- } else {
208
- this.printInLineElement( prefix, caller, key, value );
209
- }
210
-
211
- return;
212
- }
213
-
214
- this.printMultiLineObject( prefix, caller, params as any );
215
- }
216
-
217
- protected printInLineElement( prefix: string, caller: interfaces.TCaller, key: string, value: any, notice = "" ) {
218
- const callerName = this.getCallerName( caller ),
219
- ownerName = this.getOwnerName(),
220
- format = notice.length ?
221
- `%c(${ prefix })-> %c%c${ ownerName }%c::%c${ callerName }%c() ->> [${ notice }] ->> ${ key }: '${ value }'%c` :
222
- `%c(${ prefix })-> %c%c${ ownerName }%c::%c${ callerName }%c() ->> ${ key }: '${ value }'%c`;
223
-
224
- this.output.apply( this, [ format ].concat( this.defaultStyle ) );
225
- }
226
-
227
- protected printInLineFunction( prefix: string, caller: interfaces.TCaller, key: string, fn: string | Function ) {
228
- fn = this.getFunctionView( fn );
229
-
230
- this.printInLineElement( prefix, caller, key, fn );
231
- }
232
-
233
- protected printInLineString( prefix: string, caller: interfaces.TCaller, string: string ) {
234
- this.printInLineElement( prefix, caller, "(string)", string );
235
- }
236
-
237
- protected printInNextLineObject( prefix: string, caller: interfaces.TCaller, key: string, obj: object ) {
238
- const mapped = LoggerBrowserInfra.useObjectMapper( obj ),
239
- callerName = this.getCallerName( caller );
240
-
241
- this.output.apply(
242
- this,
243
- [
244
- `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c() ->> ${ key } %c↓`,
245
- ].concat( this.defaultStyle )
246
- );
247
-
248
- // print in next line
249
- this.output( mapped );
250
- }
251
-
252
- protected printMultiLineObject( prefix: string, caller: interfaces.TCaller, obj: { [ key: string ]: string | Function } ) {
253
- const callerName = this.getCallerName( caller );
254
-
255
- this.output.apply(
256
- this,
257
- [
258
- `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c(${ Object.keys( obj )
259
- .join( ", " ) }) %c↓`,
260
- ].concat( this.defaultStyle )
261
- );
262
-
263
- for ( let key in obj ) {
264
- let value = obj[ key ];
265
-
266
- if ( typeof value === "object" ) {
267
- const mapped = LoggerBrowserInfra.useObjectMapper( value );
268
-
269
- value = JSON.stringify( mapped, reduceCircularReferences() );
270
- } else if ( typeof obj[ key ] == "function" ) {
271
- value = this.getFunctionView( value );
272
- }
273
-
274
- this.output.apply( this, [
275
- "%c" + key + ": `" + value + "`",
276
- "color: #a3a3a3",
277
- ] );
278
- }
279
- }
280
-
281
- private getRandomColor(): string {
282
- const hex = "0123456789ABCDEF";
283
- let attempt = 0;
284
- let similarityThreshold = 0.8;
285
- let lastTried = "#000000";
286
-
287
- while ( attempt < MAX_COLOR_ATTEMPTS ) {
288
- let color = "#";
289
-
290
- for ( let i = 0 ; i < 6 ; i++ ) {
291
- color += hex[ Math.floor( Math.random() * 16 ) ];
292
- }
293
-
294
- lastTried = color;
295
-
296
- const similar = LoggerBrowserInfra.colorsUsed.some( ( value ) => {
297
- // it returns the ratio of difference... closer to 1.0 is less difference.
298
- return getHexColorDelta( color, value ) >= similarityThreshold;
299
- } );
300
-
301
- if ( ! similar ) {
302
- return color;
303
- }
304
-
305
- attempt++;
306
-
307
- // Gradually relax the threshold to guarantee termination if palette is crowded.
308
- if ( attempt % 5 === 0 && similarityThreshold > 0.6 ) {
309
- similarityThreshold -= 0.05;
310
- }
311
- }
312
-
313
- // Fallback: pick a color from a predefined palette to guarantee termination.
314
- // Prefer an unused palette color; otherwise reuse by index to preserve determinism.
315
- const unusedPaletteColor = FALLBACK_PALETTE.find( ( paletteColor ) => {
316
- return ! LoggerBrowserInfra.colorsUsed.includes( paletteColor );
317
- } );
318
-
319
- if ( unusedPaletteColor ) {
320
- return unusedPaletteColor;
321
- }
322
-
323
- return FALLBACK_PALETTE[ LoggerBrowserInfra.colorsUsed.length % FALLBACK_PALETTE.length ] || lastTried;
324
- }
325
-
326
- protected getCallerName( caller: interfaces.TCaller ) {
327
- if ( "function" === typeof caller ) {
328
- return caller.prototype instanceof ObjectBase ? "constructor" : caller.name;
329
- }
330
-
331
- throw new Error( "Invalid caller" );
332
- }
333
-
334
- private getFunctionView( fn: string | Function ): ( string | Function ) {
335
- let fReturn = UNKNOWN_CALLER_NAME;
336
-
337
- // TODO: Check if needed.
338
- if ( typeof fn !== "string" && fn.name.length !== 0 ) {
339
- fReturn = fn.name.split( " " )[ 1 ] + "()";
340
- }
341
-
342
- return fReturn;
343
- }
344
- }
@@ -1,15 +0,0 @@
1
- declare module "picocolors" {
2
- const pc: {
3
- ( input: string ): string;
4
- red( input: string ): string;
5
- blue( input: string ): string;
6
- green( input: string ): string;
7
- yellow( input: string ): string;
8
- gray( input: string ): string;
9
- white( input: string ): string;
10
- bold( input: string ): string;
11
- };
12
-
13
- export default pc;
14
- }
15
-
@@ -1,3 +0,0 @@
1
- export * from "./object";
2
- export * from "./rgb";
3
-
@@ -1,19 +0,0 @@
1
- /**
2
- * Reduce circular references.
3
- *
4
- * @copyright https://stackoverflow.com/a/53731154
5
- */
6
- export const reduceCircularReferences = () => {
7
- const seen = new WeakSet();
8
-
9
- return ( key: any, value: any ) => {
10
- if ( typeof value === "object" && value !== null ) {
11
- if ( seen.has( value ) ) {
12
- return;
13
- }
14
- seen.add( value );
15
- }
16
- return value;
17
- };
18
- };
19
-
@@ -1,34 +0,0 @@
1
- /**
2
- * Function hexColorDelta() : Return color difference in ratio decimal point.
3
- *
4
- * @copyright http://jsfiddle.net/96sME/
5
- */
6
- export const getHexColorDelta = function ( hex1: string, hex2: string ): number {
7
- hex1 = hex1.replace( "#", "" );
8
- hex2 = hex2.replace( "#", "" );
9
-
10
- // Get red/green/blue int values of hex1
11
- const r1 = parseInt( hex1.substring( 0, 2 ), 16 );
12
- const g1 = parseInt( hex1.substring( 2, 4 ), 16 );
13
- const b1 = parseInt( hex1.substring( 4, 6 ), 16 );
14
-
15
- // Get red/green/blue int values of hex2
16
- const r2 = parseInt( hex2.substring( 0, 2 ), 16 );
17
- const g2 = parseInt( hex2.substring( 2, 4 ), 16 );
18
- const b2 = parseInt( hex2.substring( 4, 6 ), 16 );
19
-
20
- // Calculate differences between reds, greens and blues
21
- let r = 255 - Math.abs( r1 - r2 );
22
- let g = 255 - Math.abs( g1 - g2 );
23
- let b = 255 - Math.abs( b1 - b2 );
24
-
25
- // Limit differences between 0 and 1
26
-
27
- r /= 255;
28
- g /= 255;
29
- b /= 255;
30
-
31
- // 0 means opposite colors, 1 means same colors
32
- return ( r + g + b ) / 3;
33
- };
34
-
@@ -1,139 +0,0 @@
1
- import { FastMCP } from "fastmcp";
2
- import { z } from "zod";
3
-
4
- import { ObjectBase } from "../../bases";
5
-
6
- // Keep logs in memory (simple approach)
7
- const MAX_LOGS = 5000; // Define a maximum number of logs to store
8
- const logs: any[] = [];
9
-
10
- export class McpServer extends ObjectBase {
11
- private server: FastMCP;
12
-
13
- public static getName(): string {
14
- return "ZenFlux/Core/Modules/McpServer";
15
- }
16
-
17
- public constructor() {
18
- super();
19
-
20
- this.server = new FastMCP( {
21
- name: "ZenfluxBackendLogger",
22
- version: "0.1.0",
23
- } );
24
-
25
- this.defineMcpTools();
26
- }
27
-
28
- private defineMcpTools(): void {
29
- // Define the getRecentLogs tool using the fastmcp API
30
- this.server.addTool( {
31
- name: "getRecentLogs",
32
- description: "Retrieves the most recent logs received by the MCP server, optionally filtered by time range.",
33
- parameters: z.object( {
34
- limit: z.number().optional().default( 50 ).describe( "Maximum number of logs to return" ),
35
- startTime: z.number().optional().describe( "Optional start timestamp (ms) to filter logs after" ),
36
- endTime: z.number().optional().describe( "Optional end timestamp (ms) to filter logs before" ),
37
- } ),
38
- execute: async( args ) => {
39
- const { limit, startTime, endTime } = args;
40
-
41
- // Get initial slice based on limit (most recent)
42
- let recentLogs = logs.slice( -limit );
43
-
44
- // Apply time filters if provided
45
- if ( startTime ) {
46
- recentLogs = recentLogs.filter( log => log.timestamp >= startTime );
47
- }
48
- if ( endTime ) {
49
- recentLogs = recentLogs.filter( log => log.timestamp <= endTime );
50
- }
51
-
52
- return JSON.stringify( recentLogs, null, 2 );
53
- },
54
- } );
55
-
56
- // Define the getLogsInfo tool
57
- this.server.addTool( {
58
- name: "getLogsInfo",
59
- description: "Provides information about stored logs, including count, and first/last timestamps.",
60
- parameters: z.object( {} ), // No parameters
61
- execute: async() => {
62
- const logCount = logs.length;
63
- const firstTimestamp = logCount > 0 ? logs[ 0 ]?.timestamp : null;
64
- const lastTimestamp = logCount > 0 ? logs[ logCount - 1 ]?.timestamp : null;
65
-
66
- const info = {
67
- logCount,
68
- firstTimestamp,
69
- lastTimestamp
70
- };
71
- return JSON.stringify( info, null, 2 );
72
- },
73
- } );
74
-
75
- // Define the getLogsRange tool
76
- this.server.addTool( {
77
- name: "getLogsRange",
78
- description: "Retrieves logs within a specific time range.",
79
- parameters: z.object( {
80
- startTime: z.number().describe( "Required start timestamp (ms) to filter logs after" ),
81
- endTime: z.number().describe( "Required end timestamp (ms) to filter logs before" ),
82
- } ),
83
- execute: async( args ) => {
84
- const { startTime, endTime } = args;
85
-
86
- // Validate timestamps
87
- if ( startTime >= endTime ) {
88
- throw new Error( "Start time must be before end time." );
89
- }
90
-
91
- const filteredLogs = logs.filter( log =>
92
- log.timestamp >= startTime && log.timestamp <= endTime
93
- );
94
-
95
- // Consider adding a safety limit here if the range could be huge
96
- // const MAX_RANGE_RESULTS = 1000;
97
- // if (filteredLogs.length > MAX_RANGE_RESULTS) {
98
- // throw new Error(`Log range too large (${filteredLogs.length} logs). Maximum allowed: ${MAX_RANGE_RESULTS}`);
99
- // }
100
-
101
- return JSON.stringify( filteredLogs, null, 2 );
102
- },
103
- } );
104
-
105
- console.log( "MCP Tools defined: getRecentLogs, getLogsInfo, getLogsRange" );
106
- }
107
-
108
- // Start the fastmcp server
109
- public async start( port: number = 3000, host: string = "0.0.0.0" ): Promise<void> {
110
- try {
111
- // Removed server name from log as config access is different
112
- console.log( "Attempting to start fastmcp server..." );
113
- await this.server.start( {
114
- transportType: "httpStream", // Explicitly use SSE
115
- httpStream: {
116
- port,
117
- host,
118
- endpoint: "/mcp" // Standard MCP endpoint
119
- }
120
- } );
121
- } catch ( err ) {
122
- console.error( "Error starting fastmcp server:", err );
123
- process.exit( 1 );
124
- }
125
- }
126
-
127
- // Stop the fastmcp server
128
- public async stop(): Promise<void> {
129
- console.log( "Stopping fastmcp server..." );
130
- }
131
-
132
- // Method to add a log entry, now with capping
133
- public addLog( logEntry: any ): void {
134
- if ( logs.length >= MAX_LOGS ) {
135
- logs.shift(); // Remove the oldest log if the limit is reached
136
- }
137
- logs.push( logEntry );
138
- }
139
- }
@@ -1,80 +0,0 @@
1
- import { McpServer } from "./mcp-server";
2
-
3
- import { EventBus } from "../event-bus/event-bus";
4
-
5
- import { ServiceBase } from "../service/service-base";
6
-
7
- // TODO: Get port/host from configuration/environment variables
8
- const MCP_PORT = 3090;
9
- const MCP_HOST = "0.0.0.0";
10
-
11
- export class MCPService extends ServiceBase {
12
- private static mcpServer: McpServer;
13
-
14
- public static getName(): string {
15
- return "ZenFlux/Core/Modules/MCPService";
16
- }
17
-
18
- public constructor() {
19
- super();
20
-
21
- // Initialization logic is handled in the initialize method by ServiceBase
22
- }
23
-
24
- protected async initialize(): Promise<void> {
25
- this.logger.log( this.initialize, "Initializing MCP Service..." );
26
-
27
- try {
28
- MCPService.mcpServer = new McpServer();
29
-
30
- // Start the MCP server (Fastify instance)
31
- // Consider adding error handling or status checking
32
- await MCPService.mcpServer.start( MCP_PORT, MCP_HOST );
33
-
34
- EventBus.$.on( "ZenFlux/Core/Modules/Logger", "outputInternal", this.onLoggerOutput.bind( this ) );
35
-
36
- this.logger.info( this.initialize, `MCP Server started on http://${ MCP_HOST }:${ MCP_PORT }` );
37
- } catch ( error ) {
38
- this.logger.error( this.initialize, "Failed to start MCP Server", error );
39
- // Rethrow or handle appropriately - ServiceBase might catch this
40
- throw error;
41
- }
42
- }
43
-
44
- /**
45
- * Optional: Add a method to explicitly stop the server if needed.
46
- * ServiceBase doesn't seem to have a standard shutdown hook, so manual call might be necessary.
47
- */
48
- public async stopServer(): Promise<void> {
49
- if ( MCPService.mcpServer ) {
50
- this.logger.log( this.stopServer, "Stopping MCP Server..." );
51
- await MCPService.mcpServer.stop();
52
- this.logger.info( this.stopServer, "MCP Server stopped." );
53
- }
54
- }
55
-
56
- // You can add methods here to interact with McpServer if needed,
57
- // e.g., retrieving logs or status, although tools will likely handle log retrieval.
58
- private onLoggerOutput( prefix: string, timeDiff: string, source: string, messagePrefix: string, message: string, params: any[] ) {
59
- // Create a log entry with all the relevant information
60
- const logEntry = {
61
- timestamp: new Date().getTime(),
62
- prefix,
63
- timeDiff,
64
- source,
65
- messagePrefix,
66
- message,
67
- params: params && params.length ? params : [],
68
- formatted: `${ prefix }[+${ timeDiff }ms][${ source }]${ messagePrefix }: ${ message }`
69
- };
70
-
71
- if ( MCPService.mcpServer ) {
72
- // Call the addLog method directly on the static McpServer instance
73
- try {
74
- MCPService.mcpServer.addLog( logEntry );
75
- } catch ( error ) {
76
- console.error( "MCPService.onLoggerOutput: Failed to add log via addLog method:", error );
77
- }
78
- }
79
- }
80
- }
@@ -1,55 +0,0 @@
1
- import { ObjectBase } from "../../bases/object-base";
2
-
3
- import { Logger } from "../logger";
4
-
5
- export abstract class ServiceBase extends ObjectBase {
6
- protected logger: Logger;
7
-
8
- private readonly initialization: {
9
- promise: Promise<void>;
10
- state: "pending" | "resolved" | "rejected";
11
- reason?: Error;
12
- };
13
-
14
- public static getName(): string {
15
- return "ZenFlux/Core/Modules/ServiceBase";
16
- }
17
-
18
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
19
- public constructor( ...args: any[] ) {
20
- super();
21
-
22
- this.logger = new Logger( this );
23
-
24
- if ( this.initialize ) {
25
- this.initialization = {
26
- promise: this.initialize(),
27
- state: "pending"
28
- };
29
-
30
- this.initialization.promise
31
- .then( () => ( this.initialization.state = "resolved" ) )
32
- .catch( ( reason ) => {
33
- this.initialization.state = "rejected";
34
- this.initialization.reason = reason;
35
- } );
36
-
37
- return;
38
- }
39
-
40
- this.initialization = {
41
- promise: Promise.resolve(),
42
- state: "resolved"
43
- };
44
- }
45
-
46
- protected async initialize?(): Promise<void>;
47
-
48
- public isWithDependencies() {
49
- return false;
50
- }
51
-
52
- public getInitialization() {
53
- return this.initialization;
54
- }
55
- }