@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,431 +0,0 @@
1
- /**
2
- * upload_resource Tool
3
- *
4
- * Uploads resource files to a CSP source repository via the two-step API:
5
- * Step 1: POST /csp/api/resources/upload → returns upload_id (server-side staging)
6
- * Step 2: POST /csp/api/resources/finalize → triggers Git commit, returns permanent resource_id
7
- *
8
- * The user selects files from anywhere on their local machine. The AI reads the file
9
- * content and passes it directly in files[]. The MCP server forwards everything to the
10
- * CSP API — no local path resolution or server-side filesystem access is needed.
11
- *
12
- * target_source is passed through to the CSP API as-is; the CSP server decides
13
- * which Git repo to commit to based on that value.
14
- */
15
-
16
- import * as path from 'path';
17
- import { logger, logToolCall } from '../utils/logger';
18
- import { apiClient } from '../api/client';
19
- import { resourceLoader } from '../resources';
20
- import { MCPServerError, createValidationError } from '../types/errors';
21
- import { promptManager } from '../prompts/index.js';
22
- import type { UploadResourceParams, UploadResourceResult, ToolResult, FileEntry } from '../types/tools';
23
- import type { ResourceType } from '../types/resources';
24
-
25
- type ResourceCategory = 'command' | 'skill' | 'rule' | 'mcp';
26
-
27
- /** Extract the `description` field from YAML frontmatter (--- ... ---) in Markdown content. */
28
- function extractFrontmatterDescription(content: string): string | undefined {
29
- if (!content.startsWith('---')) return undefined;
30
- const end = content.indexOf('\n---', 3);
31
- if (end === -1) return undefined;
32
- const frontmatter = content.slice(3, end);
33
- for (const line of frontmatter.split('\n')) {
34
- const match = /^description:\s*(.+)$/.exec(line.trim());
35
- if (match) return match[1]!.trim().replace(/^['"]|['"]$/g, '');
36
- }
37
- return undefined;
38
- }
39
-
40
- /**
41
- * Infer the resource type from the uploaded file list ONLY when the user has
42
- * not explicitly stated a type. If the user declared a type, that always wins.
43
- *
44
- * Auto-detection rules (in priority order, applied only when declaredType is absent):
45
- * 1. Any file named "mcp-config.json" → mcp
46
- * 2. Any file named "SKILL.md" → skill
47
- * 3. Single file ending with ".mdc" → rule
48
- * 4. Single file ending with ".md" → command
49
- * 5. Cannot determine → throw validation error
50
- */
51
- function inferResourceType(
52
- declaredType: ResourceCategory | undefined,
53
- files: FileEntry[]
54
- ): ResourceCategory {
55
- // User explicitly specified the type — honour it unconditionally.
56
- if (declaredType) return declaredType;
57
-
58
- const names = files.map((f) => path.basename(f.path).toLowerCase());
59
-
60
- if (names.includes('mcp-config.json')) return 'mcp';
61
- if (names.includes('skill.md')) return 'skill';
62
- if (files.length === 1) {
63
- if (names[0]!.endsWith('.mdc')) return 'rule';
64
- if (names[0]!.endsWith('.md')) return 'command';
65
- }
66
-
67
- throw createValidationError(
68
- 'type',
69
- 'required',
70
- 'Cannot auto-detect the resource type from the provided files. ' +
71
- 'Please specify "type" explicitly: "command" (single .md), "skill" (contains SKILL.md), ' +
72
- '"rule" (single .mdc), or "mcp" (contains mcp-config.json).'
73
- );
74
- }
75
-
76
- /**
77
- * Derive a human-readable resource name from the primary file in the upload list.
78
- * The original filename (without extension) is used as-is — never renamed.
79
- *
80
- * - Single-file upload: strip extension from the filename.
81
- * "code-review.md" → "code-review"
82
- * "csp-agent.mdc" → "csp-agent"
83
- * - Multi-file upload: use the top-level directory name when the first
84
- * path contains a directory component.
85
- * "code-review/SKILL.md" → "code-review"
86
- * Falls back to the first file's base name otherwise.
87
- *
88
- * Returns undefined when the files array is empty (caller should error).
89
- */
90
- function deriveNameFromFiles(files: FileEntry[]): string | undefined {
91
- if (!files || files.length === 0) return undefined;
92
-
93
- const first = files[0]!.path;
94
-
95
- // For paths like "code-review/SKILL.md", use the top-level directory.
96
- const dir = path.dirname(first);
97
- if (dir && dir !== '.') return dir;
98
-
99
- // Strip extension from bare filename.
100
- const base = path.basename(first, path.extname(first));
101
- return base || undefined;
102
- }
103
-
104
- /**
105
- * Validate and return the files[] array.
106
- * Each entry path must be a relative path with no traversal.
107
- * For MCP resources, mcp-config.json must be present.
108
- *
109
- * @param resolvedType The already-inferred resource type (never undefined here).
110
- */
111
- function collectFiles(typedParams: UploadResourceParams, resolvedType: string): FileEntry[] {
112
- if (!typedParams.files || typedParams.files.length === 0) {
113
- throw createValidationError(
114
- 'files',
115
- 'required',
116
- '"files" must be a non-empty array of {path, content} entries.'
117
- );
118
- }
119
-
120
- for (const entry of typedParams.files) {
121
- const norm = path.normalize(entry.path);
122
- if (norm.startsWith('..') || path.isAbsolute(norm)) {
123
- throw createValidationError(
124
- 'files[].path',
125
- 'relative_path',
126
- `Path traversal or absolute path not allowed: "${entry.path}"`
127
- );
128
- }
129
- }
130
-
131
- // MCP resources must include mcp-config.json so the client can auto-register
132
- // the server in ~/.cursor/mcp.json after sync_resources installs it.
133
- if (resolvedType === 'mcp') {
134
- const hasMcpConfig = typedParams.files.some(
135
- (f) => path.basename(f.path) === 'mcp-config.json'
136
- );
137
- if (!hasMcpConfig) {
138
- // Look for other files that might already describe the server configuration
139
- // (e.g. pyproject.toml, package.json, README.md, config.json, server.py).
140
- // If found, surface a targeted hint so the user knows exactly what to create.
141
- const configHints = typedParams.files
142
- .map((f) => path.basename(f.path))
143
- .filter((n) =>
144
- /\.(toml|yaml|yml|json|cfg|ini|conf|py|js|ts|md)$/i.test(n) &&
145
- n !== 'mcp-config.json'
146
- );
147
-
148
- const hintNote =
149
- configHints.length > 0
150
- ? `\nFound related files (${configHints.join(', ')}) that may already describe the server ` +
151
- `configuration — please create "mcp-config.json" based on those files.`
152
- : '';
153
-
154
- throw createValidationError(
155
- 'files',
156
- 'required',
157
- 'MCP resources must include a "mcp-config.json" file. ' +
158
- 'This file tells the client how to start the MCP server after installation.' +
159
- hintNote +
160
- '\n\nRequired format:\n' +
161
- '{\n' +
162
- ' "name": "<server-name>",\n' +
163
- ' "command": "python3", // or "node", "uvx", etc.\n' +
164
- ' "args": ["<entry-file.py>"], // relative path resolved against install dir\n' +
165
- ' "env": { "ENV_VAR": "" } // optional; empty string = user must fill in\n' +
166
- '}'
167
- );
168
- }
169
- }
170
-
171
- return typedParams.files;
172
- }
173
-
174
- export async function uploadResource(params: unknown): Promise<ToolResult<UploadResourceResult>> {
175
- const startTime = Date.now();
176
- const typedParams = params as UploadResourceParams;
177
-
178
- logger.info({ tool: 'upload_resource', params }, 'upload_resource called');
179
-
180
- try {
181
- const resourceId = typedParams.resource_id;
182
- const userToken = typedParams.user_token;
183
- const targetSource = typedParams.target_source ?? 'csp';
184
- const force = (typedParams as any).force || false;
185
-
186
- // User-declared type always wins; auto-detect only when omitted.
187
- const resourceType = inferResourceType(typedParams.type, typedParams.files);
188
-
189
- // Name: explicit user value > derived from filename (no extension).
190
- // Never fall back to resource_id — that is an internal identifier, not a name.
191
- const derivedName = typedParams.name ?? deriveNameFromFiles(typedParams.files);
192
- if (!derivedName) {
193
- throw createValidationError(
194
- 'name',
195
- 'required',
196
- 'Could not determine a resource name from the provided files. ' +
197
- 'Please provide a "name" field explicitly.'
198
- );
199
- }
200
- const resourceName = derivedName;
201
-
202
- logger.info({ resourceId, resourceType, targetSource }, 'Upload target resolved');
203
-
204
- // ========== Step 1: Duplicate-name check ==========
205
- try {
206
- if (!resourceLoader.getStats()) {
207
- await resourceLoader.loadConfig();
208
- await resourceLoader.scanResources();
209
- }
210
- const existing = resourceLoader.searchResourcesByName(resourceName, resourceType as ResourceType | undefined);
211
- if (existing.length > 0 && !force) {
212
- const conflictInfo = existing.map((r) => ({ name: r.name, type: r.type, source: r.source }));
213
- logger.warn({ resourceName, resourceType, conflictInfo }, 'Resource name conflict detected');
214
- return {
215
- success: false,
216
- error: {
217
- code: 'RESOURCE_NAME_CONFLICT',
218
- message:
219
- `Resource "${resourceName}" already exists. Add "force": true to overwrite.\n` +
220
- conflictInfo.map((c) => ` - ${c.name} (${c.type}, source: ${c.source})`).join('\n'),
221
- details: conflictInfo,
222
- } as any,
223
- };
224
- }
225
- } catch (err) {
226
- logger.warn({ error: (err as Error).message }, 'Duplicate check failed, continuing upload');
227
- }
228
-
229
- // ========== Step 3: Validate commit message ==========
230
- if (!typedParams.message || typeof typedParams.message !== 'string') {
231
- throw createValidationError('message', 'string', 'Commit message is required');
232
- }
233
- if (typedParams.message.length < 5 || typedParams.message.length > 200) {
234
- throw createValidationError(
235
- 'message', 'string',
236
- `Commit message must be 5-200 characters, got ${typedParams.message.length}`
237
- );
238
- }
239
-
240
- // ========== Step 4: Collect files ==========
241
- const fileEntries = collectFiles(typedParams, resourceType);
242
- logger.info({ resourceId, fileCount: fileEntries.length }, 'Files collected for upload');
243
-
244
- // ========== Step 5: Call CSP API — upload (staging) ==========
245
- logger.info({ resourceName, resourceType, targetSource }, 'Calling CSP upload API...');
246
- const uploadResp = await apiClient.uploadResourceFiles(
247
- {
248
- type: resourceType,
249
- name: resourceName,
250
- files: fileEntries,
251
- target_source: targetSource,
252
- force,
253
- },
254
- userToken
255
- );
256
-
257
- const uploadId = uploadResp.upload_id;
258
- logger.info({ uploadId, expiresAt: uploadResp.expires_at }, 'Upload staged successfully');
259
-
260
- // ========== Step 6: Call CSP API — finalize (Git commit) ==========
261
- logger.info({ uploadId }, 'Calling CSP finalize API...');
262
- const finalizeResp = await apiClient.finalizeResourceUpload(uploadId, typedParams.message, userToken);
263
-
264
- const finalResourceId = finalizeResp.resource_id;
265
- const version = finalizeResp.version ?? '1.0.0';
266
- const resourceUrl = finalizeResp.url ?? '';
267
- const commitHash = finalizeResp.commit_hash ?? '';
268
-
269
- logger.info({ finalResourceId, version, commitHash }, 'Upload finalized successfully');
270
-
271
- // For Command / Skill: register the uploaded content as an MCP Prompt immediately,
272
- // so the user can invoke it via slash-command without a full sync cycle.
273
- if (resourceType === 'command' || resourceType === 'skill') {
274
- try {
275
- const primaryFile = resourceType === 'skill'
276
- ? (fileEntries.find((f) => path.basename(f.path) === 'SKILL.md') ??
277
- fileEntries.find((f) => f.path.endsWith('.md')) ??
278
- fileEntries[0])
279
- : (fileEntries.find((f) => path.basename(f.path).replace(/\.md$/, '') === resourceName) ??
280
- fileEntries.find((f) => f.path.endsWith('.md')) ??
281
- fileEntries[0]);
282
-
283
- const rawContent = primaryFile?.content ?? '';
284
- const team = (typedParams as any).team ?? 'general';
285
- const frontmatterDesc = extractFrontmatterDescription(rawContent);
286
- const description = frontmatterDesc ?? typedParams.message ?? resourceName;
287
-
288
- await promptManager.registerPrompt({
289
- resource_id: finalResourceId,
290
- resource_type: resourceType as 'command' | 'skill',
291
- resource_name: resourceName,
292
- team,
293
- description,
294
- rawContent,
295
- }, userToken ?? '');
296
- logger.info({ finalResourceId, resourceType }, 'MCP Prompt registered after upload');
297
- } catch (promptErr) {
298
- // Non-fatal: the resource is uploaded; Prompt registration is best-effort.
299
- logger.warn(
300
- { finalResourceId, error: (promptErr as Error).message },
301
- 'MCP Prompt registration after upload failed (non-fatal)',
302
- );
303
- }
304
- }
305
-
306
- const result: UploadResourceResult = {
307
- resource_id: finalResourceId,
308
- version,
309
- url: resourceUrl,
310
- commit_hash: commitHash,
311
- message: `Resource '${resourceName}' (${resourceType}) uploaded to source '${targetSource}' (v${version}). ${resourceUrl ? `URL: ${resourceUrl}` : ''}`.trim(),
312
- };
313
-
314
- const duration = Date.now() - startTime;
315
- logToolCall('upload_resource', 'user-id', params as Record<string, unknown>, duration);
316
- logger.info({ finalResourceId, version, source: targetSource, duration }, 'upload_resource completed');
317
-
318
- return { success: true, data: result };
319
-
320
- } catch (error) {
321
- logger.error({ error, resourceId: typedParams.resource_id }, 'upload_resource failed');
322
- return {
323
- success: false,
324
- error: {
325
- code: error instanceof MCPServerError ? error.code : 'UNKNOWN_ERROR',
326
- message: error instanceof Error ? error.message : String(error),
327
- },
328
- };
329
- }
330
- }
331
-
332
- // Tool definition for registry
333
- export const uploadResourceTool = {
334
- name: 'upload_resource',
335
- description:
336
- 'Upload a new AI resource (command, skill, rule, or mcp) to a CSP source repository. ' +
337
- 'The user selects files from their local machine — read each file and pass its content in files[]. ' +
338
- 'ALWAYS confirm the target source repo with the user (e.g. "csp" (default) or "client-sdk-ai-hub"). ' +
339
-
340
- '\n\nResource type rules:\n' +
341
- ' • If the user explicitly states the type, use it as-is — no overriding.\n' +
342
- ' • If the user does NOT state a type, auto-detect from file structure:\n' +
343
- ' - Contains mcp-config.json → type="mcp"\n' +
344
- ' - Contains SKILL.md → type="skill"\n' +
345
- ' - Single .mdc file → type="rule"\n' +
346
- ' - Single .md file → type="command"\n' +
347
- ' • If the user says type="mcp" but mcp-config.json is missing, the tool will\n' +
348
- ' return an error with a hint about creating mcp-config.json.\n' +
349
-
350
- '\n\nResource name rules:\n' +
351
- ' • If the user provides a name, use it.\n' +
352
- ' • Otherwise derive the name from the filename WITHOUT its extension.\n' +
353
- ' Keep the original filename — NEVER rename files (e.g. do not rename any .md file).\n' +
354
- ' Examples: "code-review.md" → name="code-review"; "code-review/SKILL.md" → name="code-review".\n' +
355
-
356
- '\n\nPass files[] — an array of {path, content} entries. ' +
357
- 'path must be the original filename as-is (relative, no path traversal). ' +
358
- 'No restriction on file extensions — mcp packages may include .py, .js, package.json, etc.\n' +
359
-
360
- '\nThe user_token is injected automatically by the server — do NOT read or pass it manually.',
361
- inputSchema: {
362
- type: 'object' as const,
363
- properties: {
364
- resource_id: {
365
- type: 'string',
366
- description: 'Unique resource identifier used as commit label and for duplicate detection',
367
- },
368
- name: {
369
- type: 'string',
370
- description: 'Human-readable resource name sent to the CSP API (defaults to resource_id if omitted)',
371
- },
372
- type: {
373
- type: 'string',
374
- enum: ['command', 'skill', 'rule', 'mcp'],
375
- description:
376
- 'Resource category. Auto-detected from file structure — only set explicitly when detection is ambiguous. ' +
377
- 'command: single .md slash-command file; ' +
378
- 'skill: directory or file set containing SKILL.md; ' +
379
- 'rule: single .mdc Cursor rule file; ' +
380
- 'mcp: MCP server package — MUST include mcp-config.json.',
381
- },
382
- message: {
383
- type: 'string',
384
- description: 'Git commit message (5-200 characters)',
385
- },
386
- target_source: {
387
- type: 'string',
388
- description:
389
- 'Target source repo name on the CSP server. ' +
390
- 'Ask the user which repo to target. Typical values: "csp" (default), "client-sdk-ai-hub". ' +
391
- 'The CSP server will commit the resource to the corresponding Git repo.',
392
- },
393
- files: {
394
- type: 'array',
395
- description:
396
- 'List of files to upload. Read each file from the user\'s local machine and pass content here. ' +
397
- 'path is the filename the resource should be stored as on the server. ' +
398
- 'Examples (type="rule"): [{path: "csp-ai-agent.mdc", content: "..."}]. ' +
399
- 'Examples (type="skill"): [{path: "SKILL.md", content: "..."}, {path: "examples.md", content: "..."}]. ' +
400
- 'Examples (type="mcp"): [{path: "server.py", content: "..."}, {path: "mcp-config.json", content: "..."}]. ' +
401
- 'No restriction on file extension.',
402
- items: {
403
- type: 'object',
404
- properties: {
405
- path: { type: 'string', description: 'Relative path under the type subdirectory' },
406
- content: { type: 'string', description: 'Full text content of the file' },
407
- },
408
- required: ['path', 'content'],
409
- },
410
- },
411
- team: {
412
- type: 'string',
413
- description: 'Team / group name (defaults to Client-Public)',
414
- default: 'Client-Public',
415
- },
416
- force: {
417
- type: 'boolean',
418
- description: 'Overwrite if a resource with the same name already exists',
419
- default: false,
420
- },
421
- user_token: {
422
- type: 'string',
423
- description:
424
- 'DO NOT set this field — it is automatically injected by the MCP server from ' +
425
- 'the authenticated SSE connection. The server always provides the correct token.',
426
- },
427
- },
428
- required: ['resource_id', 'message', 'files'],
429
- },
430
- handler: uploadResource,
431
- };