@airborne-dev/mcp 0.0.0-stage → 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/SKILL.md ADDED
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: airborne
3
+ description: Deploy full-stack apps to the user's own Google Cloud project via Airborne (airborne.dev) with zero GCP Console clicks, Always-Free guardrails, and keyless Service Account impersonation. Use whenever building, configuring, deploying, debugging, or pausing a Cloud Run web app with Firestore, Cloud Storage, Secrets, or Gemini.
4
+ ---
5
+
6
+ # Airborne Golden-Path Skill (Google Cloud BYOC)
7
+
8
+ Follow these rules from **Prompt #1** whenever building or deploying an app for a user connected via Airborne (`airborne.dev`) so deploys succeed on the first try and stay inside Google Cloud's Always-Free tier.
9
+
10
+ ## 1. Golden-Path App Architecture Rules
11
+
12
+ 1. **Always bind to `PORT` on `0.0.0.0`:**
13
+ - **Node / Next.js / Express / Fastify / Hono:** Listen on `Number(process.env.PORT || 8080)` and host `"0.0.0.0"`.
14
+ - **Next.js:** Ensure `"start": "next start -H 0.0.0.0 -p ${PORT:-8080}"` (or `output: "standalone"` with a Dockerfile) in `package.json`.
15
+ - **Python (FastAPI / Flask):** Include a `Procfile` containing `web: uvicorn main:app --host 0.0.0.0 --port $PORT` (or `gunicorn`) and a `requirements.txt`.
16
+ - Never hardcode `localhost` or port `3000` for production server binding.
17
+
18
+ 2. **Never use local SQLite or local disk paths for persistent data:**
19
+ - Cloud Run containers are ephemeral and scale to zero. Local files vanish on restart or scale-down.
20
+ - **Structured data:** Use Google Cloud Firestore via `@google-cloud/firestore` (or `google-cloud-firestore` in Python). Always use the `(default)` database (`process.env.FIRESTORE_DATABASE_ID || "(default)"`) and namespace every collection under `process.env.FIRESTORE_COLLECTION_PREFIX` (e.g., `apps/<app_name>/items`) so all user apps stay inside the Always-Free `(default)` Firestore tier.
21
+ - **File uploads (PDFs, images, videos):** Store objects in Cloud Storage using `process.env.UPLOAD_BUCKET`. For uploads larger than 10MB (Cloud Run's direct HTTP body cap is 32MB), generate a signed GCS PUT URL from your backend so the browser uploads straight to GCS.
22
+
23
+ 3. **Secrets & Environment Variables:**
24
+ - Never hardcode API keys or credentials in source code.
25
+ - Read secrets strictly from `process.env.*`.
26
+ - In production, Airborne packs all synced `.env` keys into **one** Secret Manager JSON secret (`AIRBORNE_SECRETS_JSON`) so users stay inside Google Secret Manager's 6 Always-Free active secret versions. Load it at startup with a 5-line helper before reading `process.env`:
27
+ ```ts
28
+ if (process.env.AIRBORNE_SECRETS_JSON) {
29
+ const parsed = JSON.parse(process.env.AIRBORNE_SECRETS_JSON);
30
+ for (const [k, v] of Object.entries(parsed)) {
31
+ if (process.env[k] === undefined) process.env[k] = String(v);
32
+ }
33
+ }
34
+ ```
35
+ - Never commit `.env` or `.env.local`; `deploy_app` automatically excludes them from the uploaded build archive.
36
+
37
+ 4. **Gemini / Vertex AI:**
38
+ - Prefer Application Default Credentials (ADC) with `@google/genai` (Vertex mode using `process.env.GCP_PROJECT_ID` and `process.env.VERTEX_LOCATION || "us-central1"`). The deployed Cloud Run `app-runtime` service account already has `roles/aiplatform.user`, requiring zero static API keys in production.
39
+
40
+ 5. **Run `init_app` before writing backend integrations:**
41
+ - Call `init_app` early with the add-ons the app needs (`firestore`, `storage`, `gemini`). It provisions resources inside the user's own GCP project and writes `.env.local` locally so local dev works immediately.
42
+
43
+ ## 2. Standard 6-Tool Workflow
44
+
45
+ 1. **`get_status(project?)`** — Always call first in a new session to verify the user is authenticated and has a connected Google Cloud project (`airborne-apps-*`). If not connected, direct them to their Airborne dashboard (`https://airborne.dev`) to complete the 2-minute Cloud Shell setup.
46
+ 2. **`init_app(app_name, addons, dir, project?)`** — Provisions requested add-ons (`"firestore"`, `"storage"`, `"gemini"`) in the user's project and writes `.env.local`. Always pass the absolute app directory `dir` (the tool refuses `$HOME` or `/`).
47
+ 3. **`sync_secrets(app_name, env_file, dir?, project?)`** — Packs keys from a local `.env` file into a single Secret Manager JSON secret (`airborne-<app_name>-env`) and cleans up old versions. Pass an absolute `env_file` path (or pass `dir` alongside a relative `env_file`; files directly in `$HOME` or `/` are refused).
48
+ 4. **`deploy_app(app_name, dir, max_instances?, region?, project?)`** — Archives `dir` (respecting `.gitignore`, excluding `node_modules`, `.venv`, `.env*`), uploads directly to the user's own GCS build bucket via a signed URL, builds with Google Cloud Buildpacks (or `Dockerfile` if present), and deploys to Cloud Run (scale-to-zero, Hobby defaults to `max_instances=3`, `512Mi`, `us-central1`; Pro+ unlocks higher scaling and custom regions). Returns the live `https://*.run.app` URL.
49
+ 5. **`diagnose_app(app_name, lines?, project?)`** — If a deploy fails or the live app errors, call this immediately. It fetches Cloud Run error logs and translates cryptic GCP errors (port mismatch, OOM, missing secret, Buildpacks entrypoint, payload limit) into plain-English fixes so you can patch the code and re-run `deploy_app`.
50
+ 6. **`toggle_app(app_name, action, project?)`** — Instantly `"pause"` or `"resume"` public traffic by removing/restoring `allUsers` on `roles/run.invoker` without deleting any data.
package/dist/api.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type StoredCredentials } from "./auth.js";
2
+ export declare class ControlPlaneError extends Error {
3
+ status: number;
4
+ code?: string;
5
+ requiredPlan?: string;
6
+ limitName?: string;
7
+ upgradeUrl?: string;
8
+ license?: unknown;
9
+ constructor(message: string, status: number, opts?: {
10
+ code?: string;
11
+ requiredPlan?: string;
12
+ limitName?: string;
13
+ upgradeUrl?: string;
14
+ license?: unknown;
15
+ });
16
+ }
17
+ export declare function ensureInteractiveLogin(apiBase?: string): Promise<StoredCredentials>;
18
+ /**
19
+ * Uses node:http / node:https directly for long-running requests (e.g. >4 min builds)
20
+ * because Node's built-in undici `fetch()` enforces a hardcoded 300s `headersTimeout`
21
+ * that aborts Cloud Build deploys prematurely.
22
+ */
23
+ export declare function nodeHttpRequest(rawUrl: string, method: string, headers: Record<string, string>, bodyText: string | undefined, timeoutMs: number, redirectsRemaining?: number, deadlineAt?: number): Promise<{
24
+ status: number;
25
+ statusText: string;
26
+ text: string;
27
+ }>;
28
+ /**
29
+ * Calls the Airborne Control Plane API, automatically initiating deduplicated
30
+ * browser OAuth login and retrying once on HTTP 401 when `AIRBORNE_API_TOKEN` is unset.
31
+ */
32
+ export declare function controlPlaneRequest<T>(endpoint: string, options?: {
33
+ method?: "GET" | "POST" | "PATCH" | "DELETE";
34
+ body?: unknown;
35
+ project?: string;
36
+ timeoutMs?: number;
37
+ }): Promise<T>;
package/dist/api.js ADDED
@@ -0,0 +1,265 @@
1
+ import http from "node:http";
2
+ import https from "node:https";
3
+ import { getAccessToken, getApiBase, runLocalhostOAuthLogin, } from "./auth.js";
4
+ export class ControlPlaneError extends Error {
5
+ status;
6
+ code;
7
+ requiredPlan;
8
+ limitName;
9
+ upgradeUrl;
10
+ license;
11
+ constructor(message, status, opts) {
12
+ super(message);
13
+ this.name = "ControlPlaneError";
14
+ this.status = status;
15
+ this.code = opts?.code;
16
+ this.requiredPlan = opts?.requiredPlan;
17
+ this.limitName = opts?.limitName;
18
+ this.upgradeUrl = opts?.upgradeUrl;
19
+ this.license = opts?.license;
20
+ }
21
+ }
22
+ // Deduplicate concurrent 401 browser OAuth flows across parallel MCP tool calls
23
+ let inFlightLogin = null;
24
+ export async function ensureInteractiveLogin(apiBase = getApiBase()) {
25
+ if (!inFlightLogin) {
26
+ inFlightLogin = runLocalhostOAuthLogin(apiBase).finally(() => {
27
+ inFlightLogin = null;
28
+ });
29
+ }
30
+ return inFlightLogin;
31
+ }
32
+ /**
33
+ * Uses node:http / node:https directly for long-running requests (e.g. >4 min builds)
34
+ * because Node's built-in undici `fetch()` enforces a hardcoded 300s `headersTimeout`
35
+ * that aborts Cloud Build deploys prematurely.
36
+ */
37
+ export function nodeHttpRequest(rawUrl, method, headers, bodyText, timeoutMs, redirectsRemaining = 3, deadlineAt = Date.now() + timeoutMs) {
38
+ return new Promise((resolve, reject) => {
39
+ const remainingMs = deadlineAt - Date.now();
40
+ if (remainingMs <= 0) {
41
+ const err = new Error(`Request timed out after ${timeoutMs}ms`);
42
+ err.name = "TimeoutError";
43
+ reject(err);
44
+ return;
45
+ }
46
+ const parsed = new URL(rawUrl);
47
+ const transport = parsed.protocol === "https:" ? https : http;
48
+ // Node's http.request rejects bracketed IPv6 literals like "[::1]" in `hostname`
49
+ const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
50
+ const reqHeaders = { ...headers };
51
+ let bodyBuf;
52
+ if (bodyText !== undefined) {
53
+ bodyBuf = Buffer.from(bodyText, "utf8");
54
+ reqHeaders["Content-Length"] = String(bodyBuf.byteLength);
55
+ }
56
+ let settled = false;
57
+ const fail = (err) => {
58
+ if (settled)
59
+ return;
60
+ settled = true;
61
+ clearTimeout(deadline);
62
+ reject(err);
63
+ };
64
+ const req = transport.request({
65
+ protocol: parsed.protocol,
66
+ hostname,
67
+ port: parsed.port || undefined,
68
+ path: `${parsed.pathname}${parsed.search}`,
69
+ method,
70
+ headers: reqHeaders,
71
+ }, (res) => {
72
+ const status = res.statusCode ?? 0;
73
+ const location = res.headers.location;
74
+ if ((status === 301 ||
75
+ status === 302 ||
76
+ status === 303 ||
77
+ status === 307 ||
78
+ status === 308) &&
79
+ location &&
80
+ redirectsRemaining > 0) {
81
+ let nextUrl = null;
82
+ try {
83
+ nextUrl = new URL(location, parsed);
84
+ }
85
+ catch {
86
+ nextUrl = null;
87
+ }
88
+ // Only follow redirects on the exact same origin (never leak Authorization/bodies cross-origin)
89
+ if (nextUrl && nextUrl.origin === parsed.origin) {
90
+ res.on("error", () => { });
91
+ res.resume();
92
+ settled = true;
93
+ clearTimeout(deadline);
94
+ const preserveBody = status === 307 || status === 308;
95
+ const nextMethod = preserveBody ? method : "GET";
96
+ const nextBody = preserveBody ? bodyText : undefined;
97
+ const nextHeaders = {};
98
+ for (const [k, v] of Object.entries(headers)) {
99
+ const lower = k.toLowerCase();
100
+ if (!preserveBody &&
101
+ (lower === "content-type" ||
102
+ lower === "content-length" ||
103
+ lower === "transfer-encoding")) {
104
+ continue;
105
+ }
106
+ nextHeaders[k] = v;
107
+ }
108
+ nodeHttpRequest(nextUrl.toString(), nextMethod, nextHeaders, nextBody, timeoutMs, redirectsRemaining - 1, deadlineAt).then(resolve, reject);
109
+ return;
110
+ }
111
+ }
112
+ const chunks = [];
113
+ let total = 0;
114
+ const MAX_RESP_BYTES = 16 * 1024 * 1024;
115
+ res.on("data", (chunk) => {
116
+ total += chunk.length;
117
+ if (total > MAX_RESP_BYTES) {
118
+ const err = new Error(`Control Plane response exceeded ${MAX_RESP_BYTES} bytes.`);
119
+ req.destroy(err);
120
+ fail(err);
121
+ return;
122
+ }
123
+ chunks.push(chunk);
124
+ });
125
+ res.on("end", () => {
126
+ if (settled)
127
+ return;
128
+ settled = true;
129
+ clearTimeout(deadline);
130
+ resolve({
131
+ status,
132
+ statusText: res.statusMessage ?? "",
133
+ text: Buffer.concat(chunks).toString("utf8"),
134
+ });
135
+ });
136
+ res.on("close", () => {
137
+ if (!settled && !res.complete) {
138
+ fail(new Error("Connection closed prematurely while reading response."));
139
+ }
140
+ });
141
+ res.on("error", (err) => fail(err));
142
+ });
143
+ const deadline = setTimeout(() => {
144
+ const err = new Error(`Request timed out after ${timeoutMs}ms`);
145
+ err.name = "TimeoutError";
146
+ req.destroy(err);
147
+ fail(err);
148
+ }, remainingMs);
149
+ req.on("error", (err) => fail(err));
150
+ if (bodyBuf)
151
+ req.write(bodyBuf);
152
+ req.end();
153
+ });
154
+ }
155
+ function isTimeoutError(err) {
156
+ if (!(err instanceof Error))
157
+ return false;
158
+ if (err.name === "TimeoutError" || err.name === "AbortError")
159
+ return true;
160
+ const cause = err.cause;
161
+ return (cause?.code === "UND_ERR_HEADERS_TIMEOUT" ||
162
+ cause?.code === "UND_ERR_BODY_TIMEOUT" ||
163
+ cause?.code === "UND_ERR_CONNECT_TIMEOUT");
164
+ }
165
+ async function rawControlPlaneRequest(endpoint, options) {
166
+ const apiBase = getApiBase();
167
+ const token = getAccessToken();
168
+ const url = `${apiBase}${endpoint.startsWith("/") ? endpoint : `/${endpoint}`}`;
169
+ const timeoutMs = options.timeoutMs ?? 30_000;
170
+ const headers = {
171
+ Accept: "application/json",
172
+ };
173
+ if (options.body !== undefined) {
174
+ headers["Content-Type"] = "application/json";
175
+ }
176
+ if (token) {
177
+ headers["Authorization"] = `Bearer ${token}`;
178
+ }
179
+ if (options.project?.trim()) {
180
+ headers["x-airborne-project"] = options.project.trim();
181
+ }
182
+ let status = 0;
183
+ let statusText = "";
184
+ let text = "";
185
+ try {
186
+ const bodyText = options.body !== undefined ? JSON.stringify(options.body) : undefined;
187
+ // Always use nodeHttpRequest so EVERY request (including sync_secrets POSTs)
188
+ // enforces exact same-origin redirects, a 16 MiB response cap, and full deadline budgets.
189
+ const res = await nodeHttpRequest(url, options.method ?? "GET", headers, bodyText, timeoutMs);
190
+ status = res.status;
191
+ statusText = res.statusText;
192
+ text = res.text;
193
+ }
194
+ catch (err) {
195
+ const detail = err instanceof Error ? err.message : String(err);
196
+ if (isTimeoutError(err)) {
197
+ throw new ControlPlaneError(`Request to Airborne Control Plane (${endpoint}) timed out after ${Math.round(timeoutMs / 1000)}s. The operation may still be running in Google Cloud — check get_status or diagnose_app.`, 408, { code: "TIMEOUT" });
198
+ }
199
+ throw new ControlPlaneError(`Could not reach Airborne Control Plane at ${apiBase} (${detail}). Make sure the web server is running or set AIRBORNE_API_BASE.`, 0, { code: "UNREACHABLE" });
200
+ }
201
+ let parsed = null;
202
+ try {
203
+ parsed = text ? JSON.parse(text) : null;
204
+ }
205
+ catch {
206
+ parsed = null;
207
+ }
208
+ if (status < 200 || status >= 300) {
209
+ const isHtml = text.trimStart().startsWith("<");
210
+ const fallbackText = isHtml
211
+ ? `HTTP ${status} ${statusText || "Server Error"} (unexpected HTML response from ${apiBase})`
212
+ : text.slice(0, 300) || `HTTP ${status} ${statusText}`;
213
+ const code = parsed && typeof parsed.code === "string"
214
+ ? parsed.code
215
+ : status === 403 && parsed?.accessRevoked === true
216
+ ? "ACCESS_REVOKED"
217
+ : undefined;
218
+ const msg = (parsed && typeof parsed.error === "string" && parsed.error) ||
219
+ (code === "ACCESS_REVOKED"
220
+ ? "Your account is not permitted to access this Airborne Control Plane. Contact your administrator."
221
+ : fallbackText);
222
+ const requiredPlan = parsed && typeof parsed.requiredPlan === "string"
223
+ ? parsed.requiredPlan
224
+ : undefined;
225
+ const limitName = parsed && typeof parsed.limitName === "string"
226
+ ? parsed.limitName
227
+ : undefined;
228
+ const upgradeUrl = parsed && typeof parsed.upgradeUrl === "string"
229
+ ? parsed.upgradeUrl
230
+ : undefined;
231
+ const license = parsed?.license;
232
+ const enrichedMsg = code === "PLAN_LIMIT_REACHED" && upgradeUrl
233
+ ? `${msg} Upgrade here: ${upgradeUrl}`
234
+ : msg;
235
+ throw new ControlPlaneError(enrichedMsg, status, {
236
+ code,
237
+ requiredPlan,
238
+ limitName,
239
+ upgradeUrl,
240
+ license,
241
+ });
242
+ }
243
+ if (text.trim() && parsed === null) {
244
+ throw new ControlPlaneError(`Unexpected non-JSON response from ${apiBase}${endpoint}. Check AIRBORNE_API_BASE or proxy/SSO settings.`, status, { code: "INVALID_RESPONSE" });
245
+ }
246
+ return (parsed ?? {});
247
+ }
248
+ /**
249
+ * Calls the Airborne Control Plane API, automatically initiating deduplicated
250
+ * browser OAuth login and retrying once on HTTP 401 when `AIRBORNE_API_TOKEN` is unset.
251
+ */
252
+ export async function controlPlaneRequest(endpoint, options = {}) {
253
+ try {
254
+ return await rawControlPlaneRequest(endpoint, options);
255
+ }
256
+ catch (err) {
257
+ if (err instanceof ControlPlaneError &&
258
+ err.status === 401 &&
259
+ !process.env.AIRBORNE_API_TOKEN?.trim()) {
260
+ await ensureInteractiveLogin(getApiBase());
261
+ return rawControlPlaneRequest(endpoint, options);
262
+ }
263
+ throw err;
264
+ }
265
+ }
@@ -0,0 +1,59 @@
1
+ export declare function isAlwaysIgnored(relativePath: string, isDir: boolean): boolean;
2
+ type SegmentToken = {
3
+ type: "star";
4
+ } | {
5
+ type: "qmark";
6
+ } | {
7
+ type: "literal";
8
+ ch: string;
9
+ } | {
10
+ type: "class";
11
+ negated: boolean;
12
+ chars: Set<string>;
13
+ ranges: Array<[number, number]>;
14
+ };
15
+ type PathPatternSegment = SegmentToken[] | "**" | "**+";
16
+ export interface GitignoreRule {
17
+ negated: boolean;
18
+ dirOnly: boolean;
19
+ anchored: boolean;
20
+ basePrefix: string;
21
+ segments: PathPatternSegment[];
22
+ }
23
+ export declare function compileGitignoreRule(rawLine: string, basePrefix?: string): GitignoreRule | null;
24
+ export declare function isIgnoredByRules(relPath: string, isDir: boolean, rules: GitignoreRule[]): boolean;
25
+ export interface PackagedArchive {
26
+ tarballPath: string;
27
+ fileCount: number;
28
+ sizeBytes: number;
29
+ hasDockerfile: boolean;
30
+ dockerfileName?: string;
31
+ cleanup: () => void;
32
+ }
33
+ /**
34
+ * Packages a local project directory into a `.tar.gz` archive suitable for
35
+ * direct signed-URL upload to the user's own GCS build bucket.
36
+ *
37
+ * Uses `new tar.Pack({ noDirRecurse: true, follow: false, ... })` + `pack.add(file)` directly
38
+ * so `@`-prefixed paths (like Next.js `@modal/page.tsx`) are NEVER treated as external archives
39
+ * and TOCTOU symlink swaps are rejected.
40
+ */
41
+ export declare function packageAppDirectory(dir: string): Promise<PackagedArchive>;
42
+ /**
43
+ * Parses a local `.env` file into a null-prototype key-value map.
44
+ * Supports:
45
+ * - UTF-8 BOM stripping
46
+ * - Line-numbered error on unterminated quotes
47
+ * - Single-pass escape handling (`\n`, `\r`, `\t`, `\"`, `\\`, `\$`)
48
+ * - Quoted values with trailing inline comments (`KEY="abc" # note`)
49
+ * - Multiline double/single-quoted values (e.g. PEM keys)
50
+ */
51
+ export declare function parseEnvFile(envFilePath: string): Record<string, string>;
52
+ export declare function formatEnvValue(val: string): string;
53
+ /**
54
+ * Atomically merges Airborne-provisioned add-on environment variables into
55
+ * `<dir>/.env.local` with `0o600` permissions set BEFORE rename, rejecting symlinks,
56
+ * validating keys, and handling multiline values cleanly.
57
+ */
58
+ export declare function upsertEnvLocal(dir: string, vars: Record<string, string>): string;
59
+ export {};