@zenflux/core 0.1.28 → 0.1.30

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 (59) hide show
  1. package/dist/.tsconfig.probe.tsbuildinfo +1 -0
  2. package/dist/src/exports.d.ts +0 -3
  3. package/dist/src/index.d.ts +0 -5
  4. package/dist/src/modules/logger/implementation.d.ts +1 -0
  5. package/dist/zenflux-core.cjs +37 -119
  6. package/dist/zenflux-core.d.ts +3 -32
  7. package/dist/zenflux-core.mjs +38 -117
  8. package/package.json +2 -2
  9. package/src/bases/cache-base.ts +64 -0
  10. package/src/bases/controller-base.ts +96 -0
  11. package/src/bases/index.ts +9 -0
  12. package/src/bases/initialize-base.ts +32 -0
  13. package/src/bases/object-base.ts +55 -0
  14. package/src/bases/singleton-base.ts +18 -0
  15. package/src/clients/http.ts +152 -0
  16. package/src/command-bases/command-base.ts +80 -0
  17. package/src/command-bases/command-internal.ts +11 -0
  18. package/src/command-bases/command-public.ts +12 -0
  19. package/src/command-bases/command-restful.ts +55 -0
  20. package/src/command-bases/index.ts +8 -0
  21. package/src/errors/command-already-registered.ts +13 -0
  22. package/src/errors/command-not-found.ts +12 -0
  23. package/src/errors/controller-already-registered.ts +13 -0
  24. package/src/errors/controller-already-set.ts +13 -0
  25. package/src/errors/error-with-metadata.ts +29 -0
  26. package/src/errors/force-method-implementation.ts +15 -0
  27. package/src/errors/index-public.ts +1 -0
  28. package/src/errors/index.ts +10 -0
  29. package/src/exports-index.ts +15 -0
  30. package/src/exports.ts +55 -0
  31. package/src/index.ts +18 -0
  32. package/src/interfaces/commands.ts +17 -0
  33. package/src/interfaces/config.ts +23 -0
  34. package/src/interfaces/index.ts +8 -0
  35. package/src/interfaces/logger.ts +19 -0
  36. package/src/interfaces/restful.ts +23 -0
  37. package/src/managers/commands.ts +269 -0
  38. package/src/managers/controllers.ts +40 -0
  39. package/src/managers/export.ts +30 -0
  40. package/src/managers/index.ts +8 -0
  41. package/src/managers/internal.ts +11 -0
  42. package/src/managers/restful.ts +117 -0
  43. package/src/modules/debugger.ts +86 -0
  44. package/src/modules/event-bus/event-bus.ts +238 -0
  45. package/src/modules/export.ts +6 -0
  46. package/src/modules/logger/config.ts +66 -0
  47. package/src/modules/logger/create-logger.ts +38 -0
  48. package/src/modules/logger/implementation.ts +371 -0
  49. package/src/modules/logger/index.ts +3 -0
  50. package/src/modules/logger/logger-browser-infra.ts +364 -0
  51. package/src/modules/logger/types/picocolors.d.ts +15 -0
  52. package/src/modules/logger/utils/index.ts +3 -0
  53. package/src/modules/logger/utils/object.ts +19 -0
  54. package/src/modules/logger/utils/rgb.ts +34 -0
  55. package/src/modules/mcp-server/mcp-server.ts +139 -0
  56. package/src/modules/mcp-server/mcp-service.ts +80 -0
  57. package/src/modules/service/service-base.ts +55 -0
  58. package/src/modules/service/service-locator.ts +205 -0
  59. package/src/modules/service/service-with-dependencies-base.ts +51 -0
@@ -0,0 +1,364 @@
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 { reduceCircularReferences } from "./utils";
11
+
12
+ import { ObjectBase } from "../../bases/object-base";
13
+
14
+ import type * as interfaces from "../../interfaces";
15
+
16
+ export type LoggerOutputLevel = "log" | "info" | "debug" | "warn" | "error" | "admin";
17
+
18
+ export interface LoggerOutputFormat {
19
+ format: string;
20
+ styles: string[];
21
+ }
22
+
23
+ export interface LoggerOutputMetadata {
24
+ id?: string;
25
+ level?: LoggerOutputLevel;
26
+ namespace?: string;
27
+ callerName?: string;
28
+ message?: string;
29
+ messagePrefix?: string;
30
+ payload?: unknown;
31
+ timestamp?: number;
32
+ formatted?: LoggerOutputFormat;
33
+ }
34
+
35
+ export interface LoggerOutputEvent {
36
+ logger: LoggerBrowserInfra;
37
+ namespace: string;
38
+ args: any[];
39
+ metadata?: LoggerOutputMetadata;
40
+ }
41
+
42
+ export type LoggerOutputSubscriber = ( event: LoggerOutputEvent ) => void;
43
+
44
+ // TODO: Should by dynamic/configure-able.
45
+ const MAX_MAPPING_RECURSIVE_DEPTH = 4,
46
+ UNKNOWN_CALLER_NAME = "anonymous function";
47
+
48
+ // TODO: Should by dynamic/configure-able.
49
+ Error.stackTraceLimit = 50;
50
+
51
+ export abstract class LoggerBrowserInfra extends ObjectBase {
52
+ public static mappers: Function[] = [];
53
+ public static mapperDepth = 0;
54
+
55
+ public static colorsOwners: { [ key: string ]: string } = {};
56
+ public static colorsUsed: string[] = [];
57
+
58
+ private static outputSubscribers = new Set<LoggerOutputSubscriber>();
59
+
60
+ public defaultStyle: string[];
61
+
62
+ protected readonly owner: ObjectBase | typeof ObjectBase | string;
63
+
64
+ protected args: {
65
+ repeatedly: boolean;
66
+ };
67
+
68
+ protected color: string;
69
+
70
+ private outputHandler: Function = console.log;
71
+ private pendingOutputMetadata?: LoggerOutputMetadata;
72
+
73
+ public static getName() {
74
+ return "ZenFlux/Logging/Modules/LoggerBrowserInfra";
75
+ }
76
+
77
+ /**
78
+ * Reset logger globals.
79
+ */
80
+ public static reset() {
81
+ LoggerBrowserInfra.mappers = [];
82
+ LoggerBrowserInfra.mapperDepth = 0;
83
+ LoggerBrowserInfra.colorsUsed = [];
84
+ LoggerBrowserInfra.colorsOwners = {};
85
+ LoggerBrowserInfra.outputSubscribers.clear();
86
+ }
87
+
88
+ public static attachOutputSubscriber( subscriber: LoggerOutputSubscriber ) {
89
+ LoggerBrowserInfra.outputSubscribers.add( subscriber );
90
+
91
+ return () => {
92
+ LoggerBrowserInfra.outputSubscribers.delete( subscriber );
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Creates a custom mapper for a specific class type.
98
+ *
99
+ * The mapper is a callback function that can modify or enhance objects mapping.
100
+ */
101
+ public static createObjectMapper( callback: Function ) {
102
+ LoggerBrowserInfra.mappers.push( callback );
103
+ }
104
+
105
+ /**
106
+ * Gets mapped version of the object by using custom created object mapper.
107
+ */
108
+ public static useObjectMapper( obj: object, shouldHandleChildren = true ) {
109
+ if ( ! obj || Array.isArray( obj ) || "object" !== typeof obj ) {
110
+ return obj;
111
+ }
112
+
113
+ LoggerBrowserInfra.mapperDepth++;
114
+
115
+ // Result will lose typeof(obj), instanceOf will not work, now based on callback.
116
+ let result = { ... obj } as { [ key: string ]: any };
117
+
118
+ // Run all mappers.
119
+ LoggerBrowserInfra.mappers.forEach( ( mapper ) => {
120
+ result = mapper( obj ) || result;
121
+ } );
122
+
123
+ // Prevent infinite recursive.
124
+ if ( LoggerBrowserInfra.mapperDepth >= MAX_MAPPING_RECURSIVE_DEPTH ) {
125
+ LoggerBrowserInfra.mapperDepth--;
126
+ return result;
127
+ }
128
+
129
+ // Children handling.
130
+ if ( shouldHandleChildren && result ) {
131
+ Object.entries( result ).forEach( ( [ key, value ] ) => {
132
+ result[ key ] = this.useObjectMapper( value, true );
133
+ } );
134
+ }
135
+
136
+ LoggerBrowserInfra.mapperDepth--;
137
+
138
+ return result;
139
+ }
140
+
141
+ public constructor( owner: ObjectBase | typeof ObjectBase | string, args = {} ) {
142
+ super();
143
+
144
+ this.args = {
145
+ repeatedly: false,
146
+
147
+ ... args,
148
+ };
149
+
150
+ this.owner = owner;
151
+
152
+ this.initialize();
153
+ }
154
+
155
+ protected getOwnerName() {
156
+ if ( typeof this.owner === "string" ) {
157
+ return this.owner;
158
+ }
159
+
160
+ if ( this.owner instanceof ObjectBase ) {
161
+ return this.owner.getName();
162
+ }
163
+
164
+ if ( this.owner && typeof ( this.owner as typeof ObjectBase ).getName === "function" ) {
165
+ return ( this.owner as typeof ObjectBase ).getName();
166
+ }
167
+
168
+ return "UnknownOwner";
169
+ }
170
+
171
+ protected initialize() {
172
+ const ownerName = this.getOwnerName();
173
+
174
+ if ( this.args.repeatedly && LoggerBrowserInfra.colorsOwners[ ownerName ] ) {
175
+ this.color = LoggerBrowserInfra.colorsOwners[ ownerName ];
176
+ } else {
177
+ this.color = this.getRandomColor();
178
+ }
179
+
180
+ LoggerBrowserInfra.colorsOwners[ ownerName ] = this.color;
181
+
182
+ this.defaultStyle = [
183
+ "color: grey;font-size:7px",
184
+ "display: block",
185
+ `color: ${ this.color }`,
186
+ "color: grey",
187
+ "font-weight: bold",
188
+ "color: #607D8B",
189
+ "font-size: 16px;color: red;font-weight:800",
190
+ ];
191
+ }
192
+
193
+ public output( ... args: any ) {
194
+ this.outputHandler.apply( this, args );
195
+
196
+ if ( LoggerBrowserInfra.outputSubscribers.size === 0 ) {
197
+ return;
198
+ }
199
+
200
+ const event: LoggerOutputEvent = {
201
+ logger: this,
202
+ namespace: this.getOwnerName(),
203
+ args,
204
+ metadata: this.pendingOutputMetadata,
205
+ };
206
+
207
+ LoggerBrowserInfra.outputSubscribers.forEach( ( subscriber ) => {
208
+ try {
209
+ subscriber( event );
210
+ } catch( error ) {
211
+
212
+ console.error( "[ZenFlux][Logger] output subscriber failed", error );
213
+ }
214
+ } );
215
+ }
216
+
217
+ protected setOutputHandler( outputHandler: Function ) {
218
+ this.outputHandler = outputHandler;
219
+ }
220
+
221
+ protected runWithOutputMetadata<T>( metadata: LoggerOutputMetadata | undefined, callback: () => T ): T {
222
+ const previous = this.pendingOutputMetadata;
223
+ this.pendingOutputMetadata = metadata;
224
+
225
+ try {
226
+ return callback();
227
+ } finally {
228
+ this.pendingOutputMetadata = previous;
229
+ }
230
+ }
231
+
232
+ protected printFunctionNotify( prefix: string, caller: interfaces.TCaller, output: any ) {
233
+ const callerName = this.getCallerName( caller );
234
+
235
+ this.output.apply(
236
+ this,
237
+ [ `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c() ${ output }%c` ].concat(
238
+ this.defaultStyle
239
+ )
240
+ );
241
+ }
242
+
243
+ protected printObjectEfficient( prefix: string, caller: interfaces.TCaller, params: string|object ) {
244
+ params = Object.assign( {}, params );
245
+
246
+ if ( typeof params === "string" ) {
247
+ this.printInLineString( prefix, caller, params );
248
+
249
+ return;
250
+ }
251
+
252
+ if ( Object.keys( params ).length === 1 ) {
253
+ const key = Object.keys( params )[ 0 ];
254
+ let value = Object.values( params )[ 0 ];
255
+
256
+ // TODO: Check is repeated logic, handle it.
257
+ if ( "object" === typeof value ) {
258
+ this.printInNextLineObject( prefix, caller, key, value || {} );
259
+ } else if ( "function" === typeof value ) {
260
+ this.printInLineFunction( prefix, caller, key, value );
261
+ } else {
262
+ this.printInLineElement( prefix, caller, key, value );
263
+ }
264
+
265
+ return;
266
+ }
267
+
268
+ this.printMultiLineObject( prefix, caller, params as any );
269
+ }
270
+
271
+ protected printInLineElement( prefix: string, caller: interfaces.TCaller, key: string, value: any, notice = "" ) {
272
+ const callerName = this.getCallerName( caller ),
273
+ ownerName = this.getOwnerName(),
274
+ format = notice.length ?
275
+ `%c(${ prefix })-> %c%c${ ownerName }%c::%c${ callerName }%c() ->> [${ notice }] ->> ${ key }: '${ value }'%c` :
276
+ `%c(${ prefix })-> %c%c${ ownerName }%c::%c${ callerName }%c() ->> ${ key }: '${ value }'%c`;
277
+
278
+ this.output.apply( this, [ format ].concat( this.defaultStyle ) );
279
+ }
280
+
281
+ protected printInLineFunction( prefix: string, caller: interfaces.TCaller, key: string, fn: string | Function ) {
282
+ fn = this.getFunctionView( fn );
283
+
284
+ this.printInLineElement( prefix, caller, key, fn );
285
+ }
286
+
287
+ protected printInLineString( prefix: string, caller: interfaces.TCaller, string: string ) {
288
+ this.printInLineElement( prefix, caller, "(string)", string );
289
+ }
290
+
291
+ protected printInNextLineObject( prefix: string, caller: interfaces.TCaller, key: string, obj: object ) {
292
+ const mapped = LoggerBrowserInfra.useObjectMapper( obj ),
293
+ callerName = this.getCallerName( caller );
294
+
295
+ this.output.apply(
296
+ this,
297
+ [
298
+ `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c() ->> ${ key } %c↓`,
299
+ ].concat( this.defaultStyle )
300
+ );
301
+
302
+ // print in next line
303
+ this.output( mapped );
304
+ }
305
+
306
+ protected printMultiLineObject( prefix: string, caller: interfaces.TCaller, obj: { [ key: string ]: string | Function } ) {
307
+ const callerName = this.getCallerName( caller );
308
+
309
+ this.output.apply(
310
+ this,
311
+ [
312
+ `%c(${ prefix })-> %c%c${ this.getOwnerName() }%c::%c${ callerName }%c(${ Object.keys( obj )
313
+ .join( ", " ) }) %c↓`,
314
+ ].concat( this.defaultStyle )
315
+ );
316
+
317
+ for ( let key in obj ) {
318
+ let value = obj[ key ];
319
+
320
+ if ( typeof value === "object" ) {
321
+ const mapped = LoggerBrowserInfra.useObjectMapper( value );
322
+
323
+ value = JSON.stringify( mapped, reduceCircularReferences() );
324
+ } else if ( typeof obj[ key ] == "function" ) {
325
+ value = this.getFunctionView( value );
326
+ }
327
+
328
+ this.output.apply( this, [
329
+ "%c" + key + ": `" + value + "`",
330
+ "color: #a3a3a3",
331
+ ] );
332
+ }
333
+ }
334
+
335
+ private getRandomColor(): string {
336
+ const hex = "0123456789ABCDEF";
337
+ let color = "#";
338
+
339
+ for ( let i = 0 ; i < 6 ; i++ ) {
340
+ color += hex[ Math.floor( Math.random() * 16 ) ];
341
+ }
342
+
343
+ return color;
344
+ }
345
+
346
+ protected getCallerName( caller: interfaces.TCaller ) {
347
+ if ( "function" === typeof caller ) {
348
+ return caller.prototype instanceof ObjectBase ? "constructor" : caller.name;
349
+ }
350
+
351
+ throw new Error( "Invalid caller" );
352
+ }
353
+
354
+ private getFunctionView( fn: string | Function ): ( string | Function ) {
355
+ let fReturn = UNKNOWN_CALLER_NAME;
356
+
357
+ // TODO: Check if needed.
358
+ if ( typeof fn !== "string" && fn.name.length !== 0 ) {
359
+ fReturn = fn.name.split( " " )[ 1 ] + "()";
360
+ }
361
+
362
+ return fReturn;
363
+ }
364
+ }
@@ -0,0 +1,15 @@
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
+
@@ -0,0 +1,3 @@
1
+ export * from "./object";
2
+ export * from "./rgb";
3
+
@@ -0,0 +1,19 @@
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
+
@@ -0,0 +1,34 @@
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
+
@@ -0,0 +1,139 @@
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
+ }
@@ -0,0 +1,80 @@
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
+ }