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