@codelia/cli 0.1.86 → 0.1.90
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/dist/auth-VNP4GLGX.js +66 -0
- package/dist/chunk-BFVVMMRM.js +202 -0
- package/dist/chunk-PG452V5E.js +45 -0
- package/dist/chunk-QYWLK4HY.js +156 -0
- package/dist/chunk-S7OVJIGV.js +1052 -0
- package/dist/index.cjs +3243 -1564
- package/dist/index.js +48 -1575
- package/dist/launch-OTCP4VZR.js +9 -0
- package/dist/launcher-TKAK6K4J.js +19 -0
- package/dist/mcp-GB4CGP6K.js +699 -0
- package/dist/prompt-mode-BYUIUSIO.js +705 -0
- package/dist/session-2EB4JKFW.js +52 -0
- package/dist/update-SEBHPMUD.js +124 -0
- package/package.json +10 -10
|
@@ -0,0 +1,699 @@
|
|
|
1
|
+
// src/commands/mcp-auth.ts
|
|
2
|
+
import { parseArgs } from "util";
|
|
3
|
+
|
|
4
|
+
// src/args.ts
|
|
5
|
+
import { cac } from "cac";
|
|
6
|
+
var parseWithCac = (values) => {
|
|
7
|
+
const cli = cac("codelia-args");
|
|
8
|
+
cli.command("[...positionals]").allowUnknownOptions();
|
|
9
|
+
const parsed = cli.parse(["node", "codelia-args", ...values], {
|
|
10
|
+
run: false
|
|
11
|
+
});
|
|
12
|
+
return {
|
|
13
|
+
args: [...parsed.args],
|
|
14
|
+
options: parsed.options
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
var parseBoolean = (value, flagName) => {
|
|
18
|
+
const normalized = value.trim().toLowerCase();
|
|
19
|
+
if (normalized === "true") return true;
|
|
20
|
+
if (normalized === "false") return false;
|
|
21
|
+
throw new Error(`${flagName} must be true|false`);
|
|
22
|
+
};
|
|
23
|
+
var parseTimeout = (value) => {
|
|
24
|
+
const parsed = Number.parseInt(value, 10);
|
|
25
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
26
|
+
throw new Error("--request-timeout-ms must be a positive integer");
|
|
27
|
+
}
|
|
28
|
+
return parsed;
|
|
29
|
+
};
|
|
30
|
+
var parseEpochMs = (value, flagName) => {
|
|
31
|
+
const parsed = Number.parseInt(value, 10);
|
|
32
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
33
|
+
throw new Error(`${flagName} must be a positive integer (epoch ms)`);
|
|
34
|
+
}
|
|
35
|
+
return parsed;
|
|
36
|
+
};
|
|
37
|
+
var parseKeyValue = (raw, flagName) => {
|
|
38
|
+
const [key, ...rest] = raw.split("=");
|
|
39
|
+
const value = rest.join("=");
|
|
40
|
+
if (!key || !value) {
|
|
41
|
+
throw new Error(`${flagName} must be key=value`);
|
|
42
|
+
}
|
|
43
|
+
return [key, value];
|
|
44
|
+
};
|
|
45
|
+
var parseCliArgs = (values) => {
|
|
46
|
+
const parsed = parseWithCac(values);
|
|
47
|
+
return {
|
|
48
|
+
positionals: parsed.args,
|
|
49
|
+
options: parsed.options
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
var readOptionValues = (parsed, flagName) => {
|
|
53
|
+
const value = parsed.options[flagName];
|
|
54
|
+
if (value == null || value === false || value === true) return [];
|
|
55
|
+
const entries = Array.isArray(value) ? value : [value];
|
|
56
|
+
return entries.map((entry) => String(entry));
|
|
57
|
+
};
|
|
58
|
+
var getLastFlagValue = (parsed, flagName) => {
|
|
59
|
+
const values = readOptionValues(parsed, flagName);
|
|
60
|
+
if (!values || values.length === 0) return void 0;
|
|
61
|
+
return values[values.length - 1];
|
|
62
|
+
};
|
|
63
|
+
var getAllFlagValues = (parsed, flagName) => readOptionValues(parsed, flagName);
|
|
64
|
+
var hasBooleanFlag = (parsed, flagName) => parsed.options[flagName] === true;
|
|
65
|
+
|
|
66
|
+
// src/mcp/auth-file.ts
|
|
67
|
+
import { McpAuthStore } from "@codelia/storage";
|
|
68
|
+
var readMcpAuth = async () => {
|
|
69
|
+
return new McpAuthStore().load();
|
|
70
|
+
};
|
|
71
|
+
var updateMcpAuth = async (mutate) => {
|
|
72
|
+
return new McpAuthStore().update(mutate);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// src/commands/mcp-config.ts
|
|
76
|
+
import path from "path";
|
|
77
|
+
import {
|
|
78
|
+
loadMcpServers,
|
|
79
|
+
removeMcpServerConfig,
|
|
80
|
+
setMcpServerEnabled,
|
|
81
|
+
upsertMcpServerConfig
|
|
82
|
+
} from "@codelia/config-loader";
|
|
83
|
+
import {
|
|
84
|
+
isSameConfigFilePath,
|
|
85
|
+
isTrustedGlobalConfigLocationSync,
|
|
86
|
+
resolveStoragePaths
|
|
87
|
+
} from "@codelia/storage";
|
|
88
|
+
import { z } from "zod";
|
|
89
|
+
|
|
90
|
+
// src/mcp/protocol.ts
|
|
91
|
+
import {
|
|
92
|
+
assertSupportedMcpProtocolVersion,
|
|
93
|
+
getInitializeProtocolVersion,
|
|
94
|
+
getMcpProtocolVersion
|
|
95
|
+
} from "@codelia/protocol";
|
|
96
|
+
var assertSupportedProtocolVersion = (value) => {
|
|
97
|
+
assertSupportedMcpProtocolVersion(value);
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// src/mcp/probe.ts
|
|
101
|
+
var DEFAULT_MCP_TIMEOUT_MS = 3e4;
|
|
102
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
103
|
+
var postHttpJson = async (url, body, headers, timeoutMs, redirect) => {
|
|
104
|
+
const controller = new AbortController();
|
|
105
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
106
|
+
try {
|
|
107
|
+
const response = await fetch(url, {
|
|
108
|
+
method: "POST",
|
|
109
|
+
redirect,
|
|
110
|
+
headers,
|
|
111
|
+
body: JSON.stringify(body),
|
|
112
|
+
signal: controller.signal
|
|
113
|
+
});
|
|
114
|
+
if (!response.ok) {
|
|
115
|
+
const bodyText = await response.text().catch(() => "");
|
|
116
|
+
throw new Error(`HTTP ${response.status}: ${bodyText.slice(0, 300)}`);
|
|
117
|
+
}
|
|
118
|
+
const text = await response.text();
|
|
119
|
+
const sessionId = response.headers.get("MCP-Session-Id") ?? void 0;
|
|
120
|
+
if (!text.trim()) return { body: null, sessionId };
|
|
121
|
+
return { body: JSON.parse(text), sessionId };
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (controller.signal.aborted) {
|
|
124
|
+
throw new Error(`request timed out after ${timeoutMs}ms`);
|
|
125
|
+
}
|
|
126
|
+
throw error;
|
|
127
|
+
} finally {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
var parseRpcResult = (raw, requestId) => {
|
|
132
|
+
if (Array.isArray(raw)) {
|
|
133
|
+
const found = raw.find(
|
|
134
|
+
(entry) => isRecord(entry) && String(entry.id ?? "") === requestId
|
|
135
|
+
);
|
|
136
|
+
if (!found) {
|
|
137
|
+
throw new Error(`missing response id=${requestId}`);
|
|
138
|
+
}
|
|
139
|
+
return parseRpcResult(found, requestId);
|
|
140
|
+
}
|
|
141
|
+
if (!isRecord(raw)) {
|
|
142
|
+
throw new Error("invalid JSON-RPC response");
|
|
143
|
+
}
|
|
144
|
+
if (isRecord(raw.error)) {
|
|
145
|
+
throw new Error(
|
|
146
|
+
`RPC ${String(raw.error.code)}: ${String(raw.error.message)}`
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
return raw.result;
|
|
150
|
+
};
|
|
151
|
+
var parseToolsResponse = (raw) => {
|
|
152
|
+
if (!isRecord(raw)) return { count: 0 };
|
|
153
|
+
const tools = Array.isArray(raw.tools) ? raw.tools.length : 0;
|
|
154
|
+
const nextCursor = typeof raw.nextCursor === "string" ? raw.nextCursor : typeof raw.next_cursor === "string" ? raw.next_cursor : void 0;
|
|
155
|
+
return { count: tools, nextCursor };
|
|
156
|
+
};
|
|
157
|
+
var probeHttpServer = async (config) => {
|
|
158
|
+
let seq = 0;
|
|
159
|
+
let sessionId;
|
|
160
|
+
const timeoutMs = config.request_timeout_ms ?? DEFAULT_MCP_TIMEOUT_MS;
|
|
161
|
+
const protocolVersion = getMcpProtocolVersion();
|
|
162
|
+
const baseHeaders = {
|
|
163
|
+
"Content-Type": "application/json",
|
|
164
|
+
Accept: "application/json, text/event-stream",
|
|
165
|
+
"MCP-Protocol-Version": protocolVersion,
|
|
166
|
+
...config.headers ?? {}
|
|
167
|
+
};
|
|
168
|
+
const hasConfiguredHeaders = Object.keys(config.headers ?? {}).length > 0;
|
|
169
|
+
const send = async (message) => {
|
|
170
|
+
const raw = await postHttpJson(
|
|
171
|
+
config.url ?? "",
|
|
172
|
+
{ jsonrpc: "2.0", ...message },
|
|
173
|
+
{ ...baseHeaders, ...sessionId ? { "MCP-Session-Id": sessionId } : {} },
|
|
174
|
+
timeoutMs,
|
|
175
|
+
hasConfiguredHeaders || sessionId ? "error" : "follow"
|
|
176
|
+
);
|
|
177
|
+
if (raw.sessionId) sessionId = raw.sessionId;
|
|
178
|
+
return raw.body;
|
|
179
|
+
};
|
|
180
|
+
const request = async (method, params) => {
|
|
181
|
+
const id = `cli-${++seq}`;
|
|
182
|
+
return parseRpcResult(await send({ id, method, params }), id);
|
|
183
|
+
};
|
|
184
|
+
const initResult = await request("initialize", {
|
|
185
|
+
protocolVersion,
|
|
186
|
+
clientInfo: { name: "codelia-cli", version: "0.1.0" },
|
|
187
|
+
capabilities: {}
|
|
188
|
+
});
|
|
189
|
+
assertSupportedProtocolVersion(initResult);
|
|
190
|
+
await send({ method: "notifications/initialized", params: {} });
|
|
191
|
+
let total = 0;
|
|
192
|
+
let cursor;
|
|
193
|
+
for (let page = 0; page < 100; page += 1) {
|
|
194
|
+
const result = await request("tools/list", cursor ? { cursor } : {});
|
|
195
|
+
const parsed = parseToolsResponse(result);
|
|
196
|
+
total += parsed.count;
|
|
197
|
+
if (!parsed.nextCursor) break;
|
|
198
|
+
cursor = parsed.nextCursor;
|
|
199
|
+
}
|
|
200
|
+
return total;
|
|
201
|
+
};
|
|
202
|
+
var probeStdioServer = async (config, serverId) => {
|
|
203
|
+
const { createLocalMcpStdioProbeClient } = await import("@codelia/runtime/sdk");
|
|
204
|
+
const client = await createLocalMcpStdioProbeClient(serverId, config);
|
|
205
|
+
const options = {
|
|
206
|
+
timeoutMs: config.request_timeout_ms ?? DEFAULT_MCP_TIMEOUT_MS
|
|
207
|
+
};
|
|
208
|
+
try {
|
|
209
|
+
const initResult = await client.request(
|
|
210
|
+
"initialize",
|
|
211
|
+
{
|
|
212
|
+
protocolVersion: getMcpProtocolVersion(),
|
|
213
|
+
clientInfo: { name: "codelia-cli", version: "0.1.0" },
|
|
214
|
+
capabilities: {}
|
|
215
|
+
},
|
|
216
|
+
options
|
|
217
|
+
);
|
|
218
|
+
assertSupportedProtocolVersion(initResult);
|
|
219
|
+
await client.notify("notifications/initialized", {});
|
|
220
|
+
let total = 0;
|
|
221
|
+
let cursor;
|
|
222
|
+
for (let page = 0; page < 100; page += 1) {
|
|
223
|
+
const result = await client.request(
|
|
224
|
+
"tools/list",
|
|
225
|
+
cursor ? { cursor } : {},
|
|
226
|
+
options
|
|
227
|
+
);
|
|
228
|
+
const parsed = parseToolsResponse(result);
|
|
229
|
+
total += parsed.count;
|
|
230
|
+
if (!parsed.nextCursor) break;
|
|
231
|
+
cursor = parsed.nextCursor;
|
|
232
|
+
}
|
|
233
|
+
return total;
|
|
234
|
+
} finally {
|
|
235
|
+
await client.close();
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
var probeServer = async (config, serverId) => {
|
|
239
|
+
if (config.transport === "http") {
|
|
240
|
+
return probeHttpServer(config);
|
|
241
|
+
}
|
|
242
|
+
return probeStdioServer(config, serverId);
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// src/commands/mcp-config.ts
|
|
246
|
+
var TIMEOUT_SCHEMA = z.number().positive().transform((value) => Math.round(value));
|
|
247
|
+
var OAUTH_SCHEMA = z.object({
|
|
248
|
+
authorization_url: z.string(),
|
|
249
|
+
token_url: z.string(),
|
|
250
|
+
registration_url: z.string(),
|
|
251
|
+
client_id: z.string(),
|
|
252
|
+
client_secret: z.string(),
|
|
253
|
+
scope: z.string()
|
|
254
|
+
}).partial();
|
|
255
|
+
var HTTP_SERVER_CONFIG_SCHEMA = z.object({
|
|
256
|
+
transport: z.literal("http"),
|
|
257
|
+
enabled: z.boolean().optional(),
|
|
258
|
+
url: z.string(),
|
|
259
|
+
headers: z.record(z.string(), z.string()).optional(),
|
|
260
|
+
env: z.record(z.string(), z.string()).optional(),
|
|
261
|
+
request_timeout_ms: TIMEOUT_SCHEMA.optional(),
|
|
262
|
+
oauth: OAUTH_SCHEMA.optional()
|
|
263
|
+
});
|
|
264
|
+
var STDIO_SERVER_CONFIG_SCHEMA = z.object({
|
|
265
|
+
transport: z.literal("stdio"),
|
|
266
|
+
enabled: z.boolean().optional(),
|
|
267
|
+
command: z.string(),
|
|
268
|
+
args: z.array(z.string()).optional(),
|
|
269
|
+
cwd: z.string().optional(),
|
|
270
|
+
env: z.record(z.string(), z.string()).optional(),
|
|
271
|
+
request_timeout_ms: TIMEOUT_SCHEMA.optional(),
|
|
272
|
+
oauth: OAUTH_SCHEMA.optional()
|
|
273
|
+
});
|
|
274
|
+
var MCP_SERVER_CONFIG_SCHEMA = z.union([
|
|
275
|
+
HTTP_SERVER_CONFIG_SCHEMA,
|
|
276
|
+
STDIO_SERVER_CONFIG_SCHEMA
|
|
277
|
+
]);
|
|
278
|
+
var describeError = (error) => error instanceof Error ? error.message : String(error);
|
|
279
|
+
var readEnvValue = (key) => {
|
|
280
|
+
const value = process.env[key];
|
|
281
|
+
if (!value) return void 0;
|
|
282
|
+
const trimmed = value.trim();
|
|
283
|
+
return trimmed ? trimmed : void 0;
|
|
284
|
+
};
|
|
285
|
+
var resolveGlobalConfigPath = () => {
|
|
286
|
+
const envPath = readEnvValue("CODELIA_CONFIG_PATH");
|
|
287
|
+
if (envPath) return path.resolve(envPath);
|
|
288
|
+
const storage = resolveStoragePaths();
|
|
289
|
+
return storage.configFile;
|
|
290
|
+
};
|
|
291
|
+
var resolveProjectConfigPath = () => path.resolve(process.cwd(), ".codelia", "config.json");
|
|
292
|
+
var resolveDistinctProjectConfigPath = () => {
|
|
293
|
+
const projectPath = resolveProjectConfigPath();
|
|
294
|
+
return isSameConfigFilePath(resolveGlobalConfigPath(), projectPath) ? null : projectPath;
|
|
295
|
+
};
|
|
296
|
+
var SHARED_CONFIG_SCOPE_ERROR = "Project config shares the global config file in this workspace; pass --scope global to update it.";
|
|
297
|
+
var normalizeServerConfig = (value) => {
|
|
298
|
+
const parsed = MCP_SERVER_CONFIG_SCHEMA.safeParse(value);
|
|
299
|
+
return parsed.success ? parsed.data : null;
|
|
300
|
+
};
|
|
301
|
+
var normalizeEntries = (servers, source) => {
|
|
302
|
+
const entries = [];
|
|
303
|
+
for (const [id, rawConfig] of Object.entries(servers)) {
|
|
304
|
+
const config = normalizeServerConfig(rawConfig);
|
|
305
|
+
if (!config) continue;
|
|
306
|
+
entries.push({ id, config, source });
|
|
307
|
+
}
|
|
308
|
+
return entries.sort((left, right) => left.id.localeCompare(right.id));
|
|
309
|
+
};
|
|
310
|
+
var loadEntriesByScope = async (scope) => {
|
|
311
|
+
const globalPath = resolveGlobalConfigPath();
|
|
312
|
+
const projectPath = resolveDistinctProjectConfigPath();
|
|
313
|
+
const globalServers = await loadMcpServers(globalPath);
|
|
314
|
+
const projectServers = projectPath ? await loadMcpServers(projectPath) : {};
|
|
315
|
+
const globalSource = isTrustedGlobalConfigLocationSync(
|
|
316
|
+
process.cwd(),
|
|
317
|
+
globalPath
|
|
318
|
+
) ? "global" : "project";
|
|
319
|
+
if (scope === "global") {
|
|
320
|
+
return normalizeEntries(globalServers, "global");
|
|
321
|
+
}
|
|
322
|
+
if (scope === "project") {
|
|
323
|
+
return normalizeEntries(projectServers, "project");
|
|
324
|
+
}
|
|
325
|
+
const merged = /* @__PURE__ */ new Map();
|
|
326
|
+
for (const entry of normalizeEntries(globalServers, globalSource)) {
|
|
327
|
+
merged.set(entry.id, entry);
|
|
328
|
+
}
|
|
329
|
+
for (const entry of normalizeEntries(projectServers, "project")) {
|
|
330
|
+
merged.set(entry.id, entry);
|
|
331
|
+
}
|
|
332
|
+
return Array.from(merged.values()).sort(
|
|
333
|
+
(left, right) => left.id.localeCompare(right.id)
|
|
334
|
+
);
|
|
335
|
+
};
|
|
336
|
+
var resolveMutableScope = (parsed) => {
|
|
337
|
+
const scopeRaw = getLastFlagValue(parsed, "scope") ?? "project";
|
|
338
|
+
if (scopeRaw === "project" || scopeRaw === "global") {
|
|
339
|
+
return scopeRaw;
|
|
340
|
+
}
|
|
341
|
+
throw new Error("--scope must be project|global");
|
|
342
|
+
};
|
|
343
|
+
var resolveListScope = (parsed) => {
|
|
344
|
+
const scopeRaw = getLastFlagValue(parsed, "scope") ?? "effective";
|
|
345
|
+
if (scopeRaw === "project" || scopeRaw === "global" || scopeRaw === "effective") {
|
|
346
|
+
return scopeRaw;
|
|
347
|
+
}
|
|
348
|
+
throw new Error("--scope must be effective|project|global");
|
|
349
|
+
};
|
|
350
|
+
var buildServerConfigFromAdd = (parsed) => {
|
|
351
|
+
const transport = getLastFlagValue(parsed, "transport");
|
|
352
|
+
if (transport !== "http" && transport !== "stdio") {
|
|
353
|
+
throw new Error("--transport must be http|stdio");
|
|
354
|
+
}
|
|
355
|
+
const enabledRaw = getLastFlagValue(parsed, "enabled");
|
|
356
|
+
const enabled = enabledRaw ? parseBoolean(enabledRaw, "--enabled") : true;
|
|
357
|
+
const timeoutRaw = getLastFlagValue(parsed, "request-timeout-ms");
|
|
358
|
+
const requestTimeoutMs = timeoutRaw ? parseTimeout(timeoutRaw) : void 0;
|
|
359
|
+
const oauth = {
|
|
360
|
+
authorization_url: getLastFlagValue(parsed, "oauth-authorization-url"),
|
|
361
|
+
token_url: getLastFlagValue(parsed, "oauth-token-url"),
|
|
362
|
+
registration_url: getLastFlagValue(parsed, "oauth-registration-url"),
|
|
363
|
+
client_id: getLastFlagValue(parsed, "oauth-client-id"),
|
|
364
|
+
client_secret: getLastFlagValue(parsed, "oauth-client-secret"),
|
|
365
|
+
scope: getLastFlagValue(parsed, "oauth-scope")
|
|
366
|
+
};
|
|
367
|
+
const oauthConfig = Object.fromEntries(
|
|
368
|
+
Object.entries(oauth).filter(([, value]) => !!value)
|
|
369
|
+
);
|
|
370
|
+
if (transport === "http") {
|
|
371
|
+
const url = getLastFlagValue(parsed, "url");
|
|
372
|
+
if (!url) throw new Error("--url is required when --transport=http");
|
|
373
|
+
const headers = Object.fromEntries(
|
|
374
|
+
getAllFlagValues(parsed, "header").map(
|
|
375
|
+
(value) => parseKeyValue(value, "--header")
|
|
376
|
+
)
|
|
377
|
+
);
|
|
378
|
+
return {
|
|
379
|
+
transport,
|
|
380
|
+
...enabled !== true ? { enabled } : {},
|
|
381
|
+
url,
|
|
382
|
+
...Object.keys(headers).length ? { headers } : {},
|
|
383
|
+
...requestTimeoutMs ? { request_timeout_ms: requestTimeoutMs } : {},
|
|
384
|
+
...oauthConfig && Object.keys(oauthConfig).length ? { oauth: oauthConfig } : {}
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
const command = getLastFlagValue(parsed, "command");
|
|
388
|
+
if (!command) {
|
|
389
|
+
throw new Error("--command is required when --transport=stdio");
|
|
390
|
+
}
|
|
391
|
+
const env = Object.fromEntries(
|
|
392
|
+
getAllFlagValues(parsed, "env").map(
|
|
393
|
+
(value) => parseKeyValue(value, "--env")
|
|
394
|
+
)
|
|
395
|
+
);
|
|
396
|
+
const args = getAllFlagValues(parsed, "arg");
|
|
397
|
+
const cwd = getLastFlagValue(parsed, "cwd");
|
|
398
|
+
return {
|
|
399
|
+
transport,
|
|
400
|
+
...enabled !== true ? { enabled } : {},
|
|
401
|
+
command,
|
|
402
|
+
...args.length ? { args } : {},
|
|
403
|
+
...cwd ? { cwd } : {},
|
|
404
|
+
...Object.keys(env).length ? { env } : {},
|
|
405
|
+
...requestTimeoutMs ? { request_timeout_ms: requestTimeoutMs } : {},
|
|
406
|
+
...oauthConfig && Object.keys(oauthConfig).length ? { oauth: oauthConfig } : {}
|
|
407
|
+
};
|
|
408
|
+
};
|
|
409
|
+
var printStaticList = (entries) => {
|
|
410
|
+
if (!entries.length) {
|
|
411
|
+
console.log("no MCP servers configured");
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
console.log("id transport source enabled");
|
|
415
|
+
for (const entry of entries) {
|
|
416
|
+
const enabled = entry.config.enabled !== false;
|
|
417
|
+
console.log(
|
|
418
|
+
`${entry.id} ${entry.config.transport} ${entry.source} ${enabled}`
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
var runMcpConfigCommand = async (subcommand, rest) => {
|
|
423
|
+
const parsed = parseCliArgs(rest);
|
|
424
|
+
if (subcommand === "list") {
|
|
425
|
+
const scope = resolveListScope(parsed);
|
|
426
|
+
const entries = await loadEntriesByScope(scope);
|
|
427
|
+
printStaticList(entries);
|
|
428
|
+
return 0;
|
|
429
|
+
}
|
|
430
|
+
if (subcommand === "add") {
|
|
431
|
+
const serverId = parsed.positionals[0];
|
|
432
|
+
if (!serverId) {
|
|
433
|
+
console.error(
|
|
434
|
+
"usage: codelia mcp add <server-id> --transport <http|stdio> ..."
|
|
435
|
+
);
|
|
436
|
+
return 1;
|
|
437
|
+
}
|
|
438
|
+
const scope = resolveMutableScope(parsed);
|
|
439
|
+
const configPath = scope === "global" ? resolveGlobalConfigPath() : resolveDistinctProjectConfigPath();
|
|
440
|
+
if (!configPath) {
|
|
441
|
+
console.error(SHARED_CONFIG_SCOPE_ERROR);
|
|
442
|
+
return 1;
|
|
443
|
+
}
|
|
444
|
+
const servers = await loadMcpServers(configPath);
|
|
445
|
+
const replace = hasBooleanFlag(parsed, "replace");
|
|
446
|
+
if (servers[serverId] !== void 0 && !replace) {
|
|
447
|
+
console.error(`server already exists in ${scope} scope: ${serverId}`);
|
|
448
|
+
console.error("pass --replace to overwrite");
|
|
449
|
+
return 1;
|
|
450
|
+
}
|
|
451
|
+
const serverConfig = buildServerConfigFromAdd(parsed);
|
|
452
|
+
await upsertMcpServerConfig(configPath, serverId, serverConfig);
|
|
453
|
+
console.log(`added MCP server '${serverId}' (${scope})`);
|
|
454
|
+
return 0;
|
|
455
|
+
}
|
|
456
|
+
if (subcommand === "remove" || subcommand === "enable" || subcommand === "disable") {
|
|
457
|
+
const serverId = parsed.positionals[0];
|
|
458
|
+
if (!serverId) {
|
|
459
|
+
console.error(
|
|
460
|
+
`usage: codelia mcp ${subcommand} <server-id> [--scope project|global]`
|
|
461
|
+
);
|
|
462
|
+
return 1;
|
|
463
|
+
}
|
|
464
|
+
const scope = resolveMutableScope(parsed);
|
|
465
|
+
const configPath = scope === "global" ? resolveGlobalConfigPath() : resolveDistinctProjectConfigPath();
|
|
466
|
+
if (!configPath) {
|
|
467
|
+
console.error(SHARED_CONFIG_SCOPE_ERROR);
|
|
468
|
+
return 1;
|
|
469
|
+
}
|
|
470
|
+
if (subcommand === "remove") {
|
|
471
|
+
const removed = await removeMcpServerConfig(configPath, serverId);
|
|
472
|
+
if (!removed) {
|
|
473
|
+
console.error(`server not found in ${scope} scope: ${serverId}`);
|
|
474
|
+
return 1;
|
|
475
|
+
}
|
|
476
|
+
} else {
|
|
477
|
+
const updated = await setMcpServerEnabled(
|
|
478
|
+
configPath,
|
|
479
|
+
serverId,
|
|
480
|
+
subcommand === "enable"
|
|
481
|
+
);
|
|
482
|
+
if (!updated) {
|
|
483
|
+
console.error(`server not found in ${scope} scope: ${serverId}`);
|
|
484
|
+
return 1;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
console.log(`${subcommand}d MCP server '${serverId}' (${scope})`);
|
|
488
|
+
return 0;
|
|
489
|
+
}
|
|
490
|
+
if (subcommand === "test") {
|
|
491
|
+
const serverId = parsed.positionals[0];
|
|
492
|
+
if (!serverId) {
|
|
493
|
+
console.error(
|
|
494
|
+
"usage: codelia mcp test <server-id> [--scope effective|project|global]"
|
|
495
|
+
);
|
|
496
|
+
return 1;
|
|
497
|
+
}
|
|
498
|
+
const scope = resolveListScope(parsed);
|
|
499
|
+
const entries = await loadEntriesByScope(scope);
|
|
500
|
+
const target = entries.find((entry) => entry.id === serverId);
|
|
501
|
+
if (!target) {
|
|
502
|
+
console.error(`server not found: ${serverId} (scope=${scope})`);
|
|
503
|
+
return 1;
|
|
504
|
+
}
|
|
505
|
+
try {
|
|
506
|
+
const storedEntry = target.config.transport === "http" && target.config.url ? (await readMcpAuth()).servers[target.id] : void 0;
|
|
507
|
+
let accessToken;
|
|
508
|
+
if (target.config.transport === "http" && target.config.url && storedEntry) {
|
|
509
|
+
const { fetchDiscoveredOAuthConfig, mcpEntryMatchesServer } = await import("@codelia/runtime/sdk");
|
|
510
|
+
const discovered = storedEntry.binding.issuer || storedEntry.binding.token_endpoint ? await fetchDiscoveredOAuthConfig(
|
|
511
|
+
target.config.url,
|
|
512
|
+
AbortSignal.timeout(target.config.request_timeout_ms ?? 3e4)
|
|
513
|
+
) : {};
|
|
514
|
+
if (mcpEntryMatchesServer(storedEntry, target.config, discovered)) {
|
|
515
|
+
accessToken = storedEntry.tokens.access_token;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const configForTest = target.config.transport === "http" && accessToken ? {
|
|
519
|
+
...target.config,
|
|
520
|
+
headers: {
|
|
521
|
+
...target.config.headers ?? {},
|
|
522
|
+
Authorization: `Bearer ${accessToken}`
|
|
523
|
+
}
|
|
524
|
+
} : target.config;
|
|
525
|
+
const tools = await probeServer(configForTest, target.id);
|
|
526
|
+
console.log(
|
|
527
|
+
`MCP test succeeded: id=${target.id} transport=${target.config.transport} source=${target.source} tools=${tools}`
|
|
528
|
+
);
|
|
529
|
+
return 0;
|
|
530
|
+
} catch (error) {
|
|
531
|
+
console.error(
|
|
532
|
+
`MCP test failed: id=${target.id} transport=${target.config.transport}: ${describeError(error)}`
|
|
533
|
+
);
|
|
534
|
+
return 1;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
return -1;
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
// src/commands/mcp-auth.ts
|
|
541
|
+
var runMcpAuthCommand = async (values) => {
|
|
542
|
+
const [subcommand, ...rest] = values;
|
|
543
|
+
const parsed = parseArgs({
|
|
544
|
+
args: rest,
|
|
545
|
+
allowPositionals: true,
|
|
546
|
+
options: {
|
|
547
|
+
"access-token": { type: "string" },
|
|
548
|
+
"refresh-token": { type: "string" },
|
|
549
|
+
"expires-at": { type: "string" },
|
|
550
|
+
"expires-in": { type: "string" },
|
|
551
|
+
"token-type": { type: "string" },
|
|
552
|
+
"token-url": { type: "string" },
|
|
553
|
+
"client-id": { type: "string" },
|
|
554
|
+
url: { type: "string" },
|
|
555
|
+
issuer: { type: "string" },
|
|
556
|
+
scope: { type: "string" }
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
if (!subcommand) {
|
|
560
|
+
console.error("usage: codelia mcp auth <list|set|clear> ...");
|
|
561
|
+
return 1;
|
|
562
|
+
}
|
|
563
|
+
if (subcommand === "list") {
|
|
564
|
+
const auth = await readMcpAuth();
|
|
565
|
+
const entries = Object.entries(auth.servers).sort(
|
|
566
|
+
([a], [b]) => a.localeCompare(b)
|
|
567
|
+
);
|
|
568
|
+
if (!entries.length) {
|
|
569
|
+
console.log("no MCP auth tokens configured");
|
|
570
|
+
return 0;
|
|
571
|
+
}
|
|
572
|
+
console.log("server_id resource_uri has_refresh expires_at");
|
|
573
|
+
for (const [serverId, entry] of entries) {
|
|
574
|
+
console.log(
|
|
575
|
+
`${serverId} ${entry.binding.resource_uri} ${entry.tokens.refresh_token ? "yes" : "no"} ${entry.tokens.expires_at ?? "-"}`
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
return 0;
|
|
579
|
+
}
|
|
580
|
+
if (subcommand === "set") {
|
|
581
|
+
const serverId = parsed.positionals[0];
|
|
582
|
+
if (!serverId) {
|
|
583
|
+
console.error(
|
|
584
|
+
"usage: codelia mcp auth set <server-id> --access-token <token> [--url <resource-uri>] [--issuer <issuer>] [--token-url <url>] [--client-id <id>] [--refresh-token <token>] [--expires-at <epoch_ms>] [--expires-in <sec>] [--scope <scope>] [--token-type <type>]"
|
|
585
|
+
);
|
|
586
|
+
return 1;
|
|
587
|
+
}
|
|
588
|
+
const accessToken = parsed.values["access-token"];
|
|
589
|
+
if (!accessToken) {
|
|
590
|
+
console.error("--access-token is required");
|
|
591
|
+
return 1;
|
|
592
|
+
}
|
|
593
|
+
const configuredEntries = await loadEntriesByScope("effective").catch(
|
|
594
|
+
() => []
|
|
595
|
+
);
|
|
596
|
+
const configuredServer = configuredEntries.find(
|
|
597
|
+
(entry) => entry.id === serverId
|
|
598
|
+
)?.config;
|
|
599
|
+
const resourceUri = parsed.values.url ?? configuredServer?.url;
|
|
600
|
+
if (!resourceUri) {
|
|
601
|
+
console.error(
|
|
602
|
+
"--url is required when the MCP server URL is not configured"
|
|
603
|
+
);
|
|
604
|
+
return 1;
|
|
605
|
+
}
|
|
606
|
+
const { fetchDiscoveredOAuthConfig, resolveMcpServerBinding } = await import("@codelia/runtime/sdk");
|
|
607
|
+
const refreshToken = parsed.values["refresh-token"];
|
|
608
|
+
const issuer = parsed.values.issuer;
|
|
609
|
+
const tokenUrl = parsed.values["token-url"] ?? configuredServer?.oauth?.token_url;
|
|
610
|
+
const clientId = parsed.values["client-id"] ?? configuredServer?.oauth?.client_id;
|
|
611
|
+
const discovered = (refreshToken || configuredServer?.oauth || tokenUrl) && (!issuer || !tokenUrl) ? await fetchDiscoveredOAuthConfig(
|
|
612
|
+
resourceUri,
|
|
613
|
+
AbortSignal.timeout(configuredServer?.request_timeout_ms ?? 3e4)
|
|
614
|
+
) : {};
|
|
615
|
+
const binding = resolveMcpServerBinding(
|
|
616
|
+
{ url: resourceUri },
|
|
617
|
+
{
|
|
618
|
+
issuer: issuer ?? discovered.issuer,
|
|
619
|
+
token_url: tokenUrl ?? discovered.token_url,
|
|
620
|
+
authorization_url: configuredServer?.oauth?.authorization_url ?? discovered.authorization_url,
|
|
621
|
+
client_id: clientId
|
|
622
|
+
}
|
|
623
|
+
);
|
|
624
|
+
if (!binding || refreshToken && !binding.token_endpoint) {
|
|
625
|
+
console.error(
|
|
626
|
+
"A valid MCP URL is required. For a refresh token, configure or specify --token-url if discovery is unavailable."
|
|
627
|
+
);
|
|
628
|
+
return 1;
|
|
629
|
+
}
|
|
630
|
+
const expiresAtRaw = parsed.values["expires-at"];
|
|
631
|
+
const expiresInRaw = parsed.values["expires-in"];
|
|
632
|
+
let expiresAt;
|
|
633
|
+
if (expiresAtRaw) {
|
|
634
|
+
expiresAt = parseEpochMs(expiresAtRaw, "--expires-at");
|
|
635
|
+
} else if (expiresInRaw) {
|
|
636
|
+
expiresAt = Date.now() + parseTimeout(expiresInRaw) * 1e3;
|
|
637
|
+
}
|
|
638
|
+
const scope = parsed.values.scope;
|
|
639
|
+
const tokenType = parsed.values["token-type"];
|
|
640
|
+
await updateMcpAuth((auth) => {
|
|
641
|
+
auth.servers[serverId] = {
|
|
642
|
+
binding,
|
|
643
|
+
tokens: {
|
|
644
|
+
access_token: accessToken,
|
|
645
|
+
...refreshToken ? { refresh_token: refreshToken } : {},
|
|
646
|
+
...expiresAt ? { expires_at: expiresAt } : {},
|
|
647
|
+
...scope ? { scope } : {},
|
|
648
|
+
...tokenType ? { token_type: tokenType } : {},
|
|
649
|
+
...clientId ? { client_id: clientId } : {}
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
});
|
|
653
|
+
console.log(`stored MCP auth token for '${serverId}'`);
|
|
654
|
+
return 0;
|
|
655
|
+
}
|
|
656
|
+
if (subcommand === "clear") {
|
|
657
|
+
const serverId = parsed.positionals[0];
|
|
658
|
+
if (!serverId) {
|
|
659
|
+
console.error("usage: codelia mcp auth clear <server-id>");
|
|
660
|
+
return 1;
|
|
661
|
+
}
|
|
662
|
+
const existed = await updateMcpAuth((auth) => {
|
|
663
|
+
if (!auth.servers[serverId]) return false;
|
|
664
|
+
delete auth.servers[serverId];
|
|
665
|
+
return true;
|
|
666
|
+
});
|
|
667
|
+
if (!existed) {
|
|
668
|
+
console.error(`no token found for server: ${serverId}`);
|
|
669
|
+
return 1;
|
|
670
|
+
}
|
|
671
|
+
console.log(`cleared MCP auth token for '${serverId}'`);
|
|
672
|
+
return 0;
|
|
673
|
+
}
|
|
674
|
+
console.error(`unknown auth subcommand: ${subcommand}`);
|
|
675
|
+
return 1;
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
// src/commands/mcp.ts
|
|
679
|
+
var runMcpCommand = async (values) => {
|
|
680
|
+
const [subcommand, ...rest] = values;
|
|
681
|
+
if (!subcommand) {
|
|
682
|
+
console.error(
|
|
683
|
+
"usage: codelia mcp <add|list|remove|enable|disable|test|auth> ..."
|
|
684
|
+
);
|
|
685
|
+
return 1;
|
|
686
|
+
}
|
|
687
|
+
if (subcommand === "auth") {
|
|
688
|
+
return runMcpAuthCommand(rest);
|
|
689
|
+
}
|
|
690
|
+
const handled = await runMcpConfigCommand(subcommand, rest);
|
|
691
|
+
if (handled >= 0) {
|
|
692
|
+
return handled;
|
|
693
|
+
}
|
|
694
|
+
console.error(`unknown subcommand: ${subcommand}`);
|
|
695
|
+
return 1;
|
|
696
|
+
};
|
|
697
|
+
export {
|
|
698
|
+
runMcpCommand
|
|
699
|
+
};
|