@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 +50 -0
- package/dist/api.d.ts +37 -0
- package/dist/api.js +265 -0
- package/dist/archive.d.ts +59 -0
- package/dist/archive.js +862 -0
- package/dist/auth.d.ts +17 -0
- package/dist/auth.js +400 -0
- package/dist/helpers.d.ts +75 -0
- package/dist/helpers.js +31 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +737 -0
- package/package.json +34 -4
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import https from "node:https";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { pipeline } from "node:stream/promises";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
9
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { ControlPlaneError, controlPlaneRequest, ensureInteractiveLogin, } from "./api.js";
|
|
12
|
+
import { packageAppDirectory, parseEnvFile, upsertEnvLocal, } from "./archive.js";
|
|
13
|
+
import { getApiBase } from "./auth.js";
|
|
14
|
+
import { ALWAYS_FREE_DEFAULTS, isValidGcpRegion, RESERVED_CLOUD_RUN_ENV_KEYS, sanitizeAppName, } from "./helpers.js";
|
|
15
|
+
function loadSkillInstructions() {
|
|
16
|
+
try {
|
|
17
|
+
const skillPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../SKILL.md");
|
|
18
|
+
if (fs.existsSync(skillPath)) {
|
|
19
|
+
return fs.readFileSync(skillPath, "utf8");
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// non-fatal
|
|
24
|
+
}
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
const server = new McpServer({
|
|
28
|
+
name: "airborne",
|
|
29
|
+
version: "0.1.0",
|
|
30
|
+
}, {
|
|
31
|
+
instructions: loadSkillInstructions(),
|
|
32
|
+
});
|
|
33
|
+
const PROJECT_SELECTOR_RE = /^[a-zA-Z0-9._:-]{2,128}$/;
|
|
34
|
+
function resolveProjectArg(project, project_id) {
|
|
35
|
+
const chosen = project?.trim() || project_id?.trim() || "";
|
|
36
|
+
if (!chosen)
|
|
37
|
+
return undefined;
|
|
38
|
+
if (!PROJECT_SELECTOR_RE.test(chosen)) {
|
|
39
|
+
throw new Error(`Invalid project identifier "${chosen}". Pass a valid GCP project ID or connection ID.`);
|
|
40
|
+
}
|
|
41
|
+
return chosen;
|
|
42
|
+
}
|
|
43
|
+
function isTransientGcsStatus(status) {
|
|
44
|
+
return (status === 429 ||
|
|
45
|
+
status === 500 ||
|
|
46
|
+
status === 502 ||
|
|
47
|
+
status === 503 ||
|
|
48
|
+
status === 504);
|
|
49
|
+
}
|
|
50
|
+
function isTransientSocketError(err) {
|
|
51
|
+
const code = err?.code;
|
|
52
|
+
return (code === "ECONNRESET" ||
|
|
53
|
+
code === "ETIMEDOUT" ||
|
|
54
|
+
code === "EPIPE" ||
|
|
55
|
+
code === "ECONNREFUSED");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Streams a local tarball straight to a Google Cloud Storage V4 Signed PUT URL
|
|
59
|
+
* via node:https + stream pipeline, preserving GCS HTTP error bodies on early rejection,
|
|
60
|
+
* detecting premature response closes, and retrying transient 429/5xx/socket failures.
|
|
61
|
+
*/
|
|
62
|
+
async function uploadTarballToSignedGcsUrl(signedUrl, tarballPath, sizeBytes, timeoutMs = 180_000, requiredHeaders) {
|
|
63
|
+
const parsed = new URL(signedUrl);
|
|
64
|
+
if (parsed.origin !== "https://storage.googleapis.com") {
|
|
65
|
+
throw new Error(`Refusing to upload source archive to untrusted origin "${parsed.origin}".`);
|
|
66
|
+
}
|
|
67
|
+
let lastErr = null;
|
|
68
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
69
|
+
if (attempt > 0) {
|
|
70
|
+
await new Promise((r) => setTimeout(r, 1000 * attempt));
|
|
71
|
+
}
|
|
72
|
+
const readStream = fs.createReadStream(tarballPath);
|
|
73
|
+
try {
|
|
74
|
+
await new Promise((resolve, reject) => {
|
|
75
|
+
let settled = false;
|
|
76
|
+
let responseStarted = false;
|
|
77
|
+
const fail = (err) => {
|
|
78
|
+
if (settled)
|
|
79
|
+
return;
|
|
80
|
+
settled = true;
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
readStream.destroy();
|
|
83
|
+
reject(err);
|
|
84
|
+
};
|
|
85
|
+
const req = https.request({
|
|
86
|
+
protocol: parsed.protocol,
|
|
87
|
+
hostname: parsed.hostname,
|
|
88
|
+
port: parsed.port || 443,
|
|
89
|
+
path: `${parsed.pathname}${parsed.search}`,
|
|
90
|
+
method: "PUT",
|
|
91
|
+
headers: {
|
|
92
|
+
"Content-Type": "application/gzip",
|
|
93
|
+
...(requiredHeaders ?? {}),
|
|
94
|
+
"Content-Length": String(sizeBytes),
|
|
95
|
+
},
|
|
96
|
+
}, (res) => {
|
|
97
|
+
responseStarted = true;
|
|
98
|
+
const chunks = [];
|
|
99
|
+
res.on("data", (chunk) => {
|
|
100
|
+
if (chunks.length < 16)
|
|
101
|
+
chunks.push(chunk);
|
|
102
|
+
});
|
|
103
|
+
res.on("end", () => {
|
|
104
|
+
if (settled)
|
|
105
|
+
return;
|
|
106
|
+
settled = true;
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
const code = res.statusCode ?? 0;
|
|
109
|
+
if (code >= 200 && code < 300) {
|
|
110
|
+
resolve();
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
const errBody = Buffer.concat(chunks)
|
|
114
|
+
.toString("utf8")
|
|
115
|
+
.slice(0, 500);
|
|
116
|
+
const err = new Error(`Direct GCS source upload failed (${code}): ${errBody}`);
|
|
117
|
+
err.status = code;
|
|
118
|
+
reject(err);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
res.on("close", () => {
|
|
122
|
+
if (!settled && !res.complete) {
|
|
123
|
+
const err = new Error("Direct GCS source upload connection closed prematurely.");
|
|
124
|
+
err.code = "ECONNRESET";
|
|
125
|
+
fail(err);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
res.on("error", (err) => fail(err));
|
|
129
|
+
});
|
|
130
|
+
const timer = setTimeout(() => {
|
|
131
|
+
const err = new Error(`Direct GCS source upload timed out after ${Math.round(timeoutMs / 1000)}s.`);
|
|
132
|
+
req.destroy(err);
|
|
133
|
+
fail(err);
|
|
134
|
+
}, timeoutMs);
|
|
135
|
+
req.on("error", (err) => {
|
|
136
|
+
// If GCS already started sending an HTTP error response (e.g., 403/413) and closed
|
|
137
|
+
// the request side early, wait for `res.on("end")` to surface the real GCS error body.
|
|
138
|
+
if (responseStarted)
|
|
139
|
+
return;
|
|
140
|
+
fail(err);
|
|
141
|
+
});
|
|
142
|
+
pipeline(readStream, req).catch((err) => {
|
|
143
|
+
if (responseStarted)
|
|
144
|
+
return;
|
|
145
|
+
fail(err instanceof Error ? err : new Error(String(err)));
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
152
|
+
lastErr = e;
|
|
153
|
+
const status = e.status;
|
|
154
|
+
if (attempt < 2 && (isTransientGcsStatus(status) || isTransientSocketError(e))) {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
throw e;
|
|
158
|
+
}
|
|
159
|
+
finally {
|
|
160
|
+
readStream.destroy();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (lastErr)
|
|
164
|
+
throw lastErr;
|
|
165
|
+
}
|
|
166
|
+
function formatJsonResult(data) {
|
|
167
|
+
return {
|
|
168
|
+
content: [
|
|
169
|
+
{
|
|
170
|
+
type: "text",
|
|
171
|
+
text: JSON.stringify(data, null, 2),
|
|
172
|
+
},
|
|
173
|
+
],
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function formatErrorResult(err) {
|
|
177
|
+
if (err instanceof ControlPlaneError && err.code) {
|
|
178
|
+
return {
|
|
179
|
+
isError: true,
|
|
180
|
+
content: [
|
|
181
|
+
{
|
|
182
|
+
type: "text",
|
|
183
|
+
text: JSON.stringify({
|
|
184
|
+
error: err.message,
|
|
185
|
+
code: err.code,
|
|
186
|
+
status: err.status,
|
|
187
|
+
...(err.requiredPlan ? { requiredPlan: err.requiredPlan } : {}),
|
|
188
|
+
...(err.limitName ? { limitName: err.limitName } : {}),
|
|
189
|
+
...(err.upgradeUrl ? { upgradeUrl: err.upgradeUrl } : {}),
|
|
190
|
+
...(err.license ? { license: err.license } : {}),
|
|
191
|
+
}, null, 2),
|
|
192
|
+
},
|
|
193
|
+
],
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
const message = err instanceof ControlPlaneError
|
|
197
|
+
? err.message
|
|
198
|
+
: err instanceof Error
|
|
199
|
+
? err.message
|
|
200
|
+
: String(err);
|
|
201
|
+
return {
|
|
202
|
+
isError: true,
|
|
203
|
+
content: [
|
|
204
|
+
{
|
|
205
|
+
type: "text",
|
|
206
|
+
text: message,
|
|
207
|
+
},
|
|
208
|
+
],
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Tool 1: get_status
|
|
213
|
+
* Checks login (automatically initiating browser OAuth when unauthenticated),
|
|
214
|
+
* connected GCP projects, active apps, plan limits, and monthly spend cap.
|
|
215
|
+
*/
|
|
216
|
+
server.tool("get_status", "Check Airborne authentication, connected Google Cloud projects, active deployed apps, plan limits, and monthly spend cap.", {
|
|
217
|
+
project: z
|
|
218
|
+
.string()
|
|
219
|
+
.optional()
|
|
220
|
+
.describe("Optional GCP project ID or connection ID to inspect when you have multiple connected projects"),
|
|
221
|
+
project_id: z
|
|
222
|
+
.string()
|
|
223
|
+
.optional()
|
|
224
|
+
.describe("Deprecated alias for `project`"),
|
|
225
|
+
}, { readOnlyHint: true }, async ({ project, project_id }) => {
|
|
226
|
+
try {
|
|
227
|
+
const effectiveProject = resolveProjectArg(project, project_id);
|
|
228
|
+
let status = await controlPlaneRequest("/api/status", {
|
|
229
|
+
project: effectiveProject,
|
|
230
|
+
});
|
|
231
|
+
// /api/status returns HTTP 200 { authenticated: false, authRequired: true } when unsigned-in;
|
|
232
|
+
// trigger interactive browser login here so get_status works as the first tool in a fresh session
|
|
233
|
+
// (skip when account access was explicitly revoked to avoid an infinite login loop).
|
|
234
|
+
if (!status.authenticated &&
|
|
235
|
+
status.authRequired &&
|
|
236
|
+
!status.accessRevoked &&
|
|
237
|
+
!process.env.AIRBORNE_API_TOKEN?.trim()) {
|
|
238
|
+
await ensureInteractiveLogin(getApiBase());
|
|
239
|
+
status = await controlPlaneRequest("/api/status", {
|
|
240
|
+
project: effectiveProject,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
const nextStep = status.accessRevoked
|
|
244
|
+
? "Your account is not permitted to access this Airborne Control Plane. Contact your administrator."
|
|
245
|
+
: !status.authenticated && status.authRequired
|
|
246
|
+
? `Sign in to Airborne at ${getApiBase()} (or set AIRBORNE_API_TOKEN).`
|
|
247
|
+
: status.requestedProjectNotFound
|
|
248
|
+
? `Requested project "${effectiveProject}" was not found. Pick one of connectedProjects or connect it at ${getApiBase()}.`
|
|
249
|
+
: status.connection
|
|
250
|
+
? "Ready to run init_app or deploy_app."
|
|
251
|
+
: `Connect your Google Cloud project in 2 minutes at ${getApiBase()}`;
|
|
252
|
+
const summary = {
|
|
253
|
+
authenticated: status.authenticated,
|
|
254
|
+
...(status.accessRevoked ? { accessRevoked: true } : {}),
|
|
255
|
+
demoMode: Boolean(status.demoMode),
|
|
256
|
+
license: status.license ?? null,
|
|
257
|
+
user: status.user,
|
|
258
|
+
planLimits: status.planLimits ?? null,
|
|
259
|
+
dashboardUrl: getApiBase(),
|
|
260
|
+
gcpConnected: Boolean(status.connection),
|
|
261
|
+
...(status.requestedProjectNotFound
|
|
262
|
+
? { requestedProjectNotFound: true }
|
|
263
|
+
: {}),
|
|
264
|
+
connectedProjects: (status.connections ?? []).map((c) => ({
|
|
265
|
+
id: c.id,
|
|
266
|
+
projectId: c.gcpProjectId,
|
|
267
|
+
provider: c.provider ?? "gcp",
|
|
268
|
+
region: c.region,
|
|
269
|
+
spendCapUsd: c.spendCapUsd,
|
|
270
|
+
billingCurrency: c.billingCurrency ?? "USD",
|
|
271
|
+
status: c.status,
|
|
272
|
+
})),
|
|
273
|
+
connection: status.connection
|
|
274
|
+
? {
|
|
275
|
+
id: status.connection.id,
|
|
276
|
+
projectId: status.connection.gcpProjectId,
|
|
277
|
+
region: status.connection.region,
|
|
278
|
+
spendCapUsd: status.connection.spendCapUsd,
|
|
279
|
+
billingCurrency: status.connection.billingCurrency ?? "USD",
|
|
280
|
+
status: status.connection.status,
|
|
281
|
+
deployerSa: status.connection.deployerSa,
|
|
282
|
+
runtimeSa: status.connection.runtimeSa,
|
|
283
|
+
}
|
|
284
|
+
: null,
|
|
285
|
+
apps: (status.apps ?? []).map((app) => ({
|
|
286
|
+
name: app.name,
|
|
287
|
+
liveUrl: app.liveUrl,
|
|
288
|
+
publicUrl: app.publicUrl,
|
|
289
|
+
customDomain: app.customDomain,
|
|
290
|
+
region: app.region,
|
|
291
|
+
status: app.isPaused ? "paused" : app.lastDeployStatus,
|
|
292
|
+
maxInstances: app.maxInstances,
|
|
293
|
+
addons: app.addons,
|
|
294
|
+
github: app.github ?? null,
|
|
295
|
+
lastDeployedAt: app.lastDeployedAt,
|
|
296
|
+
})),
|
|
297
|
+
nextStep,
|
|
298
|
+
};
|
|
299
|
+
return formatJsonResult(summary);
|
|
300
|
+
}
|
|
301
|
+
catch (err) {
|
|
302
|
+
return formatErrorResult(err);
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
/**
|
|
306
|
+
* Tool 2: init_app
|
|
307
|
+
* Provisions requested add-ons in the user's project and writes `.env.local` locally.
|
|
308
|
+
*/
|
|
309
|
+
server.tool("init_app", "Provision Always-Free Google Cloud add-ons (firestore, storage, gemini) inside the user's own GCP project and write .env.local for instant local development.", {
|
|
310
|
+
app_name: z
|
|
311
|
+
.string()
|
|
312
|
+
.min(1)
|
|
313
|
+
.describe("App name (lowercase letters, numbers, hyphens, e.g. my-saas-app)"),
|
|
314
|
+
addons: z
|
|
315
|
+
.array(z.enum(["firestore", "storage", "gemini"]))
|
|
316
|
+
.default([])
|
|
317
|
+
.describe("Add-ons to provision: firestore, storage, gemini"),
|
|
318
|
+
dir: z
|
|
319
|
+
.string()
|
|
320
|
+
.optional()
|
|
321
|
+
.describe("Local project directory where .env.local should be written (strongly recommended to pass explicitly)"),
|
|
322
|
+
project: z
|
|
323
|
+
.string()
|
|
324
|
+
.optional()
|
|
325
|
+
.describe("Optional GCP project ID or connection ID (for multi-project accounts)"),
|
|
326
|
+
project_id: z
|
|
327
|
+
.string()
|
|
328
|
+
.optional()
|
|
329
|
+
.describe("Deprecated alias for `project`"),
|
|
330
|
+
}, async ({ app_name, addons, dir, project, project_id }) => {
|
|
331
|
+
try {
|
|
332
|
+
const appName = sanitizeAppName(app_name);
|
|
333
|
+
const effectiveProject = resolveProjectArg(project, project_id);
|
|
334
|
+
const targetDir = path.resolve(dir || process.cwd());
|
|
335
|
+
const homeDir = path.resolve(os.homedir());
|
|
336
|
+
if (targetDir === path.parse(targetDir).root || targetDir === homeDir) {
|
|
337
|
+
throw new Error(`Pass a specific project subdirectory in \`dir\` to init_app (refusing to write .env.local into "${targetDir}").`);
|
|
338
|
+
}
|
|
339
|
+
const result = await controlPlaneRequest(`/api/apps/${encodeURIComponent(appName)}/init`, {
|
|
340
|
+
method: "POST",
|
|
341
|
+
body: { addons },
|
|
342
|
+
project: effectiveProject,
|
|
343
|
+
// First-time Firestore creation LRO can take up to 90s
|
|
344
|
+
timeoutMs: 120_000,
|
|
345
|
+
});
|
|
346
|
+
const envLocalPath = upsertEnvLocal(targetDir, result.envVars ?? {});
|
|
347
|
+
return formatJsonResult({
|
|
348
|
+
appName: result.app.name,
|
|
349
|
+
addons: result.app.addons,
|
|
350
|
+
envLocalPath,
|
|
351
|
+
envKeysWritten: Object.keys(result.envVars ?? {}),
|
|
352
|
+
demoMode: Boolean(result.demoMode),
|
|
353
|
+
message: `Provisioned add-ons for "${result.app.name}" and updated ${envLocalPath}.`,
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
catch (err) {
|
|
357
|
+
return formatErrorResult(err);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
/**
|
|
361
|
+
* Tool 3: deploy_app
|
|
362
|
+
*/
|
|
363
|
+
server.tool("deploy_app", "Package a local directory into a .tar.gz (respecting .gitignore and excluding secrets/node_modules/.venv), stream-upload directly to the user's own GCS build bucket via signed URL, build with Cloud Buildpacks (or Dockerfile), and deploy to Cloud Run.", {
|
|
364
|
+
app_name: z
|
|
365
|
+
.string()
|
|
366
|
+
.min(1)
|
|
367
|
+
.describe("App name (becomes the Cloud Run service name)"),
|
|
368
|
+
dir: z
|
|
369
|
+
.string()
|
|
370
|
+
.min(1)
|
|
371
|
+
.describe("Absolute or relative path to the local app directory to deploy"),
|
|
372
|
+
max_instances: z
|
|
373
|
+
.number()
|
|
374
|
+
.int()
|
|
375
|
+
.min(1)
|
|
376
|
+
.max(1000)
|
|
377
|
+
.optional()
|
|
378
|
+
.describe(`Optional max Cloud Run instances (omit to keep existing service setting, or default ${ALWAYS_FREE_DEFAULTS.maxInstances} for new services)`),
|
|
379
|
+
region: z
|
|
380
|
+
.string()
|
|
381
|
+
.optional()
|
|
382
|
+
.describe("Optional GCP region (Pro+ for non-Always-Free regions, e.g. europe-west1)"),
|
|
383
|
+
project: z
|
|
384
|
+
.string()
|
|
385
|
+
.optional()
|
|
386
|
+
.describe("Optional GCP project ID or connection ID (for multi-project accounts)"),
|
|
387
|
+
project_id: z
|
|
388
|
+
.string()
|
|
389
|
+
.optional()
|
|
390
|
+
.describe("Deprecated alias for `project`"),
|
|
391
|
+
}, async ({ app_name, dir, max_instances, region, project, project_id }) => {
|
|
392
|
+
let archive = null;
|
|
393
|
+
try {
|
|
394
|
+
const appName = sanitizeAppName(app_name);
|
|
395
|
+
const effectiveProject = resolveProjectArg(project, project_id);
|
|
396
|
+
const cleanRegion = region?.trim().toLowerCase();
|
|
397
|
+
if (cleanRegion && !isValidGcpRegion(cleanRegion)) {
|
|
398
|
+
throw new Error(`Invalid Google Cloud region "${region}". Expected a region like "us-central1" or "europe-west1".`);
|
|
399
|
+
}
|
|
400
|
+
const resolvedDir = path.resolve(dir);
|
|
401
|
+
const homeDir = path.resolve(os.homedir());
|
|
402
|
+
if (resolvedDir === path.parse(resolvedDir).root || resolvedDir === homeDir) {
|
|
403
|
+
throw new Error(`Refusing to archive and deploy "${resolvedDir}". Pass a specific project directory.`);
|
|
404
|
+
}
|
|
405
|
+
if (!fs.existsSync(resolvedDir) ||
|
|
406
|
+
!fs.statSync(resolvedDir).isDirectory()) {
|
|
407
|
+
throw new Error(`Directory not found: ${resolvedDir}`);
|
|
408
|
+
}
|
|
409
|
+
// Request upload ticket first (verifies auth & plan limits before archiving)
|
|
410
|
+
const uploadTicket = await controlPlaneRequest(`/api/apps/${encodeURIComponent(appName)}/upload-url`, {
|
|
411
|
+
method: "POST",
|
|
412
|
+
body: {
|
|
413
|
+
contentType: "application/gzip",
|
|
414
|
+
},
|
|
415
|
+
project: effectiveProject,
|
|
416
|
+
});
|
|
417
|
+
archive = await packageAppDirectory(resolvedDir);
|
|
418
|
+
const MAX_ARCHIVE_BYTES = 150 * 1024 * 1024;
|
|
419
|
+
if (archive.sizeBytes > MAX_ARCHIVE_BYTES) {
|
|
420
|
+
throw new Error(`Packaged archive is ${Math.round(archive.sizeBytes / (1024 * 1024))} MB, exceeding the 150 MB upload limit. Add large assets to .gitignore.`);
|
|
421
|
+
}
|
|
422
|
+
if (!uploadTicket.demoMode) {
|
|
423
|
+
if (!uploadTicket.uploadUrl) {
|
|
424
|
+
throw new Error("Control Plane did not return a signed GCS uploadUrl for non-demo deploy.");
|
|
425
|
+
}
|
|
426
|
+
await uploadTarballToSignedGcsUrl(uploadTicket.uploadUrl, archive.tarballPath, archive.sizeBytes, 180_000, uploadTicket.requiredHeaders);
|
|
427
|
+
}
|
|
428
|
+
const deployBody = {
|
|
429
|
+
objectName: uploadTicket.objectName,
|
|
430
|
+
hasDockerfile: archive.hasDockerfile,
|
|
431
|
+
async: true,
|
|
432
|
+
...(archive.dockerfileName
|
|
433
|
+
? { dockerfileName: archive.dockerfileName }
|
|
434
|
+
: {}),
|
|
435
|
+
// Omit maxInstances when unspecified so existing Pro/Team scaling isn't downgraded to 3
|
|
436
|
+
...(max_instances !== undefined ? { maxInstances: max_instances } : {}),
|
|
437
|
+
...(cleanRegion ? { region: cleanRegion } : {}),
|
|
438
|
+
};
|
|
439
|
+
const startResult = await controlPlaneRequest(`/api/apps/${encodeURIComponent(appName)}/deploy`, {
|
|
440
|
+
method: "POST",
|
|
441
|
+
body: deployBody,
|
|
442
|
+
project: effectiveProject,
|
|
443
|
+
timeoutMs: 120_000,
|
|
444
|
+
});
|
|
445
|
+
let deployResult = startResult;
|
|
446
|
+
if (startResult.status === "building" && startResult.buildStartedAt) {
|
|
447
|
+
class TerminalDeployError extends Error {
|
|
448
|
+
}
|
|
449
|
+
const pollDeadline = Date.now() + 15 * 60 * 1000;
|
|
450
|
+
let consecutivePollErrors = 0;
|
|
451
|
+
while (Date.now() < pollDeadline) {
|
|
452
|
+
const remainingBeforeSleep = pollDeadline - Date.now();
|
|
453
|
+
if (remainingBeforeSleep <= 0)
|
|
454
|
+
break;
|
|
455
|
+
await new Promise((r) => setTimeout(r, Math.min(4000, remainingBeforeSleep)));
|
|
456
|
+
const remainingMs = pollDeadline - Date.now();
|
|
457
|
+
if (remainingMs <= 0)
|
|
458
|
+
break;
|
|
459
|
+
try {
|
|
460
|
+
const polled = await controlPlaneRequest(`/api/apps/${encodeURIComponent(appName)}/deploy`, {
|
|
461
|
+
method: "POST",
|
|
462
|
+
body: {
|
|
463
|
+
action: "poll",
|
|
464
|
+
buildStartedAt: startResult.buildStartedAt,
|
|
465
|
+
},
|
|
466
|
+
project: effectiveProject,
|
|
467
|
+
timeoutMs: Math.min(240_000, Math.max(5_000, remainingMs)),
|
|
468
|
+
});
|
|
469
|
+
consecutivePollErrors = 0;
|
|
470
|
+
if (polled.status === "failed") {
|
|
471
|
+
throw new TerminalDeployError(polled.error ||
|
|
472
|
+
`Cloud Build ${startResult.buildId} failed. Run diagnose_app for details.`);
|
|
473
|
+
}
|
|
474
|
+
if (polled.status === "live" && polled.app && polled.liveUrl) {
|
|
475
|
+
deployResult = {
|
|
476
|
+
...startResult,
|
|
477
|
+
status: "live",
|
|
478
|
+
app: polled.app,
|
|
479
|
+
imageUri: polled.imageUri ?? startResult.imageUri,
|
|
480
|
+
liveUrl: polled.liveUrl,
|
|
481
|
+
demoMode: polled.demoMode,
|
|
482
|
+
};
|
|
483
|
+
break;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
catch (pollErr) {
|
|
487
|
+
if (pollErr instanceof TerminalDeployError) {
|
|
488
|
+
throw pollErr;
|
|
489
|
+
}
|
|
490
|
+
const isRetryable4xx = pollErr instanceof ControlPlaneError &&
|
|
491
|
+
(pollErr.status === 408 || pollErr.status === 429);
|
|
492
|
+
if (pollErr instanceof ControlPlaneError &&
|
|
493
|
+
pollErr.status >= 400 &&
|
|
494
|
+
pollErr.status < 500 &&
|
|
495
|
+
!isRetryable4xx) {
|
|
496
|
+
throw pollErr;
|
|
497
|
+
}
|
|
498
|
+
consecutivePollErrors += 1;
|
|
499
|
+
if (consecutivePollErrors >= 5) {
|
|
500
|
+
throw pollErr;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (deployResult.status !== "live" || !deployResult.liveUrl) {
|
|
505
|
+
throw new Error(`Timed out waiting for Cloud Build ${startResult.buildId} to finish.`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
const gh = deployResult.app.github;
|
|
509
|
+
const githubSyncNotice = gh && gh.autoDeploy
|
|
510
|
+
? `Note: "${deployResult.app.name}" has GitHub auto-deploy enabled on ${gh.repoFullName} (${gh.branch}). Commit and push your local changes to GitHub so the next push doesn't overwrite this deploy.`
|
|
511
|
+
: undefined;
|
|
512
|
+
return formatJsonResult({
|
|
513
|
+
appName: deployResult.app.name,
|
|
514
|
+
liveUrl: deployResult.liveUrl ?? "",
|
|
515
|
+
buildId: deployResult.buildId,
|
|
516
|
+
imageUri: deployResult.imageUri,
|
|
517
|
+
buildStrategy: archive.hasDockerfile
|
|
518
|
+
? archive.dockerfileName ?? "Dockerfile"
|
|
519
|
+
: "Google Cloud Buildpacks",
|
|
520
|
+
filesPackaged: archive.fileCount,
|
|
521
|
+
archiveSizeKb: Math.max(1, Math.round(archive.sizeBytes / 1024)),
|
|
522
|
+
maxInstances: deployResult.app.maxInstances,
|
|
523
|
+
region: deployResult.app.region,
|
|
524
|
+
demoMode: Boolean(deployResult.demoMode),
|
|
525
|
+
...(githubSyncNotice ? { githubSyncNotice } : {}),
|
|
526
|
+
message: githubSyncNotice
|
|
527
|
+
? `Live at ${deployResult.liveUrl} (${githubSyncNotice})`
|
|
528
|
+
: `Live at ${deployResult.liveUrl}`,
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
catch (err) {
|
|
532
|
+
return formatErrorResult(err);
|
|
533
|
+
}
|
|
534
|
+
finally {
|
|
535
|
+
archive?.cleanup();
|
|
536
|
+
}
|
|
537
|
+
});
|
|
538
|
+
/**
|
|
539
|
+
* Tool 4: sync_secrets
|
|
540
|
+
*/
|
|
541
|
+
server.tool("sync_secrets", "Parse a local .env file and sync its keys into a single Always-Free Google Secret Manager JSON bundle (airborne-<app>-env) in the user's GCP project.", {
|
|
542
|
+
app_name: z.string().min(1).describe("App name"),
|
|
543
|
+
env_file: z
|
|
544
|
+
.string()
|
|
545
|
+
.min(1)
|
|
546
|
+
.describe("Absolute path to the project's .env file, or relative path combined with `dir` (e.g. .env.local)"),
|
|
547
|
+
dir: z
|
|
548
|
+
.string()
|
|
549
|
+
.optional()
|
|
550
|
+
.describe("Optional absolute project directory used to resolve a relative `env_file` path"),
|
|
551
|
+
project: z
|
|
552
|
+
.string()
|
|
553
|
+
.optional()
|
|
554
|
+
.describe("Optional GCP project ID or connection ID (for multi-project accounts)"),
|
|
555
|
+
project_id: z
|
|
556
|
+
.string()
|
|
557
|
+
.optional()
|
|
558
|
+
.describe("Deprecated alias for `project`"),
|
|
559
|
+
}, async ({ app_name, env_file, dir, project, project_id }) => {
|
|
560
|
+
try {
|
|
561
|
+
const appName = sanitizeAppName(app_name);
|
|
562
|
+
const effectiveProject = resolveProjectArg(project, project_id);
|
|
563
|
+
const realpath = fs.realpathSync.native ?? fs.realpathSync;
|
|
564
|
+
const isCaseInsensitiveFs = process.platform === "darwin" || process.platform === "win32";
|
|
565
|
+
const normPath = (p) => isCaseInsensitiveFs ? p.toLowerCase() : p;
|
|
566
|
+
const baseDir = dir ? path.resolve(dir) : process.cwd();
|
|
567
|
+
let homeDir = path.resolve(os.homedir());
|
|
568
|
+
try {
|
|
569
|
+
homeDir = realpath(homeDir);
|
|
570
|
+
}
|
|
571
|
+
catch {
|
|
572
|
+
// ignore if homedir cannot be resolved
|
|
573
|
+
}
|
|
574
|
+
const resolvedEnvPath = path.isAbsolute(env_file)
|
|
575
|
+
? path.resolve(env_file)
|
|
576
|
+
: path.resolve(baseDir, env_file);
|
|
577
|
+
if (!fs.existsSync(resolvedEnvPath)) {
|
|
578
|
+
throw new Error(`Env file not found: ${resolvedEnvPath}`);
|
|
579
|
+
}
|
|
580
|
+
const realEnvPath = realpath(resolvedEnvPath);
|
|
581
|
+
const envParentDir = path.dirname(realEnvPath);
|
|
582
|
+
if (normPath(envParentDir) === normPath(homeDir) ||
|
|
583
|
+
normPath(envParentDir) === normPath(path.parse(realEnvPath).root)) {
|
|
584
|
+
throw new Error(`Refusing to read "${realEnvPath}" directly from home or filesystem root. Pass an explicit path inside your app directory (or pass \`dir\`).`);
|
|
585
|
+
}
|
|
586
|
+
if (dir) {
|
|
587
|
+
const realBaseDir = realpath(baseDir);
|
|
588
|
+
const relToBase = path.relative(normPath(realBaseDir), normPath(realEnvPath));
|
|
589
|
+
if (relToBase === ".." ||
|
|
590
|
+
relToBase.startsWith(`..${path.sep}`) ||
|
|
591
|
+
path.isAbsolute(relToBase)) {
|
|
592
|
+
throw new Error(`Refusing to read "${env_file}" because it resolves outside project directory "${realBaseDir}".`);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
const SENSITIVE_SEGMENTS = new Set([
|
|
596
|
+
".aws",
|
|
597
|
+
".ssh",
|
|
598
|
+
".gcloud",
|
|
599
|
+
".airborne",
|
|
600
|
+
".airborne-data",
|
|
601
|
+
".gnupg",
|
|
602
|
+
".kube",
|
|
603
|
+
".docker",
|
|
604
|
+
".npmrc",
|
|
605
|
+
".netrc",
|
|
606
|
+
".pypirc",
|
|
607
|
+
]);
|
|
608
|
+
const pathSegments = realEnvPath
|
|
609
|
+
.split(path.sep)
|
|
610
|
+
.filter(Boolean)
|
|
611
|
+
.map((s) => s.toLowerCase());
|
|
612
|
+
if (pathSegments.some((seg) => SENSITIVE_SEGMENTS.has(seg))) {
|
|
613
|
+
throw new Error(`Refusing to read "${realEnvPath}" from a sensitive system/credential directory.`);
|
|
614
|
+
}
|
|
615
|
+
const envBaseName = path.basename(realEnvPath);
|
|
616
|
+
if (!/^\.env(?:\.[a-zA-Z0-9._-]+)?$/i.test(envBaseName) &&
|
|
617
|
+
!/^[a-zA-Z0-9._-]+\.env$/i.test(envBaseName)) {
|
|
618
|
+
throw new Error(`Refusing to sync "${envBaseName}". sync_secrets only accepts .env files (e.g. .env, .env.local, .env.production).`);
|
|
619
|
+
}
|
|
620
|
+
const rawMap = parseEnvFile(realEnvPath);
|
|
621
|
+
const skippedKeys = [];
|
|
622
|
+
const envMap = Object.create(null);
|
|
623
|
+
for (const [k, v] of Object.entries(rawMap)) {
|
|
624
|
+
if (RESERVED_CLOUD_RUN_ENV_KEYS.has(k)) {
|
|
625
|
+
skippedKeys.push(k);
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
envMap[k] = v;
|
|
629
|
+
}
|
|
630
|
+
const keyNames = Object.keys(envMap);
|
|
631
|
+
if (keyNames.length === 0) {
|
|
632
|
+
throw new Error(`No valid syncable KEY=VALUE pairs found in ${env_file}.`);
|
|
633
|
+
}
|
|
634
|
+
const payloadBytes = Buffer.byteLength(JSON.stringify(envMap), "utf8");
|
|
635
|
+
if (payloadBytes > 65_536) {
|
|
636
|
+
throw new Error(`Packed secrets JSON is ${Math.round(payloadBytes / 1024)} KiB, exceeding Google Secret Manager's 64 KiB version limit.`);
|
|
637
|
+
}
|
|
638
|
+
const result = await controlPlaneRequest(`/api/apps/${encodeURIComponent(appName)}/secrets`, {
|
|
639
|
+
method: "POST",
|
|
640
|
+
body: { secrets: envMap },
|
|
641
|
+
project: effectiveProject,
|
|
642
|
+
});
|
|
643
|
+
return formatJsonResult({
|
|
644
|
+
appName,
|
|
645
|
+
secretName: result.secretName,
|
|
646
|
+
syncedKeys: keyNames,
|
|
647
|
+
...(skippedKeys.length > 0 ? { skippedReservedKeys: skippedKeys } : {}),
|
|
648
|
+
keyCount: result.keyCount,
|
|
649
|
+
demoMode: Boolean(result.demoMode),
|
|
650
|
+
message: `Synced ${result.keyCount} secret(s) into "${result.secretName}" (1 packed secret to stay Always-Free). Re-deploy to pick up updated values if the app is already running.`,
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
catch (err) {
|
|
654
|
+
return formatErrorResult(err);
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
/**
|
|
658
|
+
* Tool 5: diagnose_app
|
|
659
|
+
*/
|
|
660
|
+
server.tool("diagnose_app", "Pull recent Cloud Run & Cloud Build error logs from the user's GCP project and translate cryptic GCP errors into plain-English fixes.", {
|
|
661
|
+
app_name: z.string().min(1).describe("App name to inspect"),
|
|
662
|
+
lines: z
|
|
663
|
+
.number()
|
|
664
|
+
.int()
|
|
665
|
+
.min(5)
|
|
666
|
+
.max(200)
|
|
667
|
+
.optional()
|
|
668
|
+
.describe("Maximum number of recent log entries to fetch (default: 40)"),
|
|
669
|
+
project: z
|
|
670
|
+
.string()
|
|
671
|
+
.optional()
|
|
672
|
+
.describe("Optional GCP project ID or connection ID (for multi-project accounts)"),
|
|
673
|
+
project_id: z
|
|
674
|
+
.string()
|
|
675
|
+
.optional()
|
|
676
|
+
.describe("Deprecated alias for `project`"),
|
|
677
|
+
}, { readOnlyHint: true }, async ({ app_name, lines, project, project_id }) => {
|
|
678
|
+
try {
|
|
679
|
+
const appName = sanitizeAppName(app_name);
|
|
680
|
+
const effectiveProject = resolveProjectArg(project, project_id);
|
|
681
|
+
const limit = lines ?? 40;
|
|
682
|
+
const report = await controlPlaneRequest(`/api/apps/${encodeURIComponent(appName)}/diagnose?lines=${limit}`, { project: effectiveProject });
|
|
683
|
+
return formatJsonResult(report);
|
|
684
|
+
}
|
|
685
|
+
catch (err) {
|
|
686
|
+
return formatErrorResult(err);
|
|
687
|
+
}
|
|
688
|
+
});
|
|
689
|
+
/**
|
|
690
|
+
* Tool 6: toggle_app
|
|
691
|
+
*/
|
|
692
|
+
server.tool("toggle_app", "Reversibly pause or resume public traffic to a Cloud Run app by removing or restoring allUsers on roles/run.invoker (zero data loss).", {
|
|
693
|
+
app_name: z.string().min(1).describe("App name"),
|
|
694
|
+
action: z
|
|
695
|
+
.enum(["pause", "resume"])
|
|
696
|
+
.describe('"pause" halts public traffic immediately; "resume" restores public access'),
|
|
697
|
+
project: z
|
|
698
|
+
.string()
|
|
699
|
+
.optional()
|
|
700
|
+
.describe("Optional GCP project ID or connection ID (for multi-project accounts)"),
|
|
701
|
+
project_id: z
|
|
702
|
+
.string()
|
|
703
|
+
.optional()
|
|
704
|
+
.describe("Deprecated alias for `project`"),
|
|
705
|
+
}, async ({ app_name, action, project, project_id }) => {
|
|
706
|
+
try {
|
|
707
|
+
const appName = sanitizeAppName(app_name);
|
|
708
|
+
const effectiveProject = resolveProjectArg(project, project_id);
|
|
709
|
+
const result = await controlPlaneRequest(`/api/apps/${encodeURIComponent(appName)}/toggle`, {
|
|
710
|
+
method: "POST",
|
|
711
|
+
body: { action },
|
|
712
|
+
project: effectiveProject,
|
|
713
|
+
timeoutMs: 90_000,
|
|
714
|
+
});
|
|
715
|
+
return formatJsonResult({
|
|
716
|
+
appName: result.app.name,
|
|
717
|
+
action: result.action,
|
|
718
|
+
isPaused: result.app.isPaused,
|
|
719
|
+
liveUrl: result.app.liveUrl,
|
|
720
|
+
demoMode: Boolean(result.demoMode),
|
|
721
|
+
message: action === "pause"
|
|
722
|
+
? `Paused public traffic for "${result.app.name}". All Firestore & Cloud Storage data remains intact.`
|
|
723
|
+
: `Resumed public traffic for "${result.app.name}"${result.app.liveUrl ? ` at ${result.app.liveUrl}` : ""}.`,
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
catch (err) {
|
|
727
|
+
return formatErrorResult(err);
|
|
728
|
+
}
|
|
729
|
+
});
|
|
730
|
+
async function main() {
|
|
731
|
+
const transport = new StdioServerTransport();
|
|
732
|
+
await server.connect(transport);
|
|
733
|
+
}
|
|
734
|
+
main().catch((err) => {
|
|
735
|
+
console.error("[airborne] Fatal error:", err);
|
|
736
|
+
process.exit(1);
|
|
737
|
+
});
|