@elliotding/ai-agent-mcp 0.1.25 → 0.1.27

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 (53) hide show
  1. package/package.json +4 -1
  2. package/.prompt-cache/cmd-cmd-client-sdk-ai-hub-generate-testcase.md +0 -101
  3. package/.prompt-cache/cmd-cmd-client-sdk-ai-hub-submit_zct_job.md +0 -158
  4. package/.prompt-cache/skill-skill-client-sdk-ai-hub-analyze-conf-status.md +0 -311
  5. package/.prompt-cache/skill-skill-client-sdk-ai-hub-analyze-sdk-log.md +0 -64
  6. package/.prompt-cache/skill-skill-client-sdk-ai-hub-analyze-zmb-log-errors.md +0 -84
  7. package/ai-resource-telemetry.json +0 -40
  8. package/src/api/cached-client.ts +0 -144
  9. package/src/api/client.ts +0 -697
  10. package/src/auth/index.ts +0 -11
  11. package/src/auth/middleware.ts +0 -244
  12. package/src/auth/permissions.ts +0 -323
  13. package/src/auth/token-validator.ts +0 -292
  14. package/src/cache/cache-manager.ts +0 -243
  15. package/src/cache/index.ts +0 -6
  16. package/src/cache/redis-client.ts +0 -249
  17. package/src/config/constants.ts +0 -33
  18. package/src/config/index.ts +0 -269
  19. package/src/filesystem/manager.ts +0 -235
  20. package/src/git/multi-source-manager.ts +0 -654
  21. package/src/git/operations.ts +0 -93
  22. package/src/index.ts +0 -157
  23. package/src/monitoring/health.ts +0 -132
  24. package/src/prompts/cache.ts +0 -140
  25. package/src/prompts/generator.ts +0 -143
  26. package/src/prompts/index.ts +0 -20
  27. package/src/prompts/manager.ts +0 -718
  28. package/src/resources/index.ts +0 -13
  29. package/src/resources/loader.ts +0 -563
  30. package/src/server/http.ts +0 -549
  31. package/src/server.ts +0 -206
  32. package/src/session/manager.ts +0 -296
  33. package/src/telemetry/index.ts +0 -10
  34. package/src/telemetry/manager.ts +0 -419
  35. package/src/tools/index.ts +0 -13
  36. package/src/tools/manage-subscription.ts +0 -388
  37. package/src/tools/registry.ts +0 -97
  38. package/src/tools/resolve-prompt-content.ts +0 -113
  39. package/src/tools/search-resources.ts +0 -185
  40. package/src/tools/sync-resources.ts +0 -829
  41. package/src/tools/track-usage.ts +0 -113
  42. package/src/tools/uninstall-resource.ts +0 -199
  43. package/src/tools/upload-resource.ts +0 -431
  44. package/src/transport/sse.ts +0 -308
  45. package/src/types/errors.ts +0 -146
  46. package/src/types/index.ts +0 -7
  47. package/src/types/mcp.ts +0 -61
  48. package/src/types/resources.ts +0 -141
  49. package/src/types/tools.ts +0 -305
  50. package/src/utils/cursor-paths.ts +0 -135
  51. package/src/utils/log-cleaner.ts +0 -92
  52. package/src/utils/logger.ts +0 -333
  53. package/src/utils/validation.ts +0 -262
@@ -1,249 +0,0 @@
1
- /**
2
- * Redis Client Module
3
- * Connection management with retry strategy and basic cache operations
4
- */
5
-
6
- import Redis, { type Redis as RedisInstance } from 'ioredis';
7
- import { logger, logError } from '../utils/logger';
8
- import { config } from '../config';
9
-
10
- const RETRY_BASE_MS = 100;
11
- const RETRY_MAX_MS = 5000;
12
- const RETRY_MAX_ATTEMPTS = 10;
13
-
14
- /**
15
- * Exponential backoff: base * 2^times, capped at max
16
- */
17
- function exponentialBackoff(times: number): number {
18
- if (times > RETRY_MAX_ATTEMPTS) {
19
- return 0; // Stop retrying
20
- }
21
- const delay = Math.min(RETRY_BASE_MS * Math.pow(2, times), RETRY_MAX_MS);
22
- return delay;
23
- }
24
-
25
- export class RedisClient {
26
- private static instance: RedisClient | null = null;
27
- private client: RedisInstance | null = null;
28
- private isConnecting = false;
29
-
30
- private constructor() {}
31
-
32
- static getInstance(): RedisClient {
33
- if (RedisClient.instance === null) {
34
- RedisClient.instance = new RedisClient();
35
- }
36
- return RedisClient.instance;
37
- }
38
-
39
- /**
40
- * Connect to Redis with config and retry strategy
41
- */
42
- async connect(): Promise<void> {
43
- const redisConfig = config.cache?.redis;
44
- if (!redisConfig?.url) {
45
- logger.warn(
46
- { type: 'redis', event: 'connect_skipped' },
47
- 'Redis URL not configured (REDIS_URL), skipping connection'
48
- );
49
- return;
50
- }
51
-
52
- if (this.client && this.isConnected()) {
53
- logger.debug({ type: 'redis', event: 'connect' }, 'Redis already connected');
54
- return;
55
- }
56
-
57
- if (this.isConnecting) {
58
- logger.debug({ type: 'redis', event: 'connect' }, 'Redis connection in progress');
59
- return;
60
- }
61
-
62
- this.isConnecting = true;
63
-
64
- try {
65
- this.client = new Redis(redisConfig.url, {
66
- retryStrategy: (times: number) => {
67
- const delay = exponentialBackoff(times);
68
- if (delay === 0) {
69
- logger.error(
70
- { type: 'redis', event: 'retry_exhausted', times },
71
- 'Redis retry exhausted, giving up'
72
- );
73
- return undefined;
74
- }
75
- logger.warn(
76
- { type: 'redis', event: 'retry', times, delayMs: delay },
77
- `Redis reconnecting in ${delay}ms (attempt ${times})`
78
- );
79
- return delay;
80
- },
81
- maxRetriesPerRequest: null,
82
- connectTimeout: 10000,
83
- lazyConnect: true,
84
- });
85
-
86
- this.client.on('connect', () => {
87
- logger.info(
88
- { type: 'redis', event: 'connect' },
89
- 'Redis connection established'
90
- );
91
- });
92
-
93
- this.client.on('ready', () => {
94
- this.isConnecting = false;
95
- logger.info(
96
- { type: 'redis', event: 'ready' },
97
- 'Redis client ready'
98
- );
99
- });
100
-
101
- this.client.on('error', (err: Error) => {
102
- logger.error(
103
- { type: 'redis', event: 'error', error: err.message },
104
- `Redis error: ${err.message}`
105
- );
106
- });
107
-
108
- this.client.on('close', () => {
109
- logger.info(
110
- { type: 'redis', event: 'close' },
111
- 'Redis connection closed'
112
- );
113
- });
114
-
115
- await this.client.connect();
116
- } catch (error) {
117
- this.isConnecting = false;
118
- if (this.client) {
119
- this.client.disconnect();
120
- this.client = null;
121
- }
122
- logError(error as Error, { type: 'redis', event: 'connect_failed' });
123
- throw error;
124
- }
125
- }
126
-
127
- /**
128
- * Gracefully disconnect from Redis
129
- */
130
- async disconnect(): Promise<void> {
131
- if (!this.client) {
132
- logger.debug({ type: 'redis', event: 'disconnect' }, 'Redis not connected');
133
- return;
134
- }
135
-
136
- try {
137
- await this.client.quit();
138
- this.client = null;
139
- logger.info(
140
- { type: 'redis', event: 'disconnect' },
141
- 'Redis disconnected gracefully'
142
- );
143
- } catch (error) {
144
- logError(error as Error, { type: 'redis', event: 'disconnect_failed' });
145
- this.client = null;
146
- throw error;
147
- }
148
- }
149
-
150
- /**
151
- * Check if Redis client is connected
152
- */
153
- isConnected(): boolean {
154
- return this.client?.status === 'ready';
155
- }
156
-
157
- /**
158
- * Get value by key
159
- */
160
- async get(key: string): Promise<string | null> {
161
- if (!this.client) {
162
- logger.warn({ type: 'redis', operation: 'get', key }, 'Redis not connected');
163
- return null;
164
- }
165
-
166
- try {
167
- const value = await this.client.get(key);
168
- return value;
169
- } catch (error) {
170
- logError(error as Error, { type: 'redis', operation: 'get', key });
171
- throw error;
172
- }
173
- }
174
-
175
- /**
176
- * Set value with optional TTL (seconds)
177
- */
178
- async set(key: string, value: string, ttl?: number): Promise<void> {
179
- if (!this.client) {
180
- logger.warn({ type: 'redis', operation: 'set', key }, 'Redis not connected');
181
- throw new Error('Redis not connected');
182
- }
183
-
184
- try {
185
- const ttlSeconds = ttl ?? config.cache?.redis?.ttl ?? 900;
186
- await this.client.set(key, value, 'EX', ttlSeconds);
187
- } catch (error) {
188
- logError(error as Error, { type: 'redis', operation: 'set', key });
189
- throw error;
190
- }
191
- }
192
-
193
- /**
194
- * Delete key
195
- */
196
- async del(key: string): Promise<void> {
197
- if (!this.client) {
198
- logger.warn({ type: 'redis', operation: 'del', key }, 'Redis not connected');
199
- throw new Error('Redis not connected');
200
- }
201
-
202
- try {
203
- await this.client.del(key);
204
- } catch (error) {
205
- logError(error as Error, { type: 'redis', operation: 'del', key });
206
- throw error;
207
- }
208
- }
209
-
210
- /**
211
- * Clear all keys matching a pattern. Use with caution.
212
- */
213
- async clear(pattern = '*'): Promise<void> {
214
- if (!this.client) {
215
- logger.warn({ type: 'redis', operation: 'clear', pattern }, 'Redis not connected');
216
- throw new Error('Redis not connected');
217
- }
218
-
219
- try {
220
- const keys = await this.client.keys(pattern);
221
- if (keys.length > 0) {
222
- await this.client.del(...keys);
223
- }
224
- } catch (error) {
225
- logError(error as Error, { type: 'redis', operation: 'clear', pattern });
226
- throw error;
227
- }
228
- }
229
-
230
- /**
231
- * Check if key exists
232
- */
233
- async exists(key: string): Promise<boolean> {
234
- if (!this.client) {
235
- logger.warn({ type: 'redis', operation: 'exists', key }, 'Redis not connected');
236
- return false;
237
- }
238
-
239
- try {
240
- const result = await this.client.exists(key);
241
- return result === 1;
242
- } catch (error) {
243
- logError(error as Error, { type: 'redis', operation: 'exists', key });
244
- throw error;
245
- }
246
- }
247
- }
248
-
249
- export const redisClient = RedisClient.getInstance();
@@ -1,33 +0,0 @@
1
- /**
2
- * Configuration Constants
3
- */
4
-
5
- export const APP_NAME = 'csp-ai-agent-mcp';
6
- export const APP_VERSION = '0.1.0';
7
-
8
- export const DEFAULT_PORT = 5090;
9
- export const DEFAULT_LOG_LEVEL = 'info';
10
- export const DEFAULT_API_TIMEOUT = 30000;
11
-
12
- export const LOG_RETENTION_DAYS = 3;
13
- export const LOG_DIR = 'logs';
14
- export const LOG_FILE_PATTERN = 'app-{date}.log';
15
-
16
- export const CACHE_TTL_SECONDS = 900; // 15 minutes
17
- export const MEMORY_CACHE_SIZE = 20;
18
-
19
- export const TOOL_NAMES = {
20
- SYNC_RESOURCES: 'sync_resources',
21
- MANAGE_SUBSCRIPTION: 'manage_subscription',
22
- SEARCH_RESOURCES: 'search_resources',
23
- UPLOAD_RESOURCE: 'upload_resource',
24
- UNINSTALL_RESOURCE: 'uninstall_resource',
25
- } as const;
26
-
27
- export const TOOL_TIMEOUTS = {
28
- [TOOL_NAMES.SEARCH_RESOURCES]: 10000, // 10s
29
- [TOOL_NAMES.SYNC_RESOURCES]: 60000, // 60s
30
- [TOOL_NAMES.UPLOAD_RESOURCE]: 120000, // 120s
31
- [TOOL_NAMES.MANAGE_SUBSCRIPTION]: 15000, // 15s
32
- [TOOL_NAMES.UNINSTALL_RESOURCE]: 5000, // 5s
33
- } as const;
@@ -1,269 +0,0 @@
1
- /**
2
- * Configuration Management Module
3
- * Loads and validates configuration from environment variables
4
- */
5
-
6
- import * as dotenv from 'dotenv';
7
- import * as path from 'path';
8
- import * as fs from 'fs';
9
-
10
- // Load .env file if exists
11
- // Try multiple paths to find .env file
12
- const possibleEnvPaths = [
13
- path.resolve(process.cwd(), '.env'), // Current working directory
14
- path.resolve(__dirname, '../../.env'), // Relative to compiled dist/config/
15
- path.resolve(__dirname, '../../../.env'), // Project root (if deeper nesting)
16
- ];
17
-
18
- let envLoaded = false;
19
- for (const envPath of possibleEnvPaths) {
20
- if (fs.existsSync(envPath)) {
21
- dotenv.config({ path: envPath });
22
- console.log(`✓ Loaded .env from: ${envPath}`);
23
- envLoaded = true;
24
- break;
25
- }
26
- }
27
-
28
- if (!envLoaded) {
29
- console.warn('⚠ No .env file found, using environment variables only');
30
- }
31
-
32
- export interface Config {
33
- // Environment
34
- nodeEnv: 'development' | 'production' | 'test';
35
-
36
- // Server
37
- port: number;
38
- logLevel: 'debug' | 'info' | 'warn' | 'error';
39
-
40
- // Transport
41
- transport: {
42
- mode: 'stdio' | 'sse';
43
- };
44
-
45
- // HTTP Server (for SSE transport)
46
- http?: {
47
- host: string;
48
- port: number;
49
- /** URL path prefix when the server runs behind a reverse proxy sub-path.
50
- * e.g. HTTP_BASE_PATH=/csp-agent → SSE at /csp-agent/sse
51
- * → messages POST to /csp-agent/message
52
- * Leave empty (default) for direct / root-path deployments.
53
- */
54
- basePath: string;
55
- /**
56
- * The public-facing origin clients (Cursor) should use when posting
57
- * JSON-RPC messages. Derived from CSP_API_BASE_URL so that teams only
58
- * need one URL configured — the API base and the MCP server share the
59
- * same external hostname.
60
- *
61
- * e.g. CSP_API_BASE_URL=https://zct.zoomdev.us → publicOrigin=https://zct.zoomdev.us
62
- *
63
- * Falls back to PUBLIC_URL env var if set, then to the internal
64
- * http://host:port when running locally (where 0.0.0.0 == localhost).
65
- */
66
- publicOrigin: string;
67
- };
68
-
69
- // Session (for SSE transport)
70
- session?: {
71
- timeout: number; // seconds
72
- };
73
-
74
- // CSP API
75
- csp: {
76
- apiBaseUrl: string;
77
- // NOTE: No apiToken here. The user token is established during the first MCP
78
- // connection (SSE Authorization header), validated, then cached per-session.
79
- // Each tool call receives it via the injected user_token argument.
80
- // Storing a static token in config would break multi-user scenarios.
81
- timeout: number;
82
- };
83
-
84
- // Git — only commit author info; repo URLs/branches live in ai-resources-config.json
85
- git: {
86
- userName: string;
87
- userEmail: string;
88
- };
89
-
90
- // Resource Storage — resolved at runtime via cursor-paths utility.
91
- // No longer stored in config; use getCursorTypeDir() / getCursorResourcePath() directly.
92
- // Kept as an empty marker so consumers know where to look.
93
- resource: Record<string, never>;
94
-
95
- // Cache (optional)
96
- cache: {
97
- enabled: boolean;
98
- redis?: {
99
- url: string;
100
- ttl: number;
101
- };
102
- memory: {
103
- maxSize: number;
104
- };
105
- };
106
-
107
- // Database (optional)
108
- database?: {
109
- url: string;
110
- };
111
-
112
- // Monitoring (optional)
113
- metrics: {
114
- enabled: boolean;
115
- port?: number;
116
- };
117
-
118
- // Logging
119
- logging: {
120
- dir: string;
121
- retentionDays: number;
122
- };
123
- }
124
-
125
- function getEnv(key: string, defaultValue?: string): string {
126
- const value = process.env[key];
127
- if (value === undefined) {
128
- if (defaultValue !== undefined) {
129
- return defaultValue;
130
- }
131
- throw new Error(`Missing required environment variable: ${key}`);
132
- }
133
- return value;
134
- }
135
-
136
- function getEnvNumber(key: string, defaultValue?: number): number {
137
- const value = process.env[key];
138
- if (value === undefined) {
139
- if (defaultValue !== undefined) {
140
- return defaultValue;
141
- }
142
- throw new Error(`Missing required environment variable: ${key}`);
143
- }
144
- const parsed = parseInt(value, 10);
145
- if (isNaN(parsed)) {
146
- throw new Error(`Environment variable ${key} must be a number, got: ${value}`);
147
- }
148
- return parsed;
149
- }
150
-
151
- function getEnvBoolean(key: string, defaultValue: boolean): boolean {
152
- const value = process.env[key];
153
- if (value === undefined) {
154
- return defaultValue;
155
- }
156
- return value.toLowerCase() === 'true';
157
- }
158
-
159
- export function loadConfig(): Config {
160
- const nodeEnv = (process.env.NODE_ENV || 'development') as Config['nodeEnv'];
161
- const logLevel = (process.env.LOG_LEVEL || 'info') as Config['logLevel'];
162
- const transportMode = (process.env.TRANSPORT_MODE || 'stdio') as 'stdio' | 'sse';
163
-
164
- return {
165
- nodeEnv,
166
- port: getEnvNumber('PORT', 5090),
167
- logLevel,
168
-
169
- transport: {
170
- mode: transportMode,
171
- },
172
-
173
- http: transportMode === 'sse' ? (() => {
174
- const host = getEnv('HTTP_HOST', '0.0.0.0');
175
- const port = getEnvNumber('HTTP_PORT', 3000);
176
- const basePath = getEnv('HTTP_BASE_PATH', '');
177
-
178
- // Derive the public-facing origin that external clients (Cursor) will use
179
- // to POST JSON-RPC messages. Priority:
180
- // 1. PUBLIC_URL env var — explicit override (e.g. ngrok / custom domain)
181
- // 2. Origin extracted from CSP_API_BASE_URL — same host as the API
182
- // 3. http://host:port — safe for local dev where host==0.0.0.0==localhost
183
- const publicUrl = process.env['PUBLIC_URL'];
184
- const cspApiBase = process.env['CSP_API_BASE_URL'] ?? '';
185
- let publicOrigin: string;
186
- if (publicUrl) {
187
- publicOrigin = publicUrl.replace(/\/$/, '');
188
- } else if (cspApiBase) {
189
- try {
190
- const u = new URL(cspApiBase);
191
- publicOrigin = u.origin; // e.g. "https://zct.zoomdev.us"
192
- } catch {
193
- publicOrigin = `http://${host}:${port}`;
194
- }
195
- } else {
196
- publicOrigin = `http://${host}:${port}`;
197
- }
198
-
199
- return { host, port, basePath, publicOrigin };
200
- })() : undefined,
201
-
202
- session: transportMode === 'sse' ? {
203
- timeout: getEnvNumber('SESSION_TIMEOUT', 3600),
204
- } : undefined,
205
-
206
- csp: {
207
- apiBaseUrl: getEnv('CSP_API_BASE_URL', 'https://csp.example.com'),
208
- timeout: getEnvNumber('CSP_API_TIMEOUT', 30000),
209
- },
210
-
211
- git: {
212
- userName: getEnv('GIT_USER_NAME', 'CSP Agent'),
213
- userEmail: getEnv('GIT_USER_EMAIL', 'agent@example.com'),
214
- },
215
-
216
- resource: {},
217
-
218
- cache: {
219
- enabled: getEnvBoolean('ENABLE_CACHE', true),
220
- redis: process.env.REDIS_URL
221
- ? {
222
- url: process.env.REDIS_URL,
223
- ttl: getEnvNumber('REDIS_TTL', 900),
224
- }
225
- : undefined,
226
- memory: {
227
- maxSize: getEnvNumber('CACHE_MAX_SIZE', 100),
228
- },
229
- },
230
-
231
- database: process.env.DATABASE_URL
232
- ? {
233
- url: process.env.DATABASE_URL,
234
- }
235
- : undefined,
236
-
237
- metrics: {
238
- enabled: getEnvBoolean('ENABLE_METRICS', true),
239
- port: process.env.METRICS_PORT ? getEnvNumber('METRICS_PORT') : undefined,
240
- },
241
-
242
- logging: {
243
- dir: getEnv('LOG_DIR', '../Logs'),
244
- retentionDays: getEnvNumber('LOG_RETENTION_DAYS', 3),
245
- },
246
- };
247
- }
248
-
249
- // Validate configuration on load
250
- let config: Config;
251
-
252
- try {
253
- config = loadConfig();
254
- } catch (error) {
255
- // Use logger for consistent error reporting
256
- const logger = require('../utils/logger').logger;
257
- logger.error(
258
- {
259
- type: 'config',
260
- operation: 'load_config',
261
- error: (error as Error).message,
262
- stack: (error as Error).stack
263
- },
264
- 'Configuration loading failed'
265
- );
266
- process.exit(1);
267
- }
268
-
269
- export { config };