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