claude-mem 3.0.2 → 3.0.4

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 (56) hide show
  1. package/.mcp.json +11 -0
  2. package/claude-mem +0 -0
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +64 -0
  5. package/dist/commands/compress.d.ts +2 -0
  6. package/dist/commands/compress.js +59 -0
  7. package/dist/commands/install.d.ts +2 -0
  8. package/dist/commands/install.js +372 -0
  9. package/dist/commands/load-context.d.ts +2 -0
  10. package/dist/commands/load-context.js +330 -0
  11. package/dist/commands/logs.d.ts +2 -0
  12. package/dist/commands/logs.js +41 -0
  13. package/dist/commands/migrate.d.ts +9 -0
  14. package/dist/commands/migrate.js +174 -0
  15. package/dist/commands/status.d.ts +1 -0
  16. package/dist/commands/status.js +159 -0
  17. package/dist/commands/uninstall.d.ts +2 -0
  18. package/dist/commands/uninstall.js +105 -0
  19. package/dist/config.d.ts +6 -0
  20. package/dist/config.js +33 -0
  21. package/dist/constants.d.ts +516 -0
  22. package/dist/constants.js +522 -0
  23. package/dist/error-handler.d.ts +17 -0
  24. package/dist/error-handler.js +103 -0
  25. package/dist/mcp-server-cli.d.ts +34 -0
  26. package/dist/mcp-server-cli.js +158 -0
  27. package/dist/mcp-server.d.ts +103 -0
  28. package/dist/mcp-server.js +269 -0
  29. package/dist/types.d.ts +148 -0
  30. package/dist/types.js +78 -0
  31. package/dist/utils/HookDetector.d.ts +64 -0
  32. package/dist/utils/HookDetector.js +213 -0
  33. package/dist/utils/PathResolver.d.ts +16 -0
  34. package/dist/utils/PathResolver.js +55 -0
  35. package/dist/utils/SettingsManager.d.ts +63 -0
  36. package/dist/utils/SettingsManager.js +133 -0
  37. package/dist/utils/TranscriptCompressor.d.ts +111 -0
  38. package/dist/utils/TranscriptCompressor.js +486 -0
  39. package/dist/utils/common.d.ts +29 -0
  40. package/dist/utils/common.js +14 -0
  41. package/dist/utils/error-utils.d.ts +93 -0
  42. package/dist/utils/error-utils.js +238 -0
  43. package/dist/utils/index.d.ts +19 -0
  44. package/dist/utils/index.js +26 -0
  45. package/dist/utils/logger.d.ts +19 -0
  46. package/dist/utils/logger.js +42 -0
  47. package/dist/utils/mcp-client-factory.d.ts +51 -0
  48. package/dist/utils/mcp-client-factory.js +115 -0
  49. package/dist/utils/mcp-client.d.ts +75 -0
  50. package/dist/utils/mcp-client.js +120 -0
  51. package/dist/utils/memory-mcp-client.d.ts +135 -0
  52. package/dist/utils/memory-mcp-client.js +490 -0
  53. package/dist/utils/weaviate-mcp-adapter.d.ts +102 -0
  54. package/dist/utils/weaviate-mcp-adapter.js +587 -0
  55. package/package.json +3 -2
  56. package/src/claude-mem.js +0 -859
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Error handling utilities for claude-mem
3
+ *
4
+ * Consolidates error handling patterns and JSON parsing logic
5
+ * to eliminate duplicate try-catch blocks and standardize error responses.
6
+ */
7
+ export interface CommandError {
8
+ message: string;
9
+ code?: string | number;
10
+ details?: any;
11
+ }
12
+ export interface HookErrorResponse {
13
+ continue: boolean;
14
+ stopReason?: string;
15
+ suppressOutput?: boolean;
16
+ decision?: string;
17
+ reason?: string;
18
+ }
19
+ export interface MCPError {
20
+ type: 'connection' | 'operation' | 'parsing' | 'unknown';
21
+ message: string;
22
+ originalError?: any;
23
+ }
24
+ /**
25
+ * Standardizes error handling across CLI commands and hooks
26
+ */
27
+ export declare class ErrorHandler {
28
+ /**
29
+ * Handle command-line interface errors consistently
30
+ */
31
+ static handleCommandError(error: any, context?: string): CommandError;
32
+ /**
33
+ * Handle hook errors and return proper Claude Code responses
34
+ */
35
+ static handleHookError(error: any, hookName?: string): HookErrorResponse;
36
+ /**
37
+ * Handle MCP (Model Context Protocol) specific errors
38
+ */
39
+ static handleMCPError(error: any, operation?: string): MCPError;
40
+ /**
41
+ * Create user-friendly error messages
42
+ */
43
+ static createUserError(message: string, details?: any): CommandError;
44
+ /**
45
+ * Handle errors with graceful degradation
46
+ */
47
+ static handleWithFallback<T>(operation: () => T, fallback: T, context?: string): T;
48
+ }
49
+ /**
50
+ * Safe JSON parsing utilities
51
+ * Replaces 8+ duplicate JSON parsing try-catch blocks across the codebase
52
+ */
53
+ export declare class JSONParser {
54
+ /**
55
+ * Parse JSON file safely with fallback
56
+ */
57
+ static parseFile<T = any>(filePath: string, fallback?: T): T;
58
+ /**
59
+ * Parse JSON string safely with fallback
60
+ */
61
+ static parseString<T = any>(jsonString: string, fallback?: T): T;
62
+ /**
63
+ * Stringify with consistent formatting
64
+ */
65
+ static stringify(obj: any, pretty?: boolean): string;
66
+ /**
67
+ * Validate JSON string without parsing
68
+ */
69
+ static isValidJSON(jsonString: string): boolean;
70
+ /**
71
+ * Parse with detailed error information
72
+ */
73
+ static parseWithErrorInfo<T = any>(jsonString: string): {
74
+ success: true;
75
+ data: T;
76
+ } | {
77
+ success: false;
78
+ error: string;
79
+ position?: number;
80
+ };
81
+ /**
82
+ * Parse JSONL (JSON Lines) format safely
83
+ */
84
+ static parseJSONL<T = any>(jsonlString: string): T[];
85
+ }
86
+ /**
87
+ * Safe async operation wrapper
88
+ */
89
+ export declare function safeAsync<T>(operation: () => Promise<T>, fallback: T, context?: string): Promise<T>;
90
+ /**
91
+ * Helper to exit cleanly after handling an error
92
+ */
93
+ export declare function exitWithError(error: any, context?: string): never;
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Error handling utilities for claude-mem
3
+ *
4
+ * Consolidates error handling patterns and JSON parsing logic
5
+ * to eliminate duplicate try-catch blocks and standardize error responses.
6
+ */
7
+ import { readFileSync } from 'fs';
8
+ import { log } from './logger.js';
9
+ // =============================================================================
10
+ // ERROR HANDLER CLASS
11
+ // =============================================================================
12
+ /**
13
+ * Standardizes error handling across CLI commands and hooks
14
+ */
15
+ export class ErrorHandler {
16
+ /**
17
+ * Handle command-line interface errors consistently
18
+ */
19
+ static handleCommandError(error, context) {
20
+ const prefix = context ? `❌ ${context}:` : '❌ Error:';
21
+ let message;
22
+ if (error instanceof Error) {
23
+ message = `${prefix} ${error.message}`;
24
+ }
25
+ else if (typeof error === 'string') {
26
+ message = `${prefix} ${error}`;
27
+ }
28
+ else {
29
+ message = `${prefix} An unexpected error occurred`;
30
+ }
31
+ log.error(message, error);
32
+ return {
33
+ message,
34
+ details: error
35
+ };
36
+ }
37
+ /**
38
+ * Handle hook errors and return proper Claude Code responses
39
+ */
40
+ static handleHookError(error, hookName) {
41
+ const context = hookName ? `${hookName} hook` : 'Hook';
42
+ const message = error instanceof Error ? error.message : String(error);
43
+ log.error(`${context} error: ${message}`);
44
+ return {
45
+ continue: false,
46
+ stopReason: `${context} failed: ${message}`,
47
+ suppressOutput: true
48
+ };
49
+ }
50
+ /**
51
+ * Handle MCP (Model Context Protocol) specific errors
52
+ */
53
+ static handleMCPError(error, operation) {
54
+ const context = operation ? `MCP ${operation}` : 'MCP operation';
55
+ let errorType = 'unknown';
56
+ let message = 'Unknown MCP error';
57
+ if (error instanceof Error) {
58
+ message = error.message;
59
+ // Categorize common MCP error types
60
+ if (message.includes('connect') || message.includes('connection')) {
61
+ errorType = 'connection';
62
+ }
63
+ else if (message.includes('parse') || message.includes('JSON')) {
64
+ errorType = 'parsing';
65
+ }
66
+ else if (message.includes('operation') || message.includes('call')) {
67
+ errorType = 'operation';
68
+ }
69
+ }
70
+ else if (typeof error === 'string') {
71
+ message = error;
72
+ }
73
+ const mcpError = {
74
+ type: errorType,
75
+ message: `${context} failed: ${message}`,
76
+ originalError: error
77
+ };
78
+ // Log the error
79
+ log.warning(mcpError.message);
80
+ return mcpError;
81
+ }
82
+ /**
83
+ * Create user-friendly error messages
84
+ */
85
+ static createUserError(message, details) {
86
+ return {
87
+ message,
88
+ details
89
+ };
90
+ }
91
+ /**
92
+ * Handle errors with graceful degradation
93
+ */
94
+ static handleWithFallback(operation, fallback, context) {
95
+ try {
96
+ return operation();
97
+ }
98
+ catch (error) {
99
+ if (context) {
100
+ log.warning(`${context}: ${error}. Using fallback.`);
101
+ }
102
+ return fallback;
103
+ }
104
+ }
105
+ }
106
+ // =============================================================================
107
+ // JSON PARSER CLASS
108
+ // =============================================================================
109
+ /**
110
+ * Safe JSON parsing utilities
111
+ * Replaces 8+ duplicate JSON parsing try-catch blocks across the codebase
112
+ */
113
+ export class JSONParser {
114
+ /**
115
+ * Parse JSON file safely with fallback
116
+ */
117
+ static parseFile(filePath, fallback = {}) {
118
+ try {
119
+ const content = readFileSync(filePath, 'utf8');
120
+ return JSON.parse(content);
121
+ }
122
+ catch (error) {
123
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
124
+ // File doesn't exist - this is often expected
125
+ return fallback;
126
+ }
127
+ log.warning(`Could not parse JSON file ${filePath}: ${error}`);
128
+ return fallback;
129
+ }
130
+ }
131
+ /**
132
+ * Parse JSON string safely with fallback
133
+ */
134
+ static parseString(jsonString, fallback = {}) {
135
+ try {
136
+ return JSON.parse(jsonString);
137
+ }
138
+ catch (error) {
139
+ log.warning(`Could not parse JSON string: ${error}`);
140
+ return fallback;
141
+ }
142
+ }
143
+ /**
144
+ * Stringify with consistent formatting
145
+ */
146
+ static stringify(obj, pretty = true) {
147
+ try {
148
+ return pretty ? JSON.stringify(obj, null, 2) : JSON.stringify(obj);
149
+ }
150
+ catch (error) {
151
+ throw new Error(`Failed to stringify object: ${error}`);
152
+ }
153
+ }
154
+ /**
155
+ * Validate JSON string without parsing
156
+ */
157
+ static isValidJSON(jsonString) {
158
+ try {
159
+ JSON.parse(jsonString);
160
+ return true;
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ }
166
+ /**
167
+ * Parse with detailed error information
168
+ */
169
+ static parseWithErrorInfo(jsonString) {
170
+ try {
171
+ const data = JSON.parse(jsonString);
172
+ return { success: true, data };
173
+ }
174
+ catch (error) {
175
+ let errorMessage = 'Unknown JSON parsing error';
176
+ let position;
177
+ if (error instanceof SyntaxError) {
178
+ errorMessage = error.message;
179
+ // Try to extract position from error message
180
+ const positionMatch = errorMessage.match(/position (\d+)/);
181
+ if (positionMatch) {
182
+ position = parseInt(positionMatch[1]);
183
+ }
184
+ }
185
+ return {
186
+ success: false,
187
+ error: errorMessage,
188
+ position
189
+ };
190
+ }
191
+ }
192
+ /**
193
+ * Parse JSONL (JSON Lines) format safely
194
+ */
195
+ static parseJSONL(jsonlString) {
196
+ const lines = jsonlString.trim().split('\n');
197
+ const results = [];
198
+ for (let i = 0; i < lines.length; i++) {
199
+ const line = lines[i].trim();
200
+ if (!line)
201
+ continue; // Skip empty lines
202
+ try {
203
+ const parsed = JSON.parse(line);
204
+ results.push(parsed);
205
+ }
206
+ catch (error) {
207
+ log.warning(`Could not parse JSONL line ${i + 1}: ${error}`);
208
+ // Continue processing other lines
209
+ }
210
+ }
211
+ return results;
212
+ }
213
+ }
214
+ // =============================================================================
215
+ // UTILITY FUNCTIONS
216
+ // =============================================================================
217
+ /**
218
+ * Safe async operation wrapper
219
+ */
220
+ export async function safeAsync(operation, fallback, context) {
221
+ try {
222
+ return await operation();
223
+ }
224
+ catch (error) {
225
+ if (context) {
226
+ log.warning(`${context}: ${error}. Using fallback.`);
227
+ }
228
+ return fallback;
229
+ }
230
+ }
231
+ /**
232
+ * Helper to exit cleanly after handling an error
233
+ */
234
+ export function exitWithError(error, context) {
235
+ ErrorHandler.handleCommandError(error, context);
236
+ process.exit(1);
237
+ }
238
+ // Moved to constants.ts - use HOOK_RESPONSES.SUCCESS() or HOOK_RESPONSES.ERROR() instead
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Utilities Index - Main exports for claude-mem utilities
3
+ *
4
+ * This module provides clean, centralized exports for all utility modules
5
+ * used throughout the claude-mem system.
6
+ */
7
+ export { getMCPClient, createMCPClient, resetMCPClient, isMCPClientActive, getCurrentSettings, withMCPClient } from './mcp-client.js';
8
+ export { WeaviateMCPAdapter, createWeaviateMCPAdapter } from './weaviate-mcp-adapter.js';
9
+ export type { IMCPClient, MCPEntity, MCPRelation, MCPSearchResult, Settings } from '../types.js';
10
+ import { getMCPClient as _getMCPClient, createMCPClient as _createMCPClient, resetMCPClient as _resetMCPClient, withMCPClient as _withMCPClient } from './mcp-client.js';
11
+ import { createWeaviateMCPAdapter as _createWeaviateMCPAdapter } from './weaviate-mcp-adapter.js';
12
+ declare const _default: {
13
+ getMCPClient: typeof _getMCPClient;
14
+ createMCPClient: typeof _createMCPClient;
15
+ resetMCPClient: typeof _resetMCPClient;
16
+ withMCPClient: typeof _withMCPClient;
17
+ createWeaviateMCPAdapter: typeof _createWeaviateMCPAdapter;
18
+ };
19
+ export default _default;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Utilities Index - Main exports for claude-mem utilities
3
+ *
4
+ * This module provides clean, centralized exports for all utility modules
5
+ * used throughout the claude-mem system.
6
+ */
7
+ // =============================================================================
8
+ // MCP CLIENT MODULES
9
+ // =============================================================================
10
+ export { getMCPClient, createMCPClient, resetMCPClient, isMCPClientActive, getCurrentSettings, withMCPClient } from './mcp-client.js';
11
+ export { WeaviateMCPAdapter, createWeaviateMCPAdapter } from './weaviate-mcp-adapter.js';
12
+ // =============================================================================
13
+ // DEFAULT EXPORT FOR CONVENIENCE
14
+ // =============================================================================
15
+ // Import functions again for default export (required for shorthand property syntax)
16
+ import { getMCPClient as _getMCPClient, createMCPClient as _createMCPClient, resetMCPClient as _resetMCPClient, withMCPClient as _withMCPClient } from './mcp-client.js';
17
+ import { createWeaviateMCPAdapter as _createWeaviateMCPAdapter } from './weaviate-mcp-adapter.js';
18
+ export default {
19
+ // Main MCP client interface
20
+ getMCPClient: _getMCPClient,
21
+ createMCPClient: _createMCPClient,
22
+ resetMCPClient: _resetMCPClient,
23
+ withMCPClient: _withMCPClient,
24
+ // Weaviate implementation
25
+ createWeaviateMCPAdapter: _createWeaviateMCPAdapter
26
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Simple logging utility for claude-mem
3
+ */
4
+ export interface LogLevel {
5
+ DEBUG: number;
6
+ INFO: number;
7
+ WARN: number;
8
+ ERROR: number;
9
+ }
10
+ declare class Logger {
11
+ private level;
12
+ setLevel(level: keyof LogLevel): void;
13
+ debug(message: string, ...args: any[]): void;
14
+ info(message: string, ...args: any[]): void;
15
+ warn(message: string, ...args: any[]): void;
16
+ error(message: string, error?: any, context?: any): void;
17
+ }
18
+ export declare const log: Logger;
19
+ export {};
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Simple logging utility for claude-mem
3
+ */
4
+ const LOG_LEVELS = {
5
+ DEBUG: 0,
6
+ INFO: 1,
7
+ WARN: 2,
8
+ ERROR: 3,
9
+ };
10
+ class Logger {
11
+ level = LOG_LEVELS.INFO;
12
+ setLevel(level) {
13
+ this.level = LOG_LEVELS[level];
14
+ }
15
+ debug(message, ...args) {
16
+ if (this.level <= LOG_LEVELS.DEBUG) {
17
+ console.debug(`[DEBUG] ${message}`, ...args);
18
+ }
19
+ }
20
+ info(message, ...args) {
21
+ if (this.level <= LOG_LEVELS.INFO) {
22
+ console.info(`[INFO] ${message}`, ...args);
23
+ }
24
+ }
25
+ warn(message, ...args) {
26
+ if (this.level <= LOG_LEVELS.WARN) {
27
+ console.warn(`[WARN] ${message}`, ...args);
28
+ }
29
+ }
30
+ error(message, error, context) {
31
+ if (this.level <= LOG_LEVELS.ERROR) {
32
+ console.error(`[ERROR] ${message}`);
33
+ if (error) {
34
+ console.error(error);
35
+ }
36
+ if (context) {
37
+ console.error('Context:', context);
38
+ }
39
+ }
40
+ }
41
+ }
42
+ export const log = new Logger();
@@ -0,0 +1,51 @@
1
+ /**
2
+ * MCP Client Factory for claude-mem
3
+ *
4
+ * This factory provides a unified interface for creating MCP clients based on
5
+ * the configured backend type. It supports both the original memory backend
6
+ * (using JSONL files) and the new Weaviate backend for improved search capabilities.
7
+ *
8
+ * Key Features:
9
+ * - Backend detection from settings (default: 'memory')
10
+ * - Returns appropriate client implementation
11
+ * - Maintains singleton patterns where applicable
12
+ * - Provides fallback logic for robustness
13
+ */
14
+ import { Settings, IMCPClient } from '../types.js';
15
+ /**
16
+ * Create an MCP client based on the configured backend type
17
+ *
18
+ * @param settings - User/project settings containing backend configuration
19
+ * @returns IMCPClient implementation for the specified backend
20
+ */
21
+ export declare function createMCPClient(settings?: Settings): IMCPClient;
22
+ /**
23
+ * Detect the best available backend based on environment and configuration
24
+ *
25
+ * This function provides intelligent fallback logic:
26
+ * 1. If Weaviate is configured and available, prefer it
27
+ * 2. Otherwise, fall back to the reliable memory backend
28
+ *
29
+ * @param settings - User settings to check
30
+ * @returns The recommended backend type
31
+ */
32
+ export declare function detectOptimalBackend(settings?: Settings): Promise<'memory' | 'weaviate'>;
33
+ /**
34
+ * Validate backend configuration and provide helpful error messages
35
+ *
36
+ * @param settings - Settings to validate
37
+ * @throws Error if configuration is invalid
38
+ */
39
+ export declare function validateBackendConfig(settings: Settings): void;
40
+ /**
41
+ * Create a client with automatic backend detection and validation
42
+ *
43
+ * This is the recommended way to create MCP clients as it includes:
44
+ * - Backend detection and fallback logic
45
+ * - Configuration validation
46
+ * - Helpful error messages
47
+ *
48
+ * @param settings - User settings
49
+ * @returns Configured and validated MCP client
50
+ */
51
+ export declare function createOptimalMCPClient(settings?: Settings): Promise<IMCPClient>;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * MCP Client Factory for claude-mem
3
+ *
4
+ * This factory provides a unified interface for creating MCP clients based on
5
+ * the configured backend type. It supports both the original memory backend
6
+ * (using JSONL files) and the new Weaviate backend for improved search capabilities.
7
+ *
8
+ * Key Features:
9
+ * - Backend detection from settings (default: 'memory')
10
+ * - Returns appropriate client implementation
11
+ * - Maintains singleton patterns where applicable
12
+ * - Provides fallback logic for robustness
13
+ */
14
+ import { WeaviateMCPAdapter } from './weaviate-mcp-adapter.js';
15
+ import { MemoryMCPClient } from './memory-mcp-client.js';
16
+ /**
17
+ * Create an MCP client based on the configured backend type
18
+ *
19
+ * @param settings - User/project settings containing backend configuration
20
+ * @returns IMCPClient implementation for the specified backend
21
+ */
22
+ export function createMCPClient(settings = {}) {
23
+ const backend = settings.backend || 'memory';
24
+ switch (backend) {
25
+ case 'weaviate':
26
+ // Create Weaviate adapter with custom configuration
27
+ return new WeaviateMCPAdapter(settings.weaviateConfig);
28
+ case 'memory':
29
+ default:
30
+ // Use the traditional memory backend (JSONL files)
31
+ return MemoryMCPClient.getInstance();
32
+ }
33
+ }
34
+ /**
35
+ * Detect the best available backend based on environment and configuration
36
+ *
37
+ * This function provides intelligent fallback logic:
38
+ * 1. If Weaviate is configured and available, prefer it
39
+ * 2. Otherwise, fall back to the reliable memory backend
40
+ *
41
+ * @param settings - User settings to check
42
+ * @returns The recommended backend type
43
+ */
44
+ export async function detectOptimalBackend(settings = {}) {
45
+ // If explicitly set, respect the user's choice
46
+ if (settings.backend) {
47
+ return settings.backend;
48
+ }
49
+ // Check if Weaviate is configured and accessible
50
+ if (settings.weaviateConfig) {
51
+ try {
52
+ // In a real implementation, this would ping Weaviate to verify availability
53
+ // For now, we assume if it's configured, it's preferred
54
+ return 'weaviate';
55
+ }
56
+ catch (error) {
57
+ // Fall back to memory if Weaviate is not available
58
+ console.warn('Weaviate backend configured but not available, falling back to memory backend');
59
+ }
60
+ }
61
+ // Default to the reliable memory backend
62
+ return 'memory';
63
+ }
64
+ /**
65
+ * Validate backend configuration and provide helpful error messages
66
+ *
67
+ * @param settings - Settings to validate
68
+ * @throws Error if configuration is invalid
69
+ */
70
+ export function validateBackendConfig(settings) {
71
+ if (settings.backend === 'weaviate') {
72
+ if (!settings.weaviateConfig) {
73
+ throw new Error('Weaviate backend selected but no weaviateConfig provided');
74
+ }
75
+ const config = settings.weaviateConfig;
76
+ if (config.host && !config.host.includes(':')) {
77
+ throw new Error('Weaviate host must include port (e.g., "localhost:8080")');
78
+ }
79
+ if (config.scheme && !['http', 'https'].includes(config.scheme)) {
80
+ throw new Error('Weaviate scheme must be "http" or "https"');
81
+ }
82
+ }
83
+ }
84
+ /**
85
+ * Create a client with automatic backend detection and validation
86
+ *
87
+ * This is the recommended way to create MCP clients as it includes:
88
+ * - Backend detection and fallback logic
89
+ * - Configuration validation
90
+ * - Helpful error messages
91
+ *
92
+ * @param settings - User settings
93
+ * @returns Configured and validated MCP client
94
+ */
95
+ export async function createOptimalMCPClient(settings = {}) {
96
+ try {
97
+ // Validate configuration first
98
+ validateBackendConfig(settings);
99
+ // Detect optimal backend
100
+ const optimalBackend = await detectOptimalBackend(settings);
101
+ // Create client with detected backend
102
+ const clientSettings = {
103
+ ...settings,
104
+ backend: optimalBackend
105
+ };
106
+ return createMCPClient(clientSettings);
107
+ }
108
+ catch (error) {
109
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
110
+ console.warn(`Failed to create optimal MCP client: ${errorMessage}`);
111
+ console.warn('Falling back to memory backend');
112
+ // Last resort: always fall back to memory backend
113
+ return MemoryMCPClient.getInstance();
114
+ }
115
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * MCP Client for claude-mem
3
+ *
4
+ * This module provides the main interface for MCP operations in claude-mem.
5
+ * It uses embedded Weaviate as the only backend for persistent storage.
6
+ *
7
+ * Key Features:
8
+ * - Embedded Weaviate instance (no external dependencies)
9
+ * - Singleton pattern for efficient resource usage
10
+ * - Persistent storage across sessions
11
+ * - Clean interface matching existing usage patterns
12
+ */
13
+ import { IMCPClient, Settings } from '../types.js';
14
+ /**
15
+ * Get or create an MCP client instance
16
+ *
17
+ * This function maintains a singleton pattern using embedded Weaviate.
18
+ * The client persists across calls for efficient resource usage.
19
+ *
20
+ * @param settings - Configuration settings for the client (optional)
21
+ * @returns IMCPClient instance
22
+ */
23
+ export declare function getMCPClient(settings?: Settings): Promise<IMCPClient>;
24
+ /**
25
+ * Create a new MCP client (bypasses singleton)
26
+ *
27
+ * Use this when you need a fresh client instance without affecting
28
+ * the global singleton. Useful for testing or parallel operations.
29
+ *
30
+ * @param settings - Configuration settings for the client (optional)
31
+ * @returns New IMCPClient instance
32
+ */
33
+ export declare function createMCPClient(settings?: Settings): Promise<IMCPClient>;
34
+ /**
35
+ * Disconnect and reset the global MCP client
36
+ *
37
+ * This function properly cleans up the singleton instance and
38
+ * allows for a fresh client to be created on the next call.
39
+ */
40
+ export declare function resetMCPClient(): Promise<void>;
41
+ /**
42
+ * Check if MCP client is connected
43
+ *
44
+ * @returns True if a client instance exists (may not be connected yet)
45
+ */
46
+ export declare function isMCPClientActive(): boolean;
47
+ /**
48
+ * Get current client settings (read-only)
49
+ *
50
+ * @returns Copy of current settings or null if no client exists
51
+ */
52
+ export declare function getCurrentSettings(): Settings | null;
53
+ /**
54
+ * Perform an MCP operation with automatic client management
55
+ *
56
+ * This helper function automatically handles client creation, connection,
57
+ * and error handling for common MCP operations.
58
+ *
59
+ * @param operation - Function that performs the MCP operation
60
+ * @param settings - Settings for the MCP client
61
+ * @returns Result of the operation
62
+ */
63
+ export declare function withMCPClient<T>(operation: (client: IMCPClient) => Promise<T>, settings?: Settings): Promise<T>;
64
+ /**
65
+ * Default export maintains backward compatibility
66
+ */
67
+ declare const _default: {
68
+ getMCPClient: typeof getMCPClient;
69
+ createMCPClient: typeof createMCPClient;
70
+ resetMCPClient: typeof resetMCPClient;
71
+ isMCPClientActive: typeof isMCPClientActive;
72
+ getCurrentSettings: typeof getCurrentSettings;
73
+ withMCPClient: typeof withMCPClient;
74
+ };
75
+ export default _default;