Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ This server provides your AI with dedicated tools for managing your LocalStack e
| [`localstack-state-management`](./src/tools/localstack-state-management.ts) | Manages local file-based LocalStack state export/import workflows | - Export LocalStack state to a local file on disk through the LocalStack State REST API<br/>- Import LocalStack state from a local file<br/>- Inspect current LocalStack state as JSON metamodel data<br/>- Reset all state or only selected services<br/>- Supports service-level granularity for export, reset, and inspect<br/>- Use this for local disk workflows; use Cloud Pods for remote cloud-backed snapshots<br/>- Requires a valid LocalStack Auth Token |
| [`localstack-extensions`](./src/tools/localstack-extensions.ts) | Installs, uninstalls, lists, and discovers LocalStack Extensions | - Manage installed extensions (`list`, `install`, `uninstall`) inside the running container<br/>- Browse the LocalStack Extensions marketplace (`available`)<br/>- Requires a valid LocalStack Auth Token |
| [`localstack-ephemeral-instances`](./src/tools/localstack-ephemeral-instances.ts) | Manages cloud-hosted LocalStack Ephemeral Instances | - Create temporary cloud-hosted LocalStack instances and get an endpoint URL<br/>- List available ephemeral instances, fetch logs, and delete instances<br/>- Supports lifetime, extension preload, Cloud Pod preload, and custom env vars on create<br/>- Requires a valid LocalStack Auth Token |
| [`localstack-aws-client`](./src/tools/localstack-aws-client.ts) | Runs AWS CLI commands inside the LocalStack for AWS container | - Executes commands via `awslocal` inside the running container<br/>- Sanitizes commands to block shell chaining<br/>- Auto-detects LocalStack coverage errors and links to docs |
| [`localstack-aws-client`](./src/tools/localstack-aws-client.ts) | Runs AWS CLI commands inside the LocalStack for AWS container | - Executes commands via `awslocal` inside the running container, against the gateway's in-container address (works with a remapped host port, `LOCALSTACK_HOST` or `GATEWAY_LISTEN`)<br/>- Sanitizes commands to block shell chaining<br/>- Auto-detects LocalStack coverage errors and links to docs |
| [`localstack-azure-client`](./src/tools/localstack-azure-client.ts) | Runs Azure CLI (`az`) commands against the LocalStack for Azure emulator | - Runs the Azure CLI installed on your machine with its own profile, never your Azure login<br/>- Blocks shell syntax and commands that would change the profile, install software or never end<br/>- Uses the extensions you installed with `az extension add`<br/>- Requires the Azure CLI and a valid LocalStack Auth Token |
| [`localstack-aws-replicator`](./src/tools/localstack-aws-replicator.ts) | Replicates external AWS resources into a running LocalStack instance | - Start single-resource replication jobs with a resource type and identifier or ARN<br/>- Start batch replication jobs, such as SSM parameters under a path prefix<br/>- Poll job status by job ID and list existing jobs<br/>- List resource types supported by the running Replicator extension<br/>- Reads source AWS credentials from the MCP server environment and supports optional target account or region overrides |
| [`localstack-app-inspector`](./src/tools/localstack-app-inspector.ts) | Inspects LocalStack application traces, spans, events, and IAM evaluations | - Enable or disable App Inspector for the running LocalStack instance<br/>- List and inspect traces to understand AWS service-to-service flows<br/>- Drill into spans, events, payload metadata, and IAM policy evaluation events<br/>- Filter by service, region, operation, resource, ARN, status, and time range<br/>- Requires a valid LocalStack Auth Token and the App Inspector feature in the connected LocalStack license |
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"test": "jest",
"test:mcp:direct": "yarn build && playwright test -c playwright.config.mjs tests/mcp/direct.spec.mjs tests/mcp/azure-offline.spec.mjs",
"test:mcp:evals": "yarn build && playwright test -c playwright.config.mjs tests/mcp/evals.spec.mjs",
"test:mcp:tools": "yarn build && playwright test -c playwright.config.mjs tests/mcp/tools.spec.mjs",
"test:mcp:tools": "yarn build && playwright test -c playwright.config.mjs --workers=1 tests/mcp/tools.spec.mjs tests/mcp/aws-client-ports.spec.mjs",
"test:mcp": "yarn test:mcp:direct && yarn test:mcp:tools && yarn test:mcp:evals"
},
"dependencies": {
Expand Down
119 changes: 119 additions & 0 deletions src/lib/aws/awslocal-endpoint.logic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import {
awsCliCommandName,
awslocalExecEnv,
buildsClientUrl,
containerEnvValue,
containerGatewayEndpoint,
containerGatewayPort,
} from "./awslocal-endpoint.logic";

describe("containerGatewayEndpoint", () => {
test("default: no GATEWAY_LISTEN means the gateway on 4566", () => {
expect(containerGatewayEndpoint(undefined)).toBe("http://localhost:4566");
expect(containerGatewayEndpoint(["PATH=/usr/bin", "DEBUG=1"])).toBe("http://localhost:4566");
});

test("the server's own container spec (:4566,:443) keeps 4566", () => {
expect(containerGatewayEndpoint(["GATEWAY_LISTEN=:4566,:443"])).toBe("http://localhost:4566");
});

test("mapped host port: LOCALSTACK_HOST names the host side and is ignored", () => {
const env = ["LOCALSTACK_HOST=localhost.localstack.cloud:4700", "PATH=/usr/bin"];
expect(containerGatewayEndpoint(env)).toBe("http://localhost:4566");
});

test("mapped host port with the server's GATEWAY_LISTEN still targets the container port", () => {
const env = ["LOCALSTACK_HOST=localhost.localstack.cloud:4700", "GATEWAY_LISTEN=:4566,:443"];
expect(containerGatewayEndpoint(env)).toBe("http://localhost:4566");
});

test("custom GATEWAY_LISTEN: the first entry's port", () => {
expect(containerGatewayEndpoint(["GATEWAY_LISTEN=0.0.0.0:4700"])).toBe("http://localhost:4700");
expect(containerGatewayEndpoint(["GATEWAY_LISTEN=:5000,:4566"])).toBe("http://localhost:5000");
expect(containerGatewayEndpoint(["GATEWAY_LISTEN= 127.0.0.1:4800 , :443"])).toBe(
"http://localhost:4800"
);
});

test("custom GATEWAY_LISTEN together with LOCALSTACK_HOST on another port", () => {
const env = ["GATEWAY_LISTEN=0.0.0.0:4700", "LOCALSTACK_HOST=localhost.localstack.cloud:5700"];
expect(containerGatewayEndpoint(env)).toBe("http://localhost:4700");
});

test("IPv6 entries", () => {
expect(containerGatewayPort(["GATEWAY_LISTEN=[::]:4700"])).toBe(4700);
expect(containerGatewayPort(["GATEWAY_LISTEN=[::1]"])).toBe(4566);
});

test("a host without a port keeps the default port, as LocalStack reads it", () => {
expect(containerGatewayPort(["GATEWAY_LISTEN=0.0.0.0"])).toBe(4566);
});

test("LOCALSTACK_GATEWAY_LISTEN wins, since the entrypoint exports it as GATEWAY_LISTEN", () => {
const env = ["GATEWAY_LISTEN=:4566", "LOCALSTACK_GATEWAY_LISTEN=:4900"];
expect(containerGatewayPort(env)).toBe(4900);
});

test("empty or unreadable values fall back to 4566", () => {
expect(containerGatewayPort(["GATEWAY_LISTEN="])).toBe(4566);
expect(containerGatewayPort(["GATEWAY_LISTEN=:abc"])).toBe(4566);
expect(containerGatewayPort(["GATEWAY_LISTEN=:0"])).toBe(4566);
expect(containerGatewayPort(["GATEWAY_LISTEN=:70000"])).toBe(4566);
expect(containerGatewayPort(["GATEWAY_LISTEN=[::1"])).toBe(4566);
});

test("a variable whose name only starts with GATEWAY_LISTEN is not read", () => {
expect(containerGatewayPort(["GATEWAY_LISTEN_EXTRA=:4700"])).toBe(4566);
});
});

describe("containerEnvValue", () => {
test("keeps '=' inside the value", () => {
expect(containerEnvValue(["A=b=c"], "A")).toBe("b=c");
expect(containerEnvValue(["A=1"], "B")).toBeUndefined();
});
});

describe("awslocalExecEnv", () => {
const mapped = ["LOCALSTACK_HOST=localhost.localstack.cloud:4700", "GATEWAY_LISTEN=:4600"];

test("sets only AWS_ENDPOINT_URL, to the container-side gateway", () => {
expect(awslocalExecEnv(mapped, ["sqs", "list-queues"])).toEqual([
"AWS_ENDPOINT_URL=http://localhost:4600",
]);
});

test.each([
[["s3", "presign", "s3://bucket/key"]],
[["s3", "presign", "s3://bucket/key", "--expires-in", "60"]],
[["--region", "eu-west-1", "s3", "presign", "s3://bucket/key"]],
[["rds", "generate-db-auth-token", "--hostname", "db", "--port", "5432", "--username", "u"]],
[["eks", "get-token", "--cluster-name", "c1"]],
[["dsql", "generate-db-connect-auth-token", "--hostname", "h"]],
[["dsql", "generate-db-connect-admin-auth-token", "--hostname", "h"]],
])("%j builds a URL for the caller, so it keeps awslocal's LOCALSTACK_HOST endpoint", (args) => {
expect(awslocalExecEnv(mapped, args)).toEqual([]);
});

test.each([
[["s3", "ls"]],
[["s3", "cp", "presign", "s3://bucket/presign"]],
[["s3api", "get-object", "--bucket", "presign", "--key", "k", "out"]],
[["rds", "describe-db-instances"]],
[["eks", "list-clusters"]],
[["--output", "s3", "sqs", "list-queues"]],
])("%j calls the gateway, so it gets the container-side endpoint", (args) => {
expect(awslocalExecEnv(mapped, args)).toEqual(["AWS_ENDPOINT_URL=http://localhost:4600"]);
});
});

describe("awsCliCommandName", () => {
test("skips global options and their values", () => {
expect(awsCliCommandName(["--debug", "--profile", "p", "S3", "Presign", "x"])).toBe(
"s3 presign"
);
expect(awsCliCommandName(["--region=us-east-1", "sqs", "list-queues"])).toBe("sqs list-queues");
expect(awsCliCommandName(["help"])).toBe("help");
expect(buildsClientUrl([])).toBe(false);
});
});
116 changes: 116 additions & 0 deletions src/lib/aws/awslocal-endpoint.logic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/**
* Where `awslocal` must send requests when it runs inside the LocalStack container.
*
* `awslocal` builds its endpoint from `LOCALSTACK_HOST` unless `AWS_ENDPOINT_URL` is set.
* `LOCALSTACK_HOST` names the gateway as the host sees it (for example
* `localhost.localstack.cloud:4700` when the gateway is published on host port 4700), and
* that port is not open inside the container. The gateway listens inside the container on
* the first `GATEWAY_LISTEN` address, port 4566 by default, so `awslocal` gets that address
* as `AWS_ENDPOINT_URL` for its own process only. The container's `LOCALSTACK_HOST` stays as
* it is, so the URLs LocalStack returns (SQS queue URLs) still name the host-side address.
*
* Commands that only build a URL or token for the caller, without calling the gateway
* (`s3 presign`), are the exception: their output is used from the host, so they keep the
* `LOCALSTACK_HOST` address `awslocal` picks on its own.
*/

export const DEFAULT_CONTAINER_GATEWAY_PORT = 4566;

/**
* AWS CLI commands that sign a URL or token locally and print it, without a request to the
* endpoint, so the endpoint they embed must be reachable by whoever uses the output.
*/
const CLIENT_URL_COMMANDS = new Set([
"s3 presign",
"rds generate-db-auth-token",
"eks get-token",
"dsql generate-db-connect-auth-token",
"dsql generate-db-connect-admin-auth-token",
]);

/** AWS CLI global options that take a value, so the next argument is not the service. */
const GLOBAL_OPTIONS_WITH_VALUE = new Set([
"--profile",
"--region",
"--output",
"--query",
"--endpoint-url",
"--ca-bundle",
"--color",
"--cli-read-timeout",
"--cli-connect-timeout",
"--cli-binary-format",
]);

/** The value of `key` in a container's `KEY=value` environment list, or undefined. */
export function containerEnvValue(env: string[] | undefined, key: string): string | undefined {
const prefix = `${key}=`;
const entry = (env ?? []).find((item) => item.startsWith(prefix));
return entry === undefined ? undefined : entry.slice(prefix.length);
}

/**
* The port of the first `GATEWAY_LISTEN` entry, read the way LocalStack reads it: `[ipv6]:port`,
* `host:port`, `:port`, or a host alone, which keeps the default port. The container entrypoint
* exports `LOCALSTACK_GATEWAY_LISTEN` as `GATEWAY_LISTEN`, so the prefixed name wins. An unset,
* empty or unreadable value means the default port.
*
* This does not reuse `parseGatewayListen` in `container-spec.logic.ts`: that one parses the
* value the server is given to start a container, and reads a bare entry (`4700`) as a port.
* This one reads the value a running container already has, so it follows how LocalStack
* parses each address (`HostAndPort.parse`), where a bare entry is a host on the default port.
*
* `GATEWAY_LISTEN=:0` lets LocalStack pick a free port, which the environment does not reveal;
* it falls back to 4566.
*/
export function containerGatewayPort(env: string[] | undefined): number {
const raw =
containerEnvValue(env, "LOCALSTACK_GATEWAY_LISTEN") ?? containerEnvValue(env, "GATEWAY_LISTEN");
const first = raw?.split(",")[0]?.trim();
if (!first) return DEFAULT_CONTAINER_GATEWAY_PORT;

let portText: string | undefined;
if (first.startsWith("[")) {
portText = /^\[[^\]]+\](?::(\d+))?$/.exec(first)?.[1];
} else if (first.includes(":")) {
portText = first.slice(first.indexOf(":") + 1);
}
if (portText === undefined) return DEFAULT_CONTAINER_GATEWAY_PORT;

const port = Number(portText);
return Number.isInteger(port) && port > 0 && port < 65536 ? port : DEFAULT_CONTAINER_GATEWAY_PORT;
}

/** The gateway as a process inside the container reaches it. */
export function containerGatewayEndpoint(env: string[] | undefined): string {
return `http://localhost:${containerGatewayPort(env)}`;
}

/** The service and operation of an AWS CLI argument list, skipping global options. */
export function awsCliCommandName(args: string[]): string {
const positional: string[] = [];
for (let i = 0; i < args.length && positional.length < 2; i++) {
const arg = args[i];
if (arg.startsWith("-")) {
if (GLOBAL_OPTIONS_WITH_VALUE.has(arg)) i++;
continue;
}
positional.push(arg.toLowerCase());
}
return positional.join(" ");
}

/** Whether the command builds a URL or token for the caller instead of calling the gateway. */
export function buildsClientUrl(args: string[]): boolean {
return CLIENT_URL_COMMANDS.has(awsCliCommandName(args));
}

/**
* The environment for `awslocal <args>` in the container whose environment is `env`: the
* container-side gateway, except for commands that build a URL for the caller, which keep
* `awslocal`'s own `LOCALSTACK_HOST` endpoint.
*/
export function awslocalExecEnv(env: string[] | undefined, args: string[]): string[] {
if (buildsClientUrl(args)) return [];
return [`AWS_ENDPOINT_URL=${containerGatewayEndpoint(env)}`];
}
21 changes: 21 additions & 0 deletions src/lib/aws/awslocal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { DockerApiClient } from "../docker/docker.client";
import { awslocalExecEnv, buildsClientUrl } from "./awslocal-endpoint.logic";

/**
* Runs `awslocal <args>` inside the LocalStack container, pointed at the gateway's
* container-side address (see `awslocal-endpoint.logic.ts`), so it works whatever host port
* publishes the gateway and whatever `LOCALSTACK_HOST` says. Commands that build a URL for
* the caller keep `awslocal`'s own endpoint and need no container inspect.
*/
export async function execAwslocal(
dockerClient: DockerApiClient,
containerId: string,
args: string[]
) {
const containerEnv = buildsClientUrl(args)
? undefined
: (await dockerClient.inspectContainer(containerId)).env;
return dockerClient.executeInContainer(containerId, ["awslocal", ...args], undefined, {
env: awslocalExecEnv(containerEnv, args),
});
}
Loading