@postmcp/cli 0.1.0

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/index.js ADDED
@@ -0,0 +1,828 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ ALL_PRESETS: () => import_presets.ALL_PRESETS,
35
+ BUNDLED_PRESETS: () => BUNDLED_PRESETS,
36
+ PRESETS_BY_ID: () => import_presets.PRESETS_BY_ID,
37
+ Preset: () => import_presets.Preset,
38
+ buildClientConfigSnippet: () => buildClientConfigSnippet,
39
+ buildPresetAuthConfig: () => import_presets.buildPresetAuthConfig,
40
+ estimateSpecTokenSavings: () => estimateSpecTokenSavings,
41
+ exportCommand: () => exportCommand,
42
+ findStudioDir: () => findStudioDir,
43
+ generateCommand: () => generateCommand,
44
+ generatePythonProject: () => import_core6.generatePythonProject,
45
+ generateTypeScriptProject: () => import_core5.generateTypeScriptProject,
46
+ getClientConfigPath: () => getClientConfigPath,
47
+ getPreset: () => import_presets.getPreset,
48
+ getPresetCacheDir: () => getPresetCacheDir,
49
+ inspectCommand: () => inspectCommand,
50
+ listPresetsCommand: () => listPresetsCommand,
51
+ loadConfigFile: () => loadConfigFile,
52
+ loadEnvFile: () => loadEnvFile,
53
+ parseApiKeyFlag: () => parseApiKeyFlag,
54
+ parseHeaderFlags: () => parseHeaderFlags,
55
+ resolvePresetSpec: () => resolvePresetSpec,
56
+ runCommand: () => runCommand,
57
+ studioCommand: () => studioCommand,
58
+ syncAllPresets: () => syncAllPresets,
59
+ syncPresetsCommand: () => syncPresetsCommand,
60
+ waitForServer: () => waitForServer
61
+ });
62
+ module.exports = __toCommonJS(index_exports);
63
+
64
+ // src/commands/run.ts
65
+ var import_core = require("@postmcp/core");
66
+
67
+ // src/config/loader.ts
68
+ var fs = __toESM(require("fs"));
69
+ var path = __toESM(require("path"));
70
+ var import_dotenv = __toESM(require("dotenv"));
71
+ function loadEnvFile(envFilePath) {
72
+ if (envFilePath) {
73
+ const resolved = path.resolve(envFilePath);
74
+ if (fs.existsSync(resolved)) {
75
+ import_dotenv.default.config({ path: resolved });
76
+ }
77
+ } else {
78
+ const defaultEnv = path.resolve(process.cwd(), ".env");
79
+ if (fs.existsSync(defaultEnv)) {
80
+ import_dotenv.default.config({ path: defaultEnv });
81
+ }
82
+ }
83
+ }
84
+ function loadConfigFile(configPath) {
85
+ let targetPath = configPath ? path.resolve(configPath) : null;
86
+ if (!targetPath) {
87
+ const candidates = ["postmcp.config.json", "postmcp.json", ".postmcprc.json"];
88
+ for (const c of candidates) {
89
+ const candidatePath = path.resolve(process.cwd(), c);
90
+ if (fs.existsSync(candidatePath)) {
91
+ targetPath = candidatePath;
92
+ break;
93
+ }
94
+ }
95
+ }
96
+ if (targetPath && fs.existsSync(targetPath)) {
97
+ try {
98
+ const content = fs.readFileSync(targetPath, "utf-8");
99
+ return JSON.parse(content);
100
+ } catch {
101
+ return {};
102
+ }
103
+ }
104
+ return {};
105
+ }
106
+ function parseHeaderFlags(headers) {
107
+ if (!headers || !Array.isArray(headers)) return {};
108
+ const result = {};
109
+ for (const h of headers) {
110
+ const colonIdx = h.indexOf(":");
111
+ if (colonIdx !== -1) {
112
+ const key = h.slice(0, colonIdx).trim();
113
+ const val = h.slice(colonIdx + 1).trim();
114
+ if (key && val) {
115
+ result[key] = val;
116
+ }
117
+ }
118
+ }
119
+ return result;
120
+ }
121
+ function parseApiKeyFlag(apiKeyStr) {
122
+ if (!apiKeyStr) return void 0;
123
+ let location = "header";
124
+ let rest = apiKeyStr;
125
+ if (apiKeyStr.startsWith("query:")) {
126
+ location = "query";
127
+ rest = apiKeyStr.slice(6);
128
+ } else if (apiKeyStr.startsWith("header:")) {
129
+ location = "header";
130
+ rest = apiKeyStr.slice(7);
131
+ } else if (apiKeyStr.startsWith("cookie:")) {
132
+ location = "cookie";
133
+ rest = apiKeyStr.slice(7);
134
+ }
135
+ const eqIdx = rest.indexOf("=");
136
+ if (eqIdx !== -1) {
137
+ const name = rest.slice(0, eqIdx).trim();
138
+ const value = rest.slice(eqIdx + 1).trim();
139
+ if (name && value) {
140
+ return { name, value, in: location };
141
+ }
142
+ }
143
+ return void 0;
144
+ }
145
+
146
+ // src/presets/index.ts
147
+ var fs2 = __toESM(require("fs"));
148
+ var path2 = __toESM(require("path"));
149
+ var os = __toESM(require("os"));
150
+ var import_axios = __toESM(require("axios"));
151
+ var import_presets = require("@postmcp/presets");
152
+ var BUNDLED_PRESETS = import_presets.PRESETS_BY_ID;
153
+ function getPresetCacheDir() {
154
+ try {
155
+ const dir = path2.join(os.homedir(), ".postmcp", "presets");
156
+ if (!fs2.existsSync(dir)) {
157
+ fs2.mkdirSync(dir, { recursive: true });
158
+ }
159
+ return dir;
160
+ } catch {
161
+ const fallbackDir = path2.join(os.tmpdir(), "postmcp-presets");
162
+ if (!fs2.existsSync(fallbackDir)) {
163
+ try {
164
+ fs2.mkdirSync(fallbackDir, { recursive: true });
165
+ } catch {
166
+ }
167
+ }
168
+ return fallbackDir;
169
+ }
170
+ }
171
+ async function resolvePresetSpec(presetIdOrAlias) {
172
+ const cleanId = presetIdOrAlias.replace(/^@/, "").toLowerCase().trim();
173
+ const preset = (0, import_presets.getPreset)(cleanId);
174
+ if (!preset) {
175
+ throw new Error(`Unknown preset '@${cleanId}'. Run 'postmcp presets list' to see all available presets.`);
176
+ }
177
+ const cacheDir = getPresetCacheDir();
178
+ const cacheFile = path2.join(cacheDir, `${cleanId}.json`);
179
+ if (fs2.existsSync(cacheFile)) {
180
+ return cacheFile;
181
+ }
182
+ if (preset.specUrl) {
183
+ try {
184
+ const res = await import_axios.default.get(preset.specUrl, { timeout: 8e3, responseType: "text" });
185
+ try {
186
+ fs2.writeFileSync(cacheFile, res.data, "utf-8");
187
+ return cacheFile;
188
+ } catch {
189
+ return res.data;
190
+ }
191
+ } catch {
192
+ }
193
+ }
194
+ if (preset.bundledSpec) {
195
+ try {
196
+ fs2.writeFileSync(cacheFile, JSON.stringify(preset.bundledSpec, null, 2), "utf-8");
197
+ return cacheFile;
198
+ } catch {
199
+ return preset.bundledSpec;
200
+ }
201
+ }
202
+ if (preset.specUrl) {
203
+ return preset.specUrl;
204
+ }
205
+ throw new Error(`Preset '@${cleanId}' has no specification available.`);
206
+ }
207
+ async function syncAllPresets() {
208
+ const synced = [];
209
+ const cacheDir = getPresetCacheDir();
210
+ for (const preset of import_presets.ALL_PRESETS) {
211
+ const filePath = path2.join(cacheDir, `${preset.id}.json`);
212
+ let wrote = false;
213
+ if (preset.specUrl) {
214
+ try {
215
+ const res = await import_axios.default.get(preset.specUrl, { timeout: 8e3, responseType: "text" });
216
+ fs2.writeFileSync(filePath, res.data, "utf-8");
217
+ wrote = true;
218
+ } catch {
219
+ }
220
+ }
221
+ if (!wrote && preset.bundledSpec) {
222
+ try {
223
+ fs2.writeFileSync(filePath, JSON.stringify(preset.bundledSpec, null, 2), "utf-8");
224
+ wrote = true;
225
+ } catch {
226
+ }
227
+ }
228
+ if (wrote) {
229
+ synced.push(preset.id);
230
+ }
231
+ }
232
+ return synced;
233
+ }
234
+
235
+ // src/commands/run.ts
236
+ var import_picocolors = __toESM(require("picocolors"));
237
+ async function runCommand(specArg, options) {
238
+ loadEnvFile(options.envFile);
239
+ const fileConfig = loadConfigFile(options.config);
240
+ let specPath = specArg || fileConfig.spec;
241
+ if (!specPath) {
242
+ console.error(import_picocolors.default.red("Error: No OpenAPI spec provided. Usage: postmcp run <spec-path-or-url-or-@preset>"));
243
+ process.exit(1);
244
+ return;
245
+ }
246
+ let preset = void 0;
247
+ if (typeof specPath === "string" && specPath.startsWith("@")) {
248
+ preset = (0, import_presets.getPreset)(specPath);
249
+ try {
250
+ specPath = await resolvePresetSpec(specPath);
251
+ } catch (err) {
252
+ console.error(import_picocolors.default.red(`Error resolving preset: ${err.message}`));
253
+ process.exit(1);
254
+ return;
255
+ }
256
+ }
257
+ let parsedSpec;
258
+ try {
259
+ parsedSpec = await (0, import_core.parseOpenAPI)(specPath);
260
+ } catch (err) {
261
+ console.error(import_picocolors.default.red(`Failed to parse OpenAPI specification: ${err.message}`));
262
+ process.exit(1);
263
+ return;
264
+ }
265
+ if (preset && preset.macros && preset.macros.length > 0) {
266
+ parsedSpec.macros = [...parsedSpec.macros || [], ...preset.macros];
267
+ }
268
+ if (fileConfig.macros && fileConfig.macros.length > 0) {
269
+ parsedSpec.macros = [...parsedSpec.macros || [], ...fileConfig.macros];
270
+ }
271
+ if (fileConfig.enabledOperations && Object.keys(fileConfig.enabledOperations).length > 0) {
272
+ parsedSpec.operations = parsedSpec.operations.filter(
273
+ (op) => fileConfig.enabledOperations[op.id] !== false
274
+ );
275
+ }
276
+ const cliHeaders = parseHeaderFlags(options.header);
277
+ const cliApiKey = parseApiKeyFlag(options.apiKey);
278
+ const presetAuthConfig = preset ? (0, import_presets.buildPresetAuthConfig)(preset, process.env) : {};
279
+ const authConfig = {
280
+ headers: { ...presetAuthConfig.headers, ...fileConfig.auth?.headers, ...cliHeaders },
281
+ bearerToken: options.bearer || fileConfig.auth?.bearerToken || presetAuthConfig.bearerToken || process.env.API_KEY || process.env.BEARER_TOKEN,
282
+ apiKey: cliApiKey || fileConfig.auth?.apiKey || presetAuthConfig.apiKey,
283
+ basicAuth: fileConfig.auth?.basicAuth || presetAuthConfig.basicAuth,
284
+ securitySchemes: {
285
+ ...presetAuthConfig.securitySchemes,
286
+ ...fileConfig.auth?.securitySchemes
287
+ },
288
+ allowedExternalHosts: fileConfig.auth?.allowedExternalHosts,
289
+ allowCrossOriginAuth: fileConfig.auth?.allowCrossOriginAuth
290
+ };
291
+ const transport = options.transport || fileConfig.transport || (options.port ? "http" : "stdio");
292
+ const resolvedBaseUrl = options.baseUrl || fileConfig.baseUrl || process.env.BASE_URL || (parsedSpec.servers.length > 0 ? parsedSpec.servers[0].url : preset?.defaultBaseUrl);
293
+ const isJit = options.jit !== void 0 ? options.jit : fileConfig.jit !== void 0 ? fileConfig.jit : void 0;
294
+ const isDryRun = options.dryRun !== void 0 ? options.dryRun : fileConfig.dryRun;
295
+ const isTokenDiet = options.tokenDiet !== void 0 ? options.tokenDiet : fileConfig.tokenDiet?.enabled !== false;
296
+ const maxTokens = options.maxTokens ? parseInt(options.maxTokens, 10) : fileConfig.tokenDiet?.maxTokens || 2500;
297
+ const pathFieldMasks = {};
298
+ if (preset?.fieldMasks) {
299
+ for (const fm of preset.fieldMasks) {
300
+ pathFieldMasks[fm.path] = fm.fields;
301
+ }
302
+ }
303
+ if (fileConfig.fieldMasks) {
304
+ Object.assign(pathFieldMasks, fileConfig.fieldMasks);
305
+ }
306
+ const serverOptions = {
307
+ spec: parsedSpec,
308
+ baseUrl: resolvedBaseUrl,
309
+ auth: authConfig,
310
+ jit: isJit,
311
+ dryRun: isDryRun,
312
+ tokenDiet: {
313
+ enabled: isTokenDiet,
314
+ maxTokens,
315
+ pathFieldMasks: isTokenDiet && Object.keys(pathFieldMasks).length > 0 ? pathFieldMasks : void 0,
316
+ convertToMarkdownTable: fileConfig.tokenDiet?.convertToMarkdownTable !== false
317
+ },
318
+ serverName: parsedSpec.title,
319
+ serverVersion: parsedSpec.version
320
+ };
321
+ if (transport === "http") {
322
+ const port = options.port ? parseInt(options.port, 10) : fileConfig.port || 3e3;
323
+ const host = options.host || "localhost";
324
+ const { url } = await (0, import_core.startHttpServer)({
325
+ ...serverOptions,
326
+ port,
327
+ host
328
+ });
329
+ console.log(import_picocolors.default.green(`PostMCP Streamable HTTP server listening at: ${import_picocolors.default.bold(url)}`));
330
+ console.log(import_picocolors.default.dim(` Service: ${parsedSpec.title} (v${parsedSpec.version}) | Endpoints: ${parsedSpec.operations.length}`));
331
+ if (isDryRun) {
332
+ console.log(import_picocolors.default.yellow(` Mode: DRY-RUN SIMULATION (Mutations simulated, no real side effects)`));
333
+ }
334
+ } else {
335
+ await (0, import_core.startStdioServer)(serverOptions);
336
+ }
337
+ }
338
+
339
+ // src/commands/inspect.ts
340
+ var import_core2 = require("@postmcp/core");
341
+ var import_cli_table3 = __toESM(require("cli-table3"));
342
+ var import_picocolors2 = __toESM(require("picocolors"));
343
+ function estimateSpecTokenSavings(spec) {
344
+ const rawTokensPerOp = spec.operations.map((op) => {
345
+ const descLen = (op.description || op.summary || "").length;
346
+ const schemaLen = JSON.stringify(op.inputSchema || {}).length;
347
+ return Math.ceil((descLen + schemaLen + 50) / 4);
348
+ });
349
+ const totalRawToolTokens = rawTokensPerOp.reduce((a, b) => a + b, 0);
350
+ const avgOpTokens = spec.operations.length > 0 ? Math.ceil(totalRawToolTokens / spec.operations.length) : 0;
351
+ const jitPromptTokens = 120 + Math.min(spec.operations.length, 5) * Math.ceil(avgOpTokens * 0.4);
352
+ const raw = Math.max(totalRawToolTokens, 200);
353
+ const optimized = Math.min(raw, jitPromptTokens);
354
+ const savingsPct = Math.max(15, Math.round((raw - optimized) / raw * 100));
355
+ return {
356
+ rawTokens: raw,
357
+ optimizedTokens: optimized,
358
+ savingsPct
359
+ };
360
+ }
361
+ async function inspectCommand(specArg, options) {
362
+ let specPath = specArg;
363
+ if (!specPath) {
364
+ console.error(import_picocolors2.default.red("Error: No OpenAPI spec provided. Usage: postmcp inspect <spec-path-or-url-or-@preset>"));
365
+ process.exit(1);
366
+ return;
367
+ }
368
+ let preset = void 0;
369
+ if (typeof specPath === "string" && specPath.startsWith("@")) {
370
+ preset = (0, import_presets.getPreset)(specPath);
371
+ try {
372
+ specPath = await resolvePresetSpec(specPath);
373
+ } catch (err) {
374
+ console.error(import_picocolors2.default.red(`Error resolving preset: ${err.message}`));
375
+ process.exit(1);
376
+ return;
377
+ }
378
+ }
379
+ let spec;
380
+ try {
381
+ spec = await (0, import_core2.parseOpenAPI)(specPath);
382
+ if (preset && preset.macros && preset.macros.length > 0) {
383
+ spec.macros = [...spec.macros || [], ...preset.macros];
384
+ }
385
+ } catch (err) {
386
+ console.error(import_picocolors2.default.red(`Failed to parse specification: ${err.message}`));
387
+ process.exit(1);
388
+ return;
389
+ }
390
+ if (options.json) {
391
+ console.log(JSON.stringify(spec, null, 2));
392
+ return;
393
+ }
394
+ const tokenMetrics = estimateSpecTokenSavings(spec);
395
+ console.log();
396
+ console.log(import_picocolors2.default.bold(import_picocolors2.default.cyan(`PostMCP API Inspection: ${spec.title} (v${spec.version})`)));
397
+ if (spec.description) {
398
+ console.log(import_picocolors2.default.dim(spec.description.slice(0, 120) + (spec.description.length > 120 ? "..." : "")));
399
+ }
400
+ console.log();
401
+ const overviewTable = new import_cli_table3.default({
402
+ head: [import_picocolors2.default.bold("Metric"), import_picocolors2.default.bold("Value")],
403
+ colWidths: [25, 55]
404
+ });
405
+ const totalOps = spec.operations.length;
406
+ const methodsCount = {};
407
+ const riskCounts = { READ_ONLY: 0, MUTATION: 0, CRITICAL: 0 };
408
+ for (const op of spec.operations) {
409
+ const m = op.method.toUpperCase();
410
+ methodsCount[m] = (methodsCount[m] || 0) + 1;
411
+ riskCounts[op.riskTier] = (riskCounts[op.riskTier] || 0) + 1;
412
+ }
413
+ const methodsStr = Object.entries(methodsCount).map(([m, c]) => `${m}: ${c}`).join(" | ");
414
+ const defaultUrl = spec.servers.length > 0 ? spec.servers[0].url : "None declared";
415
+ const secSchemes = Object.keys(spec.securitySchemes).join(", ") || "None declared";
416
+ const recommendedJit = totalOps > 20 ? import_picocolors2.default.green("Yes (Dynamic JIT routing recommended)") : import_picocolors2.default.blue("No (Static direct tools)");
417
+ const savingsDisplay = import_picocolors2.default.green(`~${tokenMetrics.savingsPct}% (${tokenMetrics.rawTokens.toLocaleString()} \u2192 ${tokenMetrics.optimizedTokens.toLocaleString()} tokens)`);
418
+ overviewTable.push(
419
+ ["Total Endpoints", `${totalOps} operations`],
420
+ ["HTTP Methods", methodsStr],
421
+ ["Base URL", defaultUrl],
422
+ ["Security Schemes", secSchemes],
423
+ ["JIT Router Mode", recommendedJit],
424
+ ["Est. Token Savings", savingsDisplay],
425
+ ["Macros / Workflows", `${spec.macros?.length || 0} composite macros`]
426
+ );
427
+ console.log(overviewTable.toString());
428
+ console.log();
429
+ console.log(import_picocolors2.default.bold("Token Diet & Context Optimization Preview:"));
430
+ console.log(` \u25CF Full Static Tool Declarations: ~${tokenMetrics.rawTokens.toLocaleString()} tokens`);
431
+ console.log(` \u25CF PostMCP JIT + Token Diet: ~${tokenMetrics.optimizedTokens.toLocaleString()} tokens`);
432
+ console.log(` \u25CF Context Window Savings: ${import_picocolors2.default.bold(import_picocolors2.default.green(`~${tokenMetrics.savingsPct}% saved`))}`);
433
+ console.log();
434
+ console.log(import_picocolors2.default.bold("Safety & Risk Tier Breakdown:"));
435
+ console.log(` ${import_picocolors2.default.green("\u25CF READ_ONLY")}: ${riskCounts.READ_ONLY} endpoints (Safe for autonomous exploration)`);
436
+ console.log(` ${import_picocolors2.default.yellow("\u25CF MUTATION")}: ${riskCounts.MUTATION} endpoints (Creates or updates data)`);
437
+ console.log(` ${import_picocolors2.default.red("\u25CF CRITICAL")}: ${riskCounts.CRITICAL} endpoints (Destructive actions / simulated in dry-run)`);
438
+ console.log();
439
+ console.log(import_picocolors2.default.bold(`Operations List (Showing first 10 of ${totalOps}):`));
440
+ const opTable = new import_cli_table3.default({
441
+ head: [import_picocolors2.default.bold("Tool Name (ID)"), import_picocolors2.default.bold("Method"), import_picocolors2.default.bold("Path"), import_picocolors2.default.bold("Risk Tier")],
442
+ colWidths: [22, 10, 32, 14]
443
+ });
444
+ const sampleOps = spec.operations.slice(0, 10);
445
+ for (const op of sampleOps) {
446
+ const tierColor = op.riskTier === "READ_ONLY" ? import_picocolors2.default.green(op.riskTier) : op.riskTier === "CRITICAL" ? import_picocolors2.default.red(op.riskTier) : import_picocolors2.default.yellow(op.riskTier);
447
+ opTable.push([op.id, op.method.toUpperCase(), op.path, tierColor]);
448
+ }
449
+ console.log(opTable.toString());
450
+ if (totalOps > 10) {
451
+ console.log(import_picocolors2.default.dim(` ... and ${totalOps - 10} more endpoints.`));
452
+ }
453
+ console.log();
454
+ }
455
+
456
+ // src/commands/generate.ts
457
+ var fs3 = __toESM(require("fs"));
458
+ var path3 = __toESM(require("path"));
459
+ var import_core3 = require("@postmcp/core");
460
+ var import_picocolors3 = __toESM(require("picocolors"));
461
+ async function generateCommand(specArg, options) {
462
+ let specPath = specArg;
463
+ if (!specPath) {
464
+ console.error(import_picocolors3.default.red("Error: No OpenAPI spec provided. Usage: postmcp generate <spec-path-or-url-or-@preset> --target <python|typescript>"));
465
+ process.exit(1);
466
+ return;
467
+ }
468
+ if (typeof specPath === "string" && specPath.startsWith("@")) {
469
+ try {
470
+ specPath = await resolvePresetSpec(specPath);
471
+ } catch (err) {
472
+ console.error(import_picocolors3.default.red(`Error resolving preset: ${err.message}`));
473
+ process.exit(1);
474
+ return;
475
+ }
476
+ }
477
+ let spec;
478
+ try {
479
+ spec = await (0, import_core3.parseOpenAPI)(specPath);
480
+ } catch (err) {
481
+ console.error(import_picocolors3.default.red(`Failed to parse specification: ${err.message}`));
482
+ process.exit(1);
483
+ return;
484
+ }
485
+ const rawLang = (options.lang || options.target || "ts").toLowerCase();
486
+ let targetLang;
487
+ if (rawLang === "ts" || rawLang === "typescript") {
488
+ targetLang = "ts";
489
+ } else if (rawLang === "py" || rawLang === "python") {
490
+ targetLang = "py";
491
+ } else {
492
+ console.error(import_picocolors3.default.red(`Unsupported language '${rawLang}'. Supported languages: 'ts', 'py'.`));
493
+ process.exit(1);
494
+ return;
495
+ }
496
+ const outDir = path3.resolve(options.out || `./${spec.title.toLowerCase().replace(/[^a-z0-9]/g, "-")}-mcp`);
497
+ console.log(import_picocolors3.default.cyan(`Generating standalone ${import_picocolors3.default.bold(targetLang.toUpperCase())} MCP server for '${spec.title}'...`));
498
+ const project = targetLang === "ts" ? (0, import_core3.generateTypeScriptProject)(spec) : (0, import_core3.generatePythonProject)(spec);
499
+ if (!fs3.existsSync(outDir)) {
500
+ fs3.mkdirSync(outDir, { recursive: true });
501
+ }
502
+ for (const [relativePath, content] of Object.entries(project.files)) {
503
+ const filePath = path3.join(outDir, relativePath);
504
+ const parentDir = path3.dirname(filePath);
505
+ if (!fs3.existsSync(parentDir)) {
506
+ fs3.mkdirSync(parentDir, { recursive: true });
507
+ }
508
+ fs3.writeFileSync(filePath, content, "utf-8");
509
+ console.log(` ${import_picocolors3.default.green("+")} ${relativePath}`);
510
+ }
511
+ console.log();
512
+ console.log(import_picocolors3.default.green(`Standalone MCP server successfully generated at:`));
513
+ console.log(` ${import_picocolors3.default.bold(outDir)}`);
514
+ console.log();
515
+ console.log(import_picocolors3.default.dim("Next steps:"));
516
+ if (targetLang === "ts") {
517
+ console.log(` cd ${path3.relative(process.cwd(), outDir) || "."}`);
518
+ console.log(" npm install");
519
+ console.log(" npm run build");
520
+ console.log(" npm start");
521
+ } else {
522
+ console.log(` cd ${path3.relative(process.cwd(), outDir) || "."}`);
523
+ console.log(" pip install -r requirements.txt");
524
+ console.log(" python server.py");
525
+ }
526
+ }
527
+
528
+ // src/commands/export.ts
529
+ var fs4 = __toESM(require("fs"));
530
+ var path4 = __toESM(require("path"));
531
+ var os2 = __toESM(require("os"));
532
+ var import_core4 = require("@postmcp/core");
533
+ var import_picocolors4 = __toESM(require("picocolors"));
534
+ function getClientConfigPath(client) {
535
+ const home = os2.homedir();
536
+ if (client === "cursor") {
537
+ return path4.join(process.cwd(), ".cursor", "mcp.json");
538
+ }
539
+ if (client === "claude") {
540
+ if (process.platform === "darwin") {
541
+ return path4.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
542
+ }
543
+ if (process.platform === "win32") {
544
+ return path4.join(process.env.APPDATA || path4.join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
545
+ }
546
+ return path4.join(home, ".config", "Claude", "claude_desktop_config.json");
547
+ }
548
+ if (client === "windsurf") {
549
+ return path4.join(home, ".codeium", "windsurf", "mcp_config.json");
550
+ }
551
+ return path4.join(process.cwd(), "mcp.json");
552
+ }
553
+ function buildClientConfigSnippet(serverKey, specPath, options) {
554
+ const env = {};
555
+ if (options.bearer) {
556
+ env["API_KEY"] = options.bearer;
557
+ }
558
+ if (options.baseUrl) {
559
+ env["BASE_URL"] = options.baseUrl;
560
+ }
561
+ if (options.env) {
562
+ for (const e of options.env) {
563
+ const [k, v] = e.split("=");
564
+ if (k && v) env[k] = v;
565
+ }
566
+ }
567
+ return {
568
+ mcpServers: {
569
+ [serverKey]: {
570
+ command: "npx",
571
+ args: ["-y", "postmcp", "run", specPath],
572
+ env: Object.keys(env).length > 0 ? env : void 0
573
+ }
574
+ }
575
+ };
576
+ }
577
+ async function exportCommand(specArg, options) {
578
+ let specPath = specArg;
579
+ if (!specPath) {
580
+ console.error(import_picocolors4.default.red("Error: No OpenAPI spec provided. Usage: postmcp export <spec-path-or-url-or-@preset> --target cursor|claude|windsurf|all"));
581
+ process.exit(1);
582
+ }
583
+ let serverKey = "api-server";
584
+ if (specPath.startsWith("@")) {
585
+ serverKey = specPath.replace(/^@/, "").toLowerCase();
586
+ } else {
587
+ try {
588
+ const parsed = await (0, import_core4.parseOpenAPI)(specPath);
589
+ serverKey = parsed.title.toLowerCase().replace(/[^a-z0-9]/g, "-") || "api-server";
590
+ } catch {
591
+ serverKey = "api-server";
592
+ }
593
+ }
594
+ const selectedTarget = (options.client || options.target || "all").toLowerCase();
595
+ const clientsToExport = selectedTarget === "all" ? ["cursor", "claude", "windsurf"] : [selectedTarget];
596
+ console.log(import_picocolors4.default.bold(import_picocolors4.default.cyan(`PostMCP 1-Click Client Configuration Exporter`)));
597
+ console.log();
598
+ for (const c of clientsToExport) {
599
+ const configPath = getClientConfigPath(c);
600
+ const snippet = buildClientConfigSnippet(serverKey, specPath, options);
601
+ const formattedSnippet = JSON.stringify(snippet, null, 2);
602
+ console.log(import_picocolors4.default.bold(import_picocolors4.default.green(`\u25B6 ${c.toUpperCase()} (${c === "cursor" ? "Project Local" : "Global Client"})`)));
603
+ console.log(import_picocolors4.default.dim(` Config path: ${configPath}`));
604
+ console.log();
605
+ console.log(import_picocolors4.default.gray(formattedSnippet));
606
+ console.log();
607
+ if (options.write) {
608
+ try {
609
+ let existingConfig = {};
610
+ if (fs4.existsSync(configPath)) {
611
+ const raw = fs4.readFileSync(configPath, "utf-8");
612
+ existingConfig = JSON.parse(raw);
613
+ }
614
+ existingConfig.mcpServers = existingConfig.mcpServers || {};
615
+ existingConfig.mcpServers[serverKey] = snippet.mcpServers[serverKey];
616
+ const parentDir = path4.dirname(configPath);
617
+ if (!fs4.existsSync(parentDir)) {
618
+ fs4.mkdirSync(parentDir, { recursive: true });
619
+ }
620
+ fs4.writeFileSync(configPath, JSON.stringify(existingConfig, null, 2), "utf-8");
621
+ console.log(import_picocolors4.default.green(` Successfully merged and written to ${configPath}`));
622
+ } catch (err) {
623
+ console.error(import_picocolors4.default.red(` Failed to write to ${configPath}: ${err.message}`));
624
+ }
625
+ console.log();
626
+ }
627
+ }
628
+ if (!options.write) {
629
+ console.log(import_picocolors4.default.dim(`Tip: Pass '--write' to automatically install this configuration into your client settings.`));
630
+ }
631
+ }
632
+
633
+ // src/commands/presets.ts
634
+ var import_cli_table32 = __toESM(require("cli-table3"));
635
+ var import_picocolors5 = __toESM(require("picocolors"));
636
+ async function listPresetsCommand(categoryOrQuery) {
637
+ console.log();
638
+ console.log(import_picocolors5.default.bold(import_picocolors5.default.cyan(`PostMCP Presets Catalog (${import_presets.ALL_PRESETS.length} Curated Developer APIs)`)));
639
+ console.log(import_picocolors5.default.dim(`Run any preset instantly using: postmcp run @<preset_id>`));
640
+ console.log();
641
+ let displayedPresets = import_presets.ALL_PRESETS;
642
+ if (categoryOrQuery) {
643
+ const q = categoryOrQuery.toLowerCase().trim();
644
+ displayedPresets = import_presets.ALL_PRESETS.filter((p) => {
645
+ return p.id.toLowerCase().includes(q) || p.name.toLowerCase().includes(q) || p.category.toLowerCase().includes(q) || p.tags && p.tags.some((t) => t.toLowerCase().includes(q));
646
+ });
647
+ }
648
+ const table = new import_cli_table32.default({
649
+ head: [import_picocolors5.default.bold("Preset ID"), import_picocolors5.default.bold("API Name"), import_picocolors5.default.bold("Category"), import_picocolors5.default.bold("Authentication"), import_picocolors5.default.bold("Run Command")],
650
+ colWidths: [14, 26, 22, 28, 26]
651
+ });
652
+ for (const meta of displayedPresets) {
653
+ table.push([
654
+ import_picocolors5.default.bold(import_picocolors5.default.magenta(`@${meta.id}`)),
655
+ meta.name,
656
+ meta.category,
657
+ import_picocolors5.default.dim(meta.authType),
658
+ import_picocolors5.default.green(`postmcp run @${meta.id}`)
659
+ ]);
660
+ }
661
+ console.log(table.toString());
662
+ console.log();
663
+ console.log(import_picocolors5.default.dim(`Total Presets: ${displayedPresets.length} of ${import_presets.ALL_PRESETS.length}`));
664
+ console.log(import_picocolors5.default.dim(`Run 'postmcp presets sync' to update offline cached schemas from GitHub.`));
665
+ console.log();
666
+ }
667
+ async function syncPresetsCommand() {
668
+ console.log(import_picocolors5.default.cyan(`Syncing latest OpenAPI schemas for all presets...`));
669
+ try {
670
+ const synced = await syncAllPresets();
671
+ console.log(import_picocolors5.default.green(`Successfully synced ${synced.length} presets to local cache (~/.postmcp/presets/):`));
672
+ for (const id of synced) {
673
+ console.log(` ${import_picocolors5.default.green("\u25CF")} @${id}`);
674
+ }
675
+ } catch (err) {
676
+ console.error(import_picocolors5.default.red(`Failed to sync presets: ${err.message}`));
677
+ }
678
+ }
679
+
680
+ // src/commands/studio.ts
681
+ var path5 = __toESM(require("path"));
682
+ var fs5 = __toESM(require("fs"));
683
+ var import_node_module = require("module");
684
+ var import_node_child_process = require("child_process");
685
+ var import_open = __toESM(require("open"));
686
+ var import_axios2 = __toESM(require("axios"));
687
+ var import_picocolors6 = __toESM(require("picocolors"));
688
+ function findStudioDir() {
689
+ try {
690
+ const customRequire = typeof import_node_module.createRequire !== "undefined" ? (0, import_node_module.createRequire)(__filename) : require;
691
+ const pkgPath = customRequire.resolve("@postmcp/studio/package.json");
692
+ if (fs5.existsSync(pkgPath)) {
693
+ return path5.dirname(pkgPath);
694
+ }
695
+ } catch {
696
+ }
697
+ const candidates = [
698
+ path5.resolve(__dirname, "..", "..", "studio"),
699
+ path5.resolve(__dirname, "..", "..", "..", "packages", "studio"),
700
+ path5.resolve(process.cwd(), "packages", "studio"),
701
+ path5.resolve(process.cwd(), "node_modules", "@postmcp", "studio")
702
+ ];
703
+ for (const candidate of candidates) {
704
+ if (fs5.existsSync(path5.join(candidate, "package.json"))) {
705
+ return candidate;
706
+ }
707
+ }
708
+ return path5.resolve(process.cwd(), "packages", "studio");
709
+ }
710
+ async function waitForServer(url, timeoutMs = 2e4) {
711
+ const start = Date.now();
712
+ while (Date.now() - start < timeoutMs) {
713
+ try {
714
+ const res = await import_axios2.default.get(url, { timeout: 1e3, validateStatus: () => true });
715
+ if (res.status >= 200 && res.status < 500) {
716
+ return true;
717
+ }
718
+ } catch {
719
+ }
720
+ await new Promise((r) => setTimeout(r, 400));
721
+ }
722
+ return false;
723
+ }
724
+ async function studioCommand(specArg, options = {}) {
725
+ const port = options.port || "3000";
726
+ const baseUrl = `http://localhost:${port}`;
727
+ const targetUrl = specArg ? `${baseUrl}?spec=${encodeURIComponent(specArg)}` : baseUrl;
728
+ const studioDir = findStudioDir();
729
+ console.log();
730
+ console.log(import_picocolors6.default.bold(import_picocolors6.default.cyan(`Starting PostMCP Visual Web Studio...`)));
731
+ console.log(` Port: ${import_picocolors6.default.bold(import_picocolors6.default.green(port))}`);
732
+ console.log(` Studio Dir: ${import_picocolors6.default.dim(studioDir)}`);
733
+ if (specArg) {
734
+ console.log(` Initial Spec: ${import_picocolors6.default.dim(specArg)}`);
735
+ }
736
+ console.log();
737
+ let child = null;
738
+ if (fs5.existsSync(studioDir)) {
739
+ const isBuilt = fs5.existsSync(path5.join(studioDir, ".next"));
740
+ const isPnpm = fs5.existsSync(path5.join(studioDir, "..", "..", "pnpm-lock.yaml"));
741
+ const command = isPnpm ? "pnpm" : "npx";
742
+ const args = isPnpm ? isBuilt ? ["start", "--port", port] : ["dev", "--port", port] : isBuilt ? ["next", "start", "-p", port] : ["next", "dev", "-p", port];
743
+ try {
744
+ child = (0, import_node_child_process.spawn)(command, args, {
745
+ cwd: studioDir,
746
+ stdio: "inherit",
747
+ shell: true,
748
+ env: {
749
+ ...process.env,
750
+ PORT: port,
751
+ NEXT_PUBLIC_INITIAL_SPEC: specArg || "",
752
+ STUDIO_INITIAL_SPEC: specArg || "",
753
+ POSTMCP_WORKSPACE: process.cwd(),
754
+ WORKSPACE_CWD: process.cwd()
755
+ }
756
+ });
757
+ const cleanup = () => {
758
+ if (child) {
759
+ try {
760
+ child.kill("SIGINT");
761
+ } catch {
762
+ }
763
+ }
764
+ };
765
+ process.on("SIGINT", cleanup);
766
+ process.on("SIGTERM", cleanup);
767
+ process.on("exit", cleanup);
768
+ } catch (err) {
769
+ console.log(import_picocolors6.default.yellow(` Note: Running in detached standalone mode: ${err.message}`));
770
+ }
771
+ }
772
+ const isReady = await waitForServer(baseUrl, 15e3);
773
+ if (isReady) {
774
+ console.log(import_picocolors6.default.green(`PostMCP Visual Web Studio ready at: ${import_picocolors6.default.bold(targetUrl)}`));
775
+ } else {
776
+ console.log(import_picocolors6.default.dim(` Studio server starting at: ${targetUrl}`));
777
+ }
778
+ if (!options.noOpen) {
779
+ try {
780
+ await (0, import_open.default)(targetUrl);
781
+ console.log(import_picocolors6.default.dim(`Opening Web Studio in your default browser...`));
782
+ } catch {
783
+ console.log(import_picocolors6.default.dim(`Please open ${targetUrl} in your browser.`));
784
+ }
785
+ }
786
+ if (child) {
787
+ await new Promise((resolve4) => {
788
+ child?.on("close", () => resolve4());
789
+ });
790
+ }
791
+ }
792
+
793
+ // src/generators/typescript.ts
794
+ var import_core5 = require("@postmcp/core");
795
+
796
+ // src/generators/python.ts
797
+ var import_core6 = require("@postmcp/core");
798
+ // Annotate the CommonJS export names for ESM import in node:
799
+ 0 && (module.exports = {
800
+ ALL_PRESETS,
801
+ BUNDLED_PRESETS,
802
+ PRESETS_BY_ID,
803
+ Preset,
804
+ buildClientConfigSnippet,
805
+ buildPresetAuthConfig,
806
+ estimateSpecTokenSavings,
807
+ exportCommand,
808
+ findStudioDir,
809
+ generateCommand,
810
+ generatePythonProject,
811
+ generateTypeScriptProject,
812
+ getClientConfigPath,
813
+ getPreset,
814
+ getPresetCacheDir,
815
+ inspectCommand,
816
+ listPresetsCommand,
817
+ loadConfigFile,
818
+ loadEnvFile,
819
+ parseApiKeyFlag,
820
+ parseHeaderFlags,
821
+ resolvePresetSpec,
822
+ runCommand,
823
+ studioCommand,
824
+ syncAllPresets,
825
+ syncPresetsCommand,
826
+ waitForServer
827
+ });
828
+ //# sourceMappingURL=index.js.map