-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathlocalstack-extensions.ts
More file actions
303 lines (262 loc) · 10.7 KB
/
localstack-extensions.ts
File metadata and controls
303 lines (262 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { z } from "zod";
import { type ToolMetadata, type InferSchema } from "xmcp";
import { HttpClient, HttpError } from "../core/http-client";
import { runCommand, stripAnsiCodes } from "../core/command-runner";
import {
runPreflights,
requireLocalStackCli,
requireLocalStackRunning,
requireProFeature,
} from "../core/preflight";
import { ResponseBuilder } from "../core/response-builder";
import { ProFeature } from "../lib/localstack/license-checker";
export const schema = {
action: z
.enum(["list", "install", "uninstall", "available"])
.describe(
"list = installed extensions; install = install an extension; uninstall = remove an extension; available = browse the marketplace/extensions library"
),
name: z
.string()
.optional()
.describe(
"Extension package name (e.g. 'localstack-extension-typedb' or 'localstack-extension-typedb==1.0.0'). Required for install and uninstall actions."
),
source: z
.string()
.optional()
.describe(
"Git URL to install from (e.g. 'git+https://github.com/org/repo.git'). Use this instead of name when installing from a repository."
),
};
export const metadata: ToolMetadata = {
name: "localstack-extensions",
description: "Install, uninstall, list, and discover LocalStack Extensions from the marketplace",
annotations: {
title: "LocalStack Extensions",
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
},
};
interface MarketplaceExtension {
name?: string;
summary?: string;
description?: string;
author?: string;
version?: string;
}
const AUTH_TOKEN_REQUIRED_MESSAGE =
"LOCALSTACK_AUTH_TOKEN is not set in your environment. LocalStack Extensions require a valid Auth Token. Please set it and try again.";
export default async function localstackExtensions({
action,
name,
source,
}: InferSchema<typeof schema>) {
const checks = [
requireLocalStackCli(),
requireLocalStackRunning(),
requireProFeature(ProFeature.EXTENSIONS),
];
const preflightError = await runPreflights(checks);
if (preflightError) return preflightError;
switch (action) {
case "list":
return await handleList();
case "install":
return await handleInstall(name, source);
case "uninstall":
return await handleUninstall(name);
case "available":
return await handleAvailable();
default:
return ResponseBuilder.error("Unknown action", `Unsupported action: ${action}`);
}
}
function requireAuthTokenForCli() {
if (!process.env.LOCALSTACK_AUTH_TOKEN) {
return ResponseBuilder.error("Auth Token Required", AUTH_TOKEN_REQUIRED_MESSAGE);
}
return null;
}
function cleanOutput(stdout: string, stderr: string) {
return {
stdout: stripAnsiCodes(stdout || "").trim(),
stderr: stripAnsiCodes(stderr || "").trim(),
};
}
function combineOutput(stdout: string, stderr: string): string {
return [stdout, stderr].filter((part) => part.trim().length > 0).join("\n").trim();
}
async function handleList() {
const authError = requireAuthTokenForCli();
if (authError) return authError;
const cmd = await runCommand("localstack", ["extensions", "list"], {
env: { ...process.env },
});
const cleaned = cleanOutput(cmd.stdout, cmd.stderr);
const combined = combineOutput(cleaned.stdout, cleaned.stderr);
const combinedLower = combined.toLowerCase();
if (cmd.exitCode !== 0 && !combined) {
return ResponseBuilder.error("List Failed", cleaned.stderr || "Failed to list installed extensions.");
}
const looksEmpty =
!combined ||
combinedLower.includes("no extensions installed") ||
combinedLower.includes("no extension installed");
if (looksEmpty) {
return ResponseBuilder.markdown(
"No LocalStack extensions are currently installed.\n\nUse the `available` action to browse the marketplace."
);
}
return ResponseBuilder.markdown(`## Installed LocalStack Extensions\n\n\`\`\`\n${combined}\n\`\`\``);
}
async function handleInstall(name?: string, source?: string) {
const authError = requireAuthTokenForCli();
if (authError) return authError;
const hasName = !!name;
const hasSource = !!source;
if ((hasName && hasSource) || (!hasName && !hasSource)) {
return ResponseBuilder.error(
"Invalid Parameters",
"Provide either `name` or `source` for install, but not both."
);
}
const target = source || name!;
const cmd = await runCommand("localstack", ["extensions", "install", target], {
env: { ...process.env },
timeout: 120000,
});
const cleaned = cleanOutput(cmd.stdout, cmd.stderr);
const combined = combineOutput(cleaned.stdout, cleaned.stderr);
const combinedLower = combined.toLowerCase();
if (combinedLower.includes("could not resolve package")) {
return ResponseBuilder.error(
"Extension Not Found",
`Could not resolve the extension package '${name || target}'. Please verify it exists on PyPI, or provide a git repository URL using the source parameter.`
);
}
if (combinedLower.includes("no module named 'localstack.pro'")) {
return ResponseBuilder.error(
"Auth Token Required",
"LocalStack Pro modules are not available. Ensure LOCALSTACK_AUTH_TOKEN is set correctly and LocalStack is running with a valid license."
);
}
if (
combinedLower.includes("non-zero exit status") ||
combinedLower.includes("returned non-zero")
) {
return ResponseBuilder.error(
"Install Failed",
"The extension could not be installed from the provided source. The repository may not contain valid LocalStack extension code. Run the command again with --verbose for more details, or check that the repository contains a proper LocalStack extension."
);
}
const hasSuccessPattern = combinedLower.includes("extension successfully installed");
if (cmd.exitCode !== 0 && !hasSuccessPattern) {
return ResponseBuilder.error("Install Failed", cleaned.stderr || "Extension installation failed.");
}
if (hasSuccessPattern || cmd.exitCode === 0) {
const restartCmd = await runCommand("localstack", ["restart"], { timeout: 60000 });
const restartCleaned = cleanOutput(restartCmd.stdout, restartCmd.stderr);
const restartCombined = combineOutput(restartCleaned.stdout, restartCleaned.stderr);
let response = `## Extension Installation Result\n\n\`\`\`\n${combined || "Extension successfully installed."}\n\`\`\`\n\n`;
response += "LocalStack was restarted to activate the extension.";
if (restartCombined) {
response += `\n\n### Restart Output\n\n\`\`\`\n${restartCombined}\n\`\`\``;
}
if (restartCmd.exitCode !== 0) {
response += "\n\n⚠️ Restart command reported an issue. Please verify LocalStack status.";
}
return ResponseBuilder.markdown(response);
}
return ResponseBuilder.error("Install Failed", cleaned.stderr || "Extension installation failed.");
}
async function handleUninstall(name?: string) {
const authError = requireAuthTokenForCli();
if (authError) return authError;
if (!name) {
return ResponseBuilder.error(
"Missing Required Parameter",
"The `uninstall` action requires the `name` parameter to be specified."
);
}
const cmd = await runCommand("localstack", ["extensions", "uninstall", name], {
env: { ...process.env },
timeout: 60000,
});
const cleaned = cleanOutput(cmd.stdout, cmd.stderr);
const combined = combineOutput(cleaned.stdout, cleaned.stderr);
const combinedLower = combined.toLowerCase();
if (combinedLower.includes("no module named 'localstack.pro'")) {
return ResponseBuilder.error(
"Auth Token Required",
"LocalStack Pro modules are not available. Ensure LOCALSTACK_AUTH_TOKEN is set correctly and LocalStack is running with a valid license."
);
}
const hasSuccessPattern = combinedLower.includes("extension successfully uninstalled");
if (cmd.exitCode !== 0 && !hasSuccessPattern) {
return ResponseBuilder.error("Uninstall Failed", cleaned.stderr || "Extension uninstallation failed.");
}
if (hasSuccessPattern || cmd.exitCode === 0) {
const restartCmd = await runCommand("localstack", ["restart"], { timeout: 60000 });
const restartCleaned = cleanOutput(restartCmd.stdout, restartCmd.stderr);
const restartCombined = combineOutput(restartCleaned.stdout, restartCleaned.stderr);
let response = `## Extension Uninstall Result\n\n\`\`\`\n${combined || "Extension successfully uninstalled."}\n\`\`\`\n\n`;
response += "LocalStack was restarted to apply extension removal.";
if (restartCombined) {
response += `\n\n### Restart Output\n\n\`\`\`\n${restartCombined}\n\`\`\``;
}
if (restartCmd.exitCode !== 0) {
response += "\n\n⚠️ Restart command reported an issue. Please verify LocalStack status.";
}
return ResponseBuilder.markdown(response);
}
return ResponseBuilder.error("Uninstall Failed", cleaned.stderr || "Extension uninstallation failed.");
}
async function handleAvailable() {
const token = process.env.LOCALSTACK_AUTH_TOKEN;
if (!token) {
return ResponseBuilder.error(
"Authentication Failed",
"Could not fetch the marketplace. Ensure LOCALSTACK_AUTH_TOKEN is set correctly."
);
}
const encoded = Buffer.from(`:${token}`).toString("base64");
const client = new HttpClient();
try {
const marketplace = await client.request<MarketplaceExtension[]>(
"https://api.localstack.cloud/v1/extensions/marketplace",
{
method: "GET",
baseUrl: "",
headers: {
Authorization: `Basic ${encoded}`,
Accept: "application/json",
},
}
);
if (!Array.isArray(marketplace)) {
return ResponseBuilder.error("Marketplace Fetch Failed", "Unexpected marketplace response format.");
}
const simplified = marketplace.map((item) => ({
name: item.name || "unknown-extension",
summary: item.summary || item.description || "No summary provided.",
author: item.author || "Unknown",
version: item.version || "Unknown",
}));
let markdown = `# LocalStack Extensions Marketplace\n\n${simplified.length} extensions available. Install any with the \`install\` action.\n\n---`;
for (const extension of simplified) {
markdown += `\n\n### ${extension.name}\n**Author:** ${extension.author} | **Version:** ${extension.version}\n${extension.summary}\n\n---`;
}
return ResponseBuilder.markdown(markdown);
} catch (error) {
if (error instanceof HttpError && (error.status === 401 || error.status === 403)) {
return ResponseBuilder.error(
"Authentication Failed",
"Could not fetch the marketplace. Ensure LOCALSTACK_AUTH_TOKEN is set correctly."
);
}
const message = error instanceof Error ? error.message : String(error);
return ResponseBuilder.error("Marketplace Fetch Failed", message);
}
}