@elliotding/ai-agent-mcp 0.1.4 → 0.1.6
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.
- package/ai-resource-telemetry.json +19 -1
- package/dist/api/client.d.ts.map +1 -1
- package/dist/api/client.js +3 -4
- package/dist/api/client.js.map +1 -1
- package/dist/auth/token-validator.d.ts.map +1 -1
- package/dist/auth/token-validator.js +1 -3
- package/dist/auth/token-validator.js.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/prompts/manager.d.ts.map +1 -1
- package/dist/prompts/manager.js +2 -3
- package/dist/prompts/manager.js.map +1 -1
- package/dist/server/http.d.ts.map +1 -1
- package/dist/server/http.js +2 -3
- package/dist/server/http.js.map +1 -1
- package/dist/telemetry/manager.d.ts +4 -2
- package/dist/telemetry/manager.d.ts.map +1 -1
- package/dist/telemetry/manager.js +6 -7
- package/dist/telemetry/manager.js.map +1 -1
- package/dist/tools/sync-resources.d.ts.map +1 -1
- package/dist/tools/sync-resources.js +148 -332
- package/dist/tools/sync-resources.js.map +1 -1
- package/dist/tools/uninstall-resource.d.ts.map +1 -1
- package/dist/tools/uninstall-resource.js +66 -150
- package/dist/tools/uninstall-resource.js.map +1 -1
- package/dist/types/tools.d.ts +53 -0
- package/dist/types/tools.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/api/client.ts +3 -4
- package/src/auth/token-validator.ts +1 -3
- package/src/config/index.ts +4 -4
- package/src/index.ts +3 -3
- package/src/prompts/manager.ts +2 -3
- package/src/server/http.ts +2 -3
- package/src/telemetry/manager.ts +6 -6
- package/src/tools/sync-resources.ts +162 -380
- package/src/tools/uninstall-resource.ts +70 -162
- package/src/types/tools.ts +74 -0
|
@@ -23,7 +23,13 @@ import { apiClient } from '../api/client';
|
|
|
23
23
|
import { multiSourceGitManager } from '../git/multi-source-manager';
|
|
24
24
|
import { getCursorResourcePath, getCursorTypeDir, getCursorRootDir } from '../utils/cursor-paths';
|
|
25
25
|
import { MCPServerError } from '../types/errors';
|
|
26
|
-
import type {
|
|
26
|
+
import type {
|
|
27
|
+
SyncResourcesParams,
|
|
28
|
+
SyncResourcesResult,
|
|
29
|
+
LocalAction,
|
|
30
|
+
MergeMcpJsonAction,
|
|
31
|
+
ToolResult,
|
|
32
|
+
} from '../types/tools';
|
|
27
33
|
import { telemetry } from '../telemetry/index.js';
|
|
28
34
|
import { promptManager } from '../prompts/index.js';
|
|
29
35
|
|
|
@@ -44,274 +50,6 @@ function extractFrontmatterDescription(content: string): string | undefined {
|
|
|
44
50
|
return undefined;
|
|
45
51
|
}
|
|
46
52
|
|
|
47
|
-
/**
|
|
48
|
-
* Two supported mcp-config.json formats:
|
|
49
|
-
*
|
|
50
|
-
* Format A — Local executable (e.g. jenkins):
|
|
51
|
-
* Has a top-level "command" field.
|
|
52
|
-
* { "name": "jenkins", "command": "python3", "args": ["server.py"], "env": {...} }
|
|
53
|
-
* → One entry written to mcpServers using resolved absolute args.
|
|
54
|
-
*
|
|
55
|
-
* Format B — Remote URL entries (e.g. acm):
|
|
56
|
-
* No "command" field; the object IS the mcpServers map (one or more entries).
|
|
57
|
-
* { "acm-dev": { "url": "...", "transport": "sse" }, "acm": { "url": "..." } }
|
|
58
|
-
* → Each key merged directly into mcpServers as-is (no path resolution needed).
|
|
59
|
-
*
|
|
60
|
-
* Detection: if parsed JSON has a "command" key at the top level → Format A, else Format B.
|
|
61
|
-
*/
|
|
62
|
-
interface LocalMcpDescriptor {
|
|
63
|
-
name?: string;
|
|
64
|
-
command: string;
|
|
65
|
-
args?: string[];
|
|
66
|
-
env?: Record<string, string>;
|
|
67
|
-
}
|
|
68
|
-
type RemoteMcpEntries = Record<string, unknown>; // mcpServers-compatible map
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* Register a downloaded MCP resource into ~/.cursor/mcp.json.
|
|
72
|
-
*
|
|
73
|
-
* Supports:
|
|
74
|
-
* - Format A (local executable): resolves relative args to absolute paths, writes one entry.
|
|
75
|
-
* - Format B (remote URL map): merges all entries directly into mcpServers.
|
|
76
|
-
* - No mcp-config.json: heuristic fallback (scans for .py/.js entry point, logs WARN).
|
|
77
|
-
*
|
|
78
|
-
* The write is idempotent — re-running after a re-download updates existing entries.
|
|
79
|
-
*
|
|
80
|
-
* Returns a McpSetupItem when the registered server needs manual configuration
|
|
81
|
-
* (empty env vars, or a command that might differ across platforms), or null
|
|
82
|
-
* when no action is required from the user.
|
|
83
|
-
*/
|
|
84
|
-
async function registerMcpServer(serverName: string, installDir: string): Promise<McpSetupItem | null> {
|
|
85
|
-
// ── 1. Load mcp-config.json ────────────────────────────────────────────
|
|
86
|
-
const configFilePath = path.join(installDir, 'mcp-config.json');
|
|
87
|
-
let rawConfig: unknown = null;
|
|
88
|
-
|
|
89
|
-
try {
|
|
90
|
-
const raw = await fs.readFile(configFilePath, 'utf-8');
|
|
91
|
-
rawConfig = JSON.parse(raw);
|
|
92
|
-
logger.debug({ serverName, configFilePath }, 'registerMcpServer: loaded mcp-config.json');
|
|
93
|
-
} catch {
|
|
94
|
-
logger.warn(
|
|
95
|
-
{ serverName, configFilePath },
|
|
96
|
-
'registerMcpServer: mcp-config.json not found — falling back to heuristic detection. ' +
|
|
97
|
-
'Add an mcp-config.json to this resource for reliable registration.'
|
|
98
|
-
);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// ── 2. Determine what to merge into mcp.json ──────────────────────────
|
|
102
|
-
// entriesToMerge: map of serverKey → entry object (may have multiple keys for Format B)
|
|
103
|
-
let entriesToMerge: Record<string, unknown> = {};
|
|
104
|
-
|
|
105
|
-
if (rawConfig !== null && typeof rawConfig === 'object') {
|
|
106
|
-
const cfg = rawConfig as Record<string, unknown>;
|
|
107
|
-
|
|
108
|
-
if (typeof cfg['command'] === 'string') {
|
|
109
|
-
// ── Format A: local executable ───────────────────────────────────
|
|
110
|
-
const descriptor = cfg as unknown as LocalMcpDescriptor;
|
|
111
|
-
const key = descriptor.name ?? serverName;
|
|
112
|
-
// Only resolve args that look like relative file paths (contain a dot or
|
|
113
|
-
// path separator). Plain words like "mcp", "start", "--port" are kept as-is.
|
|
114
|
-
const looksLikePath = (a: string) =>
|
|
115
|
-
a.startsWith('./') || a.startsWith('../') || a.includes(path.sep) || /\.\w+$/.test(a);
|
|
116
|
-
const resolvedArgs = (descriptor.args ?? []).map(a =>
|
|
117
|
-
path.isAbsolute(a) || !looksLikePath(a) ? a : path.join(installDir, a)
|
|
118
|
-
);
|
|
119
|
-
entriesToMerge[key] = {
|
|
120
|
-
command: descriptor.command,
|
|
121
|
-
args: resolvedArgs,
|
|
122
|
-
...(descriptor.env && Object.keys(descriptor.env).length > 0
|
|
123
|
-
? { env: descriptor.env }
|
|
124
|
-
: {}),
|
|
125
|
-
};
|
|
126
|
-
logger.info(
|
|
127
|
-
{ serverName, key, command: descriptor.command },
|
|
128
|
-
'registerMcpServer: Format A (local executable)'
|
|
129
|
-
);
|
|
130
|
-
} else {
|
|
131
|
-
// ── Format B: remote URL entries map ─────────────────────────────
|
|
132
|
-
// The entire object is a ready-to-merge mcpServers map.
|
|
133
|
-
entriesToMerge = cfg as RemoteMcpEntries;
|
|
134
|
-
logger.info(
|
|
135
|
-
{ serverName, keys: Object.keys(entriesToMerge) },
|
|
136
|
-
'registerMcpServer: Format B (remote URL entries)'
|
|
137
|
-
);
|
|
138
|
-
}
|
|
139
|
-
} else {
|
|
140
|
-
// ── Heuristic fallback (no mcp-config.json) ───────────────────────
|
|
141
|
-
let entryFile: string | null = null;
|
|
142
|
-
let command = 'python3';
|
|
143
|
-
|
|
144
|
-
try {
|
|
145
|
-
const entries = await fs.readdir(installDir);
|
|
146
|
-
if (entries.includes(`${serverName}.py`)) {
|
|
147
|
-
entryFile = path.join(installDir, `${serverName}.py`); command = 'python3';
|
|
148
|
-
} else if (entries.includes(`${serverName}.js`)) {
|
|
149
|
-
entryFile = path.join(installDir, `${serverName}.js`); command = 'node';
|
|
150
|
-
}
|
|
151
|
-
if (!entryFile) {
|
|
152
|
-
const py = entries.find(f => f.endsWith('.py') && f !== '__init__.py');
|
|
153
|
-
if (py) { entryFile = path.join(installDir, py); command = 'python3'; }
|
|
154
|
-
}
|
|
155
|
-
if (!entryFile) {
|
|
156
|
-
const js = entries.find(f => f.endsWith('.js') || f.endsWith('.mjs'));
|
|
157
|
-
if (js) { entryFile = path.join(installDir, js); command = 'node'; }
|
|
158
|
-
}
|
|
159
|
-
} catch (err) {
|
|
160
|
-
logger.warn({ serverName, installDir, err }, 'registerMcpServer: could not read install directory');
|
|
161
|
-
return null;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
if (!entryFile) {
|
|
165
|
-
logger.warn(
|
|
166
|
-
{ serverName, installDir },
|
|
167
|
-
'registerMcpServer: no entry point found and no mcp-config.json — skipping registration'
|
|
168
|
-
);
|
|
169
|
-
return null;
|
|
170
|
-
}
|
|
171
|
-
entriesToMerge[serverName] = { command, args: [entryFile] };
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// ── 3. Read / create ~/.cursor/mcp.json ───────────────────────────────
|
|
175
|
-
const mcpJsonPath = path.join(getCursorRootDir(), 'mcp.json');
|
|
176
|
-
let mcpConfig: { mcpServers: Record<string, unknown> } = { mcpServers: {} };
|
|
177
|
-
|
|
178
|
-
try {
|
|
179
|
-
const raw = await fs.readFile(mcpJsonPath, 'utf-8');
|
|
180
|
-
const parsed = JSON.parse(raw);
|
|
181
|
-
if (parsed && typeof parsed === 'object' && 'mcpServers' in parsed) {
|
|
182
|
-
mcpConfig = parsed as typeof mcpConfig;
|
|
183
|
-
}
|
|
184
|
-
} catch {
|
|
185
|
-
// File doesn't exist or is corrupt — start fresh
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// Smart-merge each entry into mcpServers:
|
|
189
|
-
// - Structural fields (command, args, url, transport, …): always take the
|
|
190
|
-
// value from mcp-config.json (server is authoritative for structure).
|
|
191
|
-
// - env field: preserve user-filled non-empty values; only add keys that
|
|
192
|
-
// are new or were previously empty (avoids wiping tokens / URLs the user
|
|
193
|
-
// has already configured).
|
|
194
|
-
for (const [key, incoming] of Object.entries(entriesToMerge)) {
|
|
195
|
-
const existing = mcpConfig.mcpServers[key];
|
|
196
|
-
|
|
197
|
-
if (!existing || typeof existing !== 'object') {
|
|
198
|
-
// No prior entry — write as-is.
|
|
199
|
-
mcpConfig.mcpServers[key] = incoming;
|
|
200
|
-
continue;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const incomingEntry = incoming as Record<string, unknown>;
|
|
204
|
-
const existingEntry = existing as Record<string, unknown>;
|
|
205
|
-
|
|
206
|
-
// Merge env: keep user values that are non-empty strings; fill in the rest
|
|
207
|
-
// from the incoming template (which uses empty strings as placeholders).
|
|
208
|
-
const mergedEnv: Record<string, string> = {};
|
|
209
|
-
const incomingEnv = (incomingEntry['env'] ?? {}) as Record<string, string>;
|
|
210
|
-
const existingEnv = (existingEntry['env'] ?? {}) as Record<string, string>;
|
|
211
|
-
|
|
212
|
-
for (const envKey of Object.keys(incomingEnv)) {
|
|
213
|
-
const userVal = existingEnv[envKey];
|
|
214
|
-
// Preserve whatever the user typed; fall back to the template placeholder.
|
|
215
|
-
mergedEnv[envKey] = (typeof userVal === 'string' && userVal !== '')
|
|
216
|
-
? userVal
|
|
217
|
-
: (incomingEnv[envKey] ?? '');
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// Structural fields from server override local, env is smart-merged.
|
|
221
|
-
mcpConfig.mcpServers[key] = {
|
|
222
|
-
...incomingEntry,
|
|
223
|
-
...(Object.keys(mergedEnv).length > 0 ? { env: mergedEnv } : {}),
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// ── 4. Atomic write ────────────────────────────────────────────────────
|
|
228
|
-
const tmpPath = `${mcpJsonPath}.tmp-${process.pid}`;
|
|
229
|
-
try {
|
|
230
|
-
await fs.writeFile(tmpPath, JSON.stringify(mcpConfig, null, 2), 'utf-8');
|
|
231
|
-
await fs.rename(tmpPath, mcpJsonPath);
|
|
232
|
-
logger.info(
|
|
233
|
-
{ serverName, mergedKeys: Object.keys(entriesToMerge), mcpJsonPath },
|
|
234
|
-
'MCP server(s) registered in mcp.json'
|
|
235
|
-
);
|
|
236
|
-
} catch (err) {
|
|
237
|
-
await fs.unlink(tmpPath).catch(() => undefined);
|
|
238
|
-
logger.error({ serverName, err }, 'registerMcpServer: failed to write mcp.json');
|
|
239
|
-
return null;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// ── 5. Detect setup requirements ──────────────────────────────────────
|
|
243
|
-
// Collect env keys that are still empty (user must fill in) and flag
|
|
244
|
-
// commands that may differ across platforms (python vs python3, etc.).
|
|
245
|
-
const AMBIGUOUS_COMMANDS = new Set(['python', 'python3', 'node', 'npx', 'uvx']);
|
|
246
|
-
const missingEnvKeys: string[] = [];
|
|
247
|
-
let commandNeedsVerification = false;
|
|
248
|
-
let registeredCommand = '';
|
|
249
|
-
|
|
250
|
-
for (const entry of Object.values(entriesToMerge)) {
|
|
251
|
-
const e = entry as Record<string, unknown>;
|
|
252
|
-
const env = (e['env'] ?? {}) as Record<string, string>;
|
|
253
|
-
for (const [k, v] of Object.entries(env)) {
|
|
254
|
-
if (v === '') missingEnvKeys.push(k);
|
|
255
|
-
}
|
|
256
|
-
if (typeof e['command'] === 'string') {
|
|
257
|
-
registeredCommand = e['command'];
|
|
258
|
-
if (AMBIGUOUS_COMMANDS.has(registeredCommand)) {
|
|
259
|
-
commandNeedsVerification = true;
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
if (missingEnvKeys.length === 0 && !commandNeedsVerification) {
|
|
265
|
-
return null; // No user action needed
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
// Locate the best available setup/readme doc in the install directory so the
|
|
269
|
-
// user can be pointed to it. Priority: SETUP.md > README.md > README*.md > *.md
|
|
270
|
-
let setupDocPath: string | null = null;
|
|
271
|
-
try {
|
|
272
|
-
const entries = await fs.readdir(installDir);
|
|
273
|
-
const mdFiles = entries.filter(f => /\.md$/i.test(f));
|
|
274
|
-
const pick = (name: string) => mdFiles.find(f => f.toLowerCase() === name.toLowerCase());
|
|
275
|
-
const found =
|
|
276
|
-
pick('SETUP.md') ??
|
|
277
|
-
pick('README.md') ??
|
|
278
|
-
mdFiles.find(f => f.toLowerCase().startsWith('readme')) ??
|
|
279
|
-
mdFiles[0];
|
|
280
|
-
if (found) {
|
|
281
|
-
setupDocPath = path.join(installDir, found);
|
|
282
|
-
}
|
|
283
|
-
} catch {
|
|
284
|
-
// installDir might not exist yet for remote-URL MCPs — ignore
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
const hints: string[] = [];
|
|
288
|
-
if (commandNeedsVerification) {
|
|
289
|
-
hints.push(
|
|
290
|
-
`The command "${registeredCommand}" may differ on your machine ` +
|
|
291
|
-
`(e.g. "python" vs "python3"). ` +
|
|
292
|
-
`Please verify the command in ${mcpJsonPath} under mcpServers["${serverName}"].`
|
|
293
|
-
);
|
|
294
|
-
}
|
|
295
|
-
if (missingEnvKeys.length > 0) {
|
|
296
|
-
hints.push(
|
|
297
|
-
`Fill in the following environment variables in ${mcpJsonPath} ` +
|
|
298
|
-
`under mcpServers["${serverName}"].env: ${missingEnvKeys.join(', ')}.`
|
|
299
|
-
);
|
|
300
|
-
}
|
|
301
|
-
if (setupDocPath) {
|
|
302
|
-
hints.push(`Refer to the setup guide for details: ${setupDocPath}`);
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
return {
|
|
306
|
-
server_name: serverName,
|
|
307
|
-
mcp_json_path: mcpJsonPath,
|
|
308
|
-
missing_env: missingEnvKeys,
|
|
309
|
-
command_needs_verification: commandNeedsVerification,
|
|
310
|
-
command: registeredCommand,
|
|
311
|
-
setup_hint: hints.join(' '),
|
|
312
|
-
...(setupDocPath ? { setup_doc: setupDocPath } : {}),
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
53
|
|
|
316
54
|
export async function syncResources(params: unknown): Promise<ToolResult<SyncResourcesResult>> {
|
|
317
55
|
const startTime = Date.now();
|
|
@@ -368,8 +106,12 @@ export async function syncResources(params: unknown): Promise<ToolResult<SyncRes
|
|
|
368
106
|
});
|
|
369
107
|
}
|
|
370
108
|
|
|
371
|
-
// ── Step 3: Download each subscribed resource
|
|
372
|
-
|
|
109
|
+
// ── Step 3: Download each subscribed resource ──────────────────────────
|
|
110
|
+
// Command / Skill → registered as MCP Prompts on the server (no local I/O)
|
|
111
|
+
// Rule / MCP → file content is returned as LocalAction instructions
|
|
112
|
+
// so that the AI Agent executes the writes on the user's
|
|
113
|
+
// LOCAL machine (not on this potentially remote server).
|
|
114
|
+
logToolStep('sync_resources', 'Step 3: Processing subscribed resources', {
|
|
373
115
|
count: subscriptions.total,
|
|
374
116
|
});
|
|
375
117
|
|
|
@@ -382,7 +124,8 @@ export async function syncResources(params: unknown): Promise<ToolResult<SyncRes
|
|
|
382
124
|
version: string;
|
|
383
125
|
}> = [];
|
|
384
126
|
|
|
385
|
-
|
|
127
|
+
// Accumulated local file-system actions the AI must perform on the user's machine.
|
|
128
|
+
const localActions: LocalAction[] = [];
|
|
386
129
|
|
|
387
130
|
for (let i = 0; i < subscriptions.subscriptions.length; i++) {
|
|
388
131
|
const sub = subscriptions.subscriptions[i];
|
|
@@ -535,141 +278,171 @@ export async function syncResources(params: unknown): Promise<ToolResult<SyncRes
|
|
|
535
278
|
}
|
|
536
279
|
|
|
537
280
|
if (isRemoteUrlMcp) {
|
|
538
|
-
// Remote-URL MCP: no local files
|
|
539
|
-
//
|
|
281
|
+
// Remote-URL MCP (Format B): no local files needed.
|
|
282
|
+
// Return a merge_mcp_json action so the AI updates ~/.cursor/mcp.json
|
|
283
|
+
// on the user's LOCAL machine, not on this (possibly remote) server.
|
|
540
284
|
const configContent = firstFile!.content;
|
|
541
285
|
const mcpJsonPath = path.join(getCursorRootDir(), 'mcp.json');
|
|
542
|
-
let mcpConfig: { mcpServers: Record<string, unknown> } = { mcpServers: {} };
|
|
543
|
-
try {
|
|
544
|
-
const raw = await fs.readFile(mcpJsonPath, 'utf-8');
|
|
545
|
-
const p = JSON.parse(raw);
|
|
546
|
-
if (p && typeof p === 'object' && 'mcpServers' in p) {
|
|
547
|
-
mcpConfig = p as typeof mcpConfig;
|
|
548
|
-
}
|
|
549
|
-
} catch { /* file missing or corrupt — start fresh */ }
|
|
550
|
-
|
|
551
286
|
const entries = JSON.parse(configContent) as Record<string, unknown>;
|
|
552
|
-
// Smart-merge: structural fields from server; preserve user env values.
|
|
553
|
-
for (const [key, incoming] of Object.entries(entries)) {
|
|
554
|
-
const existing = mcpConfig.mcpServers[key];
|
|
555
|
-
if (!existing || typeof existing !== 'object') {
|
|
556
|
-
mcpConfig.mcpServers[key] = incoming;
|
|
557
|
-
} else {
|
|
558
|
-
const inc = incoming as Record<string, unknown>;
|
|
559
|
-
const ext = existing as Record<string, unknown>;
|
|
560
|
-
const inEnv = (inc['env'] ?? {}) as Record<string, string>;
|
|
561
|
-
const exEnv = (ext['env'] ?? {}) as Record<string, string>;
|
|
562
|
-
const mergedEnv: Record<string, string> = {};
|
|
563
|
-
for (const k of Object.keys(inEnv)) {
|
|
564
|
-
const userVal = exEnv[k];
|
|
565
|
-
mergedEnv[k] = (typeof userVal === 'string' && userVal !== '') ? userVal : (inEnv[k] ?? '');
|
|
566
|
-
}
|
|
567
|
-
mcpConfig.mcpServers[key] = {
|
|
568
|
-
...inc,
|
|
569
|
-
...(Object.keys(mergedEnv).length > 0 ? { env: mergedEnv } : {}),
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
const tmpPath = `${mcpJsonPath}.tmp-${process.pid}`;
|
|
575
|
-
await fs.writeFile(tmpPath, JSON.stringify(mcpConfig, null, 2), 'utf-8');
|
|
576
|
-
await fs.rename(tmpPath, mcpJsonPath);
|
|
577
287
|
|
|
578
|
-
|
|
579
|
-
const remoteMissingEnv: string[] = [];
|
|
580
|
-
for (const entry of Object.values(entries)) {
|
|
288
|
+
for (const [serverName, entry] of Object.entries(entries)) {
|
|
581
289
|
const e = entry as Record<string, unknown>;
|
|
582
290
|
const env = (e['env'] ?? {}) as Record<string, string>;
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
server_name: sub.name,
|
|
291
|
+
const missingEnv = Object.entries(env)
|
|
292
|
+
.filter(([, v]) => v === '')
|
|
293
|
+
.map(([k]) => k);
|
|
294
|
+
|
|
295
|
+
const action: MergeMcpJsonAction = {
|
|
296
|
+
action: 'merge_mcp_json',
|
|
590
297
|
mcp_json_path: mcpJsonPath,
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
298
|
+
server_name: serverName,
|
|
299
|
+
entry: e,
|
|
300
|
+
...(missingEnv.length > 0 ? {
|
|
301
|
+
missing_env: missingEnv,
|
|
302
|
+
setup_hint:
|
|
303
|
+
`Fill in the following environment variables in ${mcpJsonPath} ` +
|
|
304
|
+
`under mcpServers["${serverName}"]: ${missingEnv.join(', ')}.`,
|
|
305
|
+
} : {}),
|
|
306
|
+
};
|
|
307
|
+
localActions.push(action);
|
|
599
308
|
}
|
|
600
309
|
|
|
601
310
|
tally.synced++;
|
|
602
311
|
details.push({ id: sub.id, name: sub.name, action: 'synced', version: resourceVersion });
|
|
603
|
-
logToolStep('sync_resources', 'Remote-URL MCP
|
|
312
|
+
logToolStep('sync_resources', 'Remote-URL MCP: merge_mcp_json action queued for AI', {
|
|
604
313
|
resourceId: sub.id,
|
|
605
|
-
|
|
314
|
+
serverKeys: Object.keys(entries),
|
|
606
315
|
});
|
|
607
316
|
continue;
|
|
608
317
|
}
|
|
609
318
|
|
|
610
|
-
//
|
|
611
|
-
//
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
let alreadyPresent = false;
|
|
615
|
-
try {
|
|
616
|
-
await fs.access(destPath);
|
|
617
|
-
alreadyPresent = true;
|
|
618
|
-
} catch { /* not present — fall through to write */ }
|
|
319
|
+
// ── Rule resource ─────────────────────────────────────────────────────
|
|
320
|
+
// Return write_file actions; the AI writes the files locally.
|
|
321
|
+
if (sub.type === 'rule') {
|
|
322
|
+
const typeDir = getCursorTypeDir(sub.type);
|
|
619
323
|
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
324
|
+
for (const file of downloadResult.files) {
|
|
325
|
+
const normalised = path.normalize(file.path);
|
|
326
|
+
if (normalised.startsWith('..')) {
|
|
327
|
+
logger.warn({ resourceId: sub.id, filePath: file.path }, 'Skipping suspicious file path');
|
|
328
|
+
continue;
|
|
624
329
|
}
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
330
|
+
localActions.push({
|
|
331
|
+
action: 'write_file',
|
|
332
|
+
path: path.join(typeDir, normalised),
|
|
333
|
+
content: file.content,
|
|
629
334
|
});
|
|
630
|
-
continue;
|
|
631
335
|
}
|
|
336
|
+
|
|
337
|
+
tally.synced++;
|
|
338
|
+
details.push({ id: sub.id, name: sub.name, action: 'synced', version: resourceVersion });
|
|
339
|
+
logToolStep('sync_resources', 'Rule: write_file actions queued for AI', {
|
|
340
|
+
resourceId: sub.id,
|
|
341
|
+
fileCount: downloadResult.files.length,
|
|
342
|
+
});
|
|
343
|
+
continue;
|
|
632
344
|
}
|
|
633
345
|
|
|
634
|
-
//
|
|
635
|
-
|
|
636
|
-
|
|
346
|
+
// ── Local-executable MCP resource (Format A — has "command" field) ───
|
|
347
|
+
// Return write_file + merge_mcp_json actions; the AI performs them locally.
|
|
348
|
+
if (sub.type === 'mcp') {
|
|
349
|
+
const typeDir = getCursorTypeDir(sub.type);
|
|
350
|
+
const installDir = path.join(typeDir, sub.name);
|
|
351
|
+
|
|
352
|
+
// Queue file writes.
|
|
353
|
+
for (const file of downloadResult.files) {
|
|
354
|
+
const normalised = path.normalize(file.path);
|
|
355
|
+
if (normalised.startsWith('..')) {
|
|
356
|
+
logger.warn({ resourceId: sub.id, filePath: file.path }, 'Skipping suspicious file path');
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
localActions.push({
|
|
360
|
+
action: 'write_file',
|
|
361
|
+
path: path.join(installDir, normalised),
|
|
362
|
+
content: file.content,
|
|
363
|
+
});
|
|
364
|
+
}
|
|
637
365
|
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
366
|
+
// Build the mcp.json entry from the downloaded descriptor.
|
|
367
|
+
// We replicate the Format-A detection logic from registerMcpServer()
|
|
368
|
+
// but without touching the server filesystem.
|
|
369
|
+
const mcpJsonPath = path.join(getCursorRootDir(), 'mcp.json');
|
|
370
|
+
let mcpEntry: Record<string, unknown> = {};
|
|
371
|
+
let missingEnv: string[] = [];
|
|
372
|
+
let setupHint: string | undefined;
|
|
373
|
+
let setupDoc: string | undefined;
|
|
374
|
+
|
|
375
|
+
const descriptorFile = downloadResult.files.find(
|
|
376
|
+
(f) => path.basename(f.path) === 'mcp-config.json',
|
|
377
|
+
);
|
|
378
|
+
if (descriptorFile) {
|
|
379
|
+
try {
|
|
380
|
+
const cfg = JSON.parse(descriptorFile.content) as Record<string, unknown>;
|
|
381
|
+
if (typeof cfg['command'] === 'string') {
|
|
382
|
+
// Format A: single-server descriptor
|
|
383
|
+
mcpEntry = cfg;
|
|
384
|
+
} else {
|
|
385
|
+
// Format B disguised as local — treat whole object as entries map
|
|
386
|
+
mcpEntry = cfg;
|
|
387
|
+
}
|
|
388
|
+
} catch { /* malformed — leave entry empty */ }
|
|
389
|
+
}
|
|
643
390
|
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
391
|
+
// Detect missing env vars.
|
|
392
|
+
const envBlock = (mcpEntry['env'] ?? {}) as Record<string, string>;
|
|
393
|
+
missingEnv = Object.entries(envBlock).filter(([, v]) => v === '').map(([k]) => k);
|
|
394
|
+
if (missingEnv.length > 0) {
|
|
395
|
+
setupHint =
|
|
396
|
+
`Fill in the following environment variables in ${mcpJsonPath} ` +
|
|
397
|
+
`under mcpServers["${sub.name}"]: ${missingEnv.join(', ')}.`;
|
|
398
|
+
}
|
|
647
399
|
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
400
|
+
// Check for a setup doc among downloaded files.
|
|
401
|
+
const readmeFile = downloadResult.files.find((f) =>
|
|
402
|
+
/readme/i.test(path.basename(f.path)) && f.path.endsWith('.md'),
|
|
403
|
+
);
|
|
404
|
+
if (readmeFile) {
|
|
405
|
+
setupDoc = path.join(installDir, readmeFile.path);
|
|
654
406
|
}
|
|
655
|
-
const writePath = path.join(writeRoot, normalised);
|
|
656
|
-
await fs.mkdir(path.dirname(writePath), { recursive: true });
|
|
657
|
-
await fs.writeFile(writePath, file.content, 'utf-8');
|
|
658
|
-
}
|
|
659
407
|
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
408
|
+
const mergeMcpAction: MergeMcpJsonAction = {
|
|
409
|
+
action: 'merge_mcp_json',
|
|
410
|
+
mcp_json_path: mcpJsonPath,
|
|
411
|
+
server_name: sub.name,
|
|
412
|
+
entry: Object.keys(mcpEntry).length > 0 ? mcpEntry : {
|
|
413
|
+
// Fallback: auto-detect entry point from file list.
|
|
414
|
+
command: (() => {
|
|
415
|
+
const jsEntry = downloadResult.files.find((f) => f.path.endsWith('.js'));
|
|
416
|
+
const pyEntry = downloadResult.files.find((f) => f.path.endsWith('.py'));
|
|
417
|
+
if (jsEntry) return 'node';
|
|
418
|
+
if (pyEntry) return 'python3';
|
|
419
|
+
return 'node';
|
|
420
|
+
})(),
|
|
421
|
+
args: [(() => {
|
|
422
|
+
const jsEntry = downloadResult.files.find((f) => f.path.endsWith('.js'));
|
|
423
|
+
const pyEntry = downloadResult.files.find((f) => f.path.endsWith('.py'));
|
|
424
|
+
const entryFile = jsEntry ?? pyEntry ?? downloadResult.files[0];
|
|
425
|
+
return path.join(installDir, entryFile?.path ?? '');
|
|
426
|
+
})()],
|
|
427
|
+
},
|
|
428
|
+
...(missingEnv.length > 0 ? { missing_env: missingEnv, setup_hint: setupHint } : {}),
|
|
429
|
+
...(setupDoc ? { setup_doc: setupDoc } : {}),
|
|
430
|
+
};
|
|
431
|
+
localActions.push(mergeMcpAction);
|
|
432
|
+
|
|
433
|
+
tally.synced++;
|
|
434
|
+
details.push({ id: sub.id, name: sub.name, action: 'synced', version: resourceVersion });
|
|
435
|
+
logToolStep('sync_resources', 'Local-executable MCP: write_file + merge_mcp_json actions queued for AI', {
|
|
436
|
+
resourceId: sub.id,
|
|
437
|
+
fileCount: downloadResult.files.length,
|
|
438
|
+
});
|
|
439
|
+
continue;
|
|
664
440
|
}
|
|
665
441
|
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
destPath,
|
|
671
|
-
fileCount: downloadResult.files.length,
|
|
672
|
-
});
|
|
442
|
+
// Fallback for any unrecognised types (should not happen in practice).
|
|
443
|
+
logger.warn({ resourceId: sub.id, type: sub.type }, 'Unrecognised resource type — skipping');
|
|
444
|
+
tally.failed++;
|
|
445
|
+
details.push({ id: sub.id, name: sub.name, action: 'failed', version: resourceVersion });
|
|
673
446
|
|
|
674
447
|
} catch (error) {
|
|
675
448
|
logger.error({
|
|
@@ -693,7 +466,7 @@ export async function syncResources(params: unknown): Promise<ToolResult<SyncRes
|
|
|
693
466
|
health_score: healthScore,
|
|
694
467
|
summary: tally,
|
|
695
468
|
details,
|
|
696
|
-
...(
|
|
469
|
+
...(localActions.length > 0 ? { local_actions_required: localActions } : {}),
|
|
697
470
|
};
|
|
698
471
|
|
|
699
472
|
const duration = Date.now() - startTime;
|
|
@@ -762,7 +535,16 @@ export async function syncResources(params: unknown): Promise<ToolResult<SyncRes
|
|
|
762
535
|
// Tool definition for registry
|
|
763
536
|
export const syncResourcesTool = {
|
|
764
537
|
name: 'sync_resources',
|
|
765
|
-
description:
|
|
538
|
+
description:
|
|
539
|
+
'Synchronize subscribed AI resources. ' +
|
|
540
|
+
'Command and Skill resources are registered as MCP Prompts on the server. ' +
|
|
541
|
+
'Rule and MCP resources are returned as `local_actions_required` — an ordered list of ' +
|
|
542
|
+
'write_file, merge_mcp_json, or other actions that the AI Agent MUST execute on the ' +
|
|
543
|
+
'USER\'S LOCAL MACHINE after receiving the response. ' +
|
|
544
|
+
'Execute every action in the list before reporting success to the user. ' +
|
|
545
|
+
'For merge_mcp_json actions: read the existing ~/.cursor/mcp.json, smart-merge the ' +
|
|
546
|
+
'provided entry (preserve existing user env values), then write the file back. ' +
|
|
547
|
+
'For write_file actions: create any missing parent directories then write the file.',
|
|
766
548
|
inputSchema: {
|
|
767
549
|
type: 'object' as const,
|
|
768
550
|
properties: {
|