
Hastening AWS Org Sign-ins
Administrating Multiple AWS Organizations is a critical Builder Survival Skill. but burns developer time. I reclaim 16 minutes a week with automation like this . . .
Series: Information Technology: Managed Service Provider Flows (3 articles)
- 3Hastening AWS Org Sign-ins This article
AWS Whitepapers say "Businesses that are starting to adopt Amazon Web Services (AWS), expanding their footprint on AWS, or planning to enhance an established AWS environment need to ensure they have a foundation on AWS for their cloud environment. One important aspect of their foundation is organizing their AWS environment following a multi-account strategy" Creating an AWS account means becoming a Systems Administrator in every sense of the words and their responsibilities. My experiences with technology and career say:
- the only things harder than keeping software running all the time
- is keeping hardware running all the time
- which is somewhat more plausible than keeping people running all the time
Everything fails all the time. As such, I adhere to the practice of a new AWS Organization for every new project. In a world where I'm collaborating with LLMs from sun-up to bedtime 7 days a week , this means logging into multiple AWS Organizations 3 times per day taking conservatively 90 seconds of my attention each time. The technique in this article cuts it down to 45 seconds. I wouldn't use this for a customer or partner account, if I'm accountable with someone's baby I'm not going to bemoan 45 seconds. But for use cases like a Domains (Amazon Route53) & S3 Vector Storage & Hosting Video Calls, this is a walkthrough of how I save time

AWS Organizations, IAM Identity Center, and SSO
AWS Organizations is the core account management and governance service managing multiple AWS accounts under one governance umbrella. One Organization might hold a production account, a dev account, and a sandbox — or entirely separate Organizations might exist for separate concerns (AI work vs. community infrastructure vs. video hosting in my flow I show here).
IAM Identity Center (you may know it by its former name AWS SSO) manages human access to those accounts. Each Organization has its own Identity Center instance with its own Start URL — an address looking like
https://d-xxxxxxxx.awsapps.com/start
Identity Center handles user directories, permission sets (which accounts a user can access and with what role), and session tokens (temporary credentials that expire after a set period)This is not to be confused with IAM Policies. IAM policies come in handy in terms of setting policies that your software and systems can use, such as policies that allow deployment of new static websites to s3 via a Continuous Deployment pipeline, or for an Internet of Things sensor
SSO (Single Sign-On) is the authentication protocol. Running
aws sso login --profile my-profile triggers device authorization grant (OAuth 2.0 RFC 8628). The AWS Command Line Interface tool (used via GNOME Linux operating system Ubuntu in my case) generates a short code, prints a URL, and waits. Once that code is approved in a browser, the CLI receives temporary credentials. No password ever touches the terminalThe browser and the CLI do not need to be on the same machine. In my case, I have my development sandboxes, pools of firecracker functions, sandboxed mcp servers, graphics tools, local image and language models on a "bare metal" linux server with 12.5 GB graphics memory & 128 AMD CPU cores. I keep the strain on that machine without a display. Following encrypted network protocol Secure Shell (SSH) I connect via mac-mini's terminal, via macbook air, or Pixel10 on my local wifi (over Eero Routers)
The
device-code flag on aws sso login flow unlocks cross-machine automation while allowing separation of "where the code & Machine Learning workloads run" from "where the human is pretending to work"

device-code flow
Running
aws sso login triggers a network-communicated handshake. The AWS CLI contacts the Identity Center token endpoint and receives a short-lived user code (like RQVN-JDPG ) and a verification URL. In my terminal is printed both as polls to the token endpoint every few seconds are waiting to trigger the next event in the chain when I confirm on my browser. To allow me to keep sipping cider, a browser anywhere opens the URL, the code gets entered and approved, and Identity Center issues tokens back to the CLI. Authenticated.Because aws sso login prints the device code and verification URL as plain text to stdout, the human operator doesn't need to log in from the exact environment where the credentials will be used. The verification code and URL sit as plaintext in stdout. If automation fails or I clog my clipboard doing something else, I can copy & paste from terminal to browser. Anything that can read stdout can forward them somewhere else, like the macOS clipboard utility

A Perl script ties the flow together. It runs on the headless workstation, iterates through all configured SSO profiles, and for each one: spawns aws sso login, reads stdout in real-time looking for the device code and URL, copies the code to the browser machine's clipboard over SSH (a secure remote connection), opens the verification URL in its browser over SSH, and waits for the CLI to report success before moving to the next profile.
The result: type sso, move to the browser machine, paste-and-approve three times. Each approval takes about 5 seconds of human interaction. Total time: under 90 seconds for all three Organizations. The script prints the expected Identity Center host with each code — confirm the browser address bar shows it before approving. That glance replaces the code comparison the automation skips — the same match check protocol used when the code arrives pre-filled on my mac clipboard ( RFC 8628 §3.3.1 ):
#!/usr/bin/env perl# aws-sso-login-all.pl — unified AWS SSO login for headless workstations# Opens each device-code auth URL on a remote browser with the code# pre-loaded in the remote clipboard.# shapes allowlist, per-profile host pin, quoted forwarding,# non-interactive ssh, stripped echo, login timeouts, cache-dir repair,# clipboard wipe on success.use strict;use warnings;use IO::Select;use IPC::Open3;use Symbol 'gensym';
my @aws_sso_profile_names = ( 'video-infrastructure', 'community-websites', 'ai-ml-workloads',);
# Which machine opens the browser: override without editing the file with# export SSO_BROWSER_SSH_ALIAS=your-host (any host in ~/.ssh/config)my $browser_machine_ssh_alias = $ENV{SSO_BROWSER_SSH_ALIAS} // 'browser-machine';my $per_profile_login_timeout_seconds = 600; # then kill and move on
my @noninteractive_ssh_options = ('-o', 'BatchMode=yes', '-o', 'ForwardAgent=no');
# Fail-closed allowlist for device-code URLs. The capture regex below# admits any non-space token, and remote sshd runs the ssh command# string through a shell, so nothing reaches ssh until it matches the# expected Identity Center shape. Anything else is dropped with a warning.sub is_allowed_identity_center_device_url { my ($candidate_device_url) = @_; return 0 unless defined $candidate_device_url; # path/query limited to characters with no shell meaning, so a # captured token can never smuggle ; & $ ` ' " \ | ( ) < > ! * behind # the remote shell that sshd runs the ssh command string through. return $candidate_device_url =~ m{\Ahttps://[a-z0-9-]+\.awsapps\.com/start/[A-Za-z0-9\-._~:/?#@%=]*\z} ? 1 : 0;}
# Expected host for a profile, resolved from ~/.aws/config — either a# legacy sso_start_url in the profile section or a modern sso_session# reference. No directory IDs live here — the config is the map.sub resolve_expected_identity_center_host { my ($aws_profile_name) = @_; open(my $config_file_handle, '<', "$ENV{HOME}/.aws/config") or return undef; my (%parsed_config_sections, $current_section_name); while (my $config_line = <$config_file_handle>) { if ($config_line =~ /^\s*\[\s*profile\s+(\S+?)\s*\]\s*$/) { $current_section_name = "profile:$1"; } elsif ($config_line =~ /^\s*\[\s*sso-session\s+(\S+?)\s*\]\s*$/) { $current_section_name = "session:$1"; } elsif ($config_line =~ /^\s*\[/) { $current_section_name = undef; } elsif (defined $current_section_name && $config_line =~ /^\s*(sso_start_url|sso_session)\s*=\s*(\S+)\s*$/) { $parsed_config_sections{$current_section_name}{$1} = $2; } } close($config_file_handle); my $profile_config_section = $parsed_config_sections{"profile:$aws_profile_name"} or return undef; my $profile_start_url = $profile_config_section->{sso_start_url}; if (!defined $profile_start_url && defined $profile_config_section->{sso_session}) { my $referenced_sso_session = $parsed_config_sections{"session:$profile_config_section->{sso_session}"}; $profile_start_url = $referenced_sso_session->{sso_start_url} if $referenced_sso_session; } return undef unless defined $profile_start_url; return $1 if $profile_start_url =~ m{\Ahttps://([a-z0-9-]+\.awsapps\.com)/start}; return undef;}
sub extract_identity_center_host_from_url { my ($device_verification_url) = @_; return undef unless defined $device_verification_url; return $1 if $device_verification_url =~ m{\Ahttps://([a-z0-9-]+\.awsapps\.com)/start/}; return undef;}
# Strip terminal escapes before echo, so unexpected bytes in captured# output cannot repaint the terminal or hide REFUSED lines.sub strip_terminal_escape_sequences { my ($raw_output_text) = @_; $raw_output_text =~ s/\e\[[0-9;?]*[A-Za-z]//g; $raw_output_text =~ s/\e[()][0-9A-Z]//g; return $raw_output_text;}
sub open_device_url_on_browser_machine { my ($device_verification_url, $device_authorization_code) = @_; unless (is_allowed_identity_center_device_url($device_verification_url)) { warn " REFUSED: device URL failed allowlist, not opening\n"; return; } # copy code to remote machine's clipboard over SSH # (list-form open: no local shell interprets the code) if (open(my $clipboard_ssh_pipe, "|-", "ssh", @noninteractive_ssh_options, $browser_machine_ssh_alias, "pbcopy")) { print $clipboard_ssh_pipe $device_authorization_code; close($clipboard_ssh_pipe); } # single-quoted: the allowlist excludes quotes, so the remote shell # receives exactly one literal argument — no glob, no option parsing. my $shell_quoted_device_url = "'$device_verification_url'"; system("ssh", @noninteractive_ssh_options, $browser_machine_ssh_alias, "open -- $shell_quoted_device_url") == 0 or warn " open URL failed\n";}
sub authenticate_single_aws_sso_profile { my ($aws_profile_name) = @_; # Host pin: the captured URL must live on the host this profile # already names in ~/.aws/config. Anything else is refused. my $expected_identity_center_host = resolve_expected_identity_center_host($aws_profile_name); unless (defined $expected_identity_center_host) { warn " REFUSED: no sso_start_url for profile ${aws_profile_name}\n"; return 0; } my $stderr_capture_handle = gensym; my $aws_cli_process_id = open3(my $cli_stdin_handle, my $cli_stdout_handle, $stderr_capture_handle, "aws", "sso", "login", "--profile", $aws_profile_name, "--use-device-code" # headless: force RFC 8628, never try a local browser ) or die "Failed to spawn: $!\n"; close($cli_stdin_handle);
my $cli_output_selector = IO::Select->new($cli_stdout_handle, $stderr_capture_handle); my ($device_verification_url, $device_authorization_code, $credentials_forwarded_to_browser, $captured_cli_output, $login_timed_out) = (undef, undef, 0, '', 0);
eval { local $SIG{ALRM} = sub { die "TIMEOUT\n" }; alarm $per_profile_login_timeout_seconds; while (my @readable_handles = $cli_output_selector->can_read(120)) { for my $ready_output_handle (@readable_handles) { my $bytes_read = sysread($ready_output_handle, my $output_chunk, 4096); if (!$bytes_read) { $cli_output_selector->remove($ready_output_handle); next; } $output_chunk = strip_terminal_escape_sequences($output_chunk); $captured_cli_output .= $output_chunk; print $output_chunk;
# capture the device URL if ($captured_cli_output =~ m{(https://\S+/start/\S*device\S*)}) { $device_verification_url = $1 unless $device_verification_url; } # capture the device code (XXXX-XXXX) if ($captured_cli_output =~ m/\b([A-Z]{4}-[A-Z]{4})\b/) { $device_authorization_code = $1 unless $device_authorization_code; } # Once both halves are captured, fire them to the browser # machine. Two checks, in order: the shape allowlist # first, then the host pin. Either check can stop the login. if (!$credentials_forwarded_to_browser && $device_authorization_code && $device_verification_url) { unless (is_allowed_identity_center_device_url($device_verification_url)) { warn " REFUSED: captured URL failed allowlist\n"; $device_verification_url = undef; next; } my $captured_url_host = extract_identity_center_host_from_url($device_verification_url); unless (defined $captured_url_host && $captured_url_host eq $expected_identity_center_host) { warn " REFUSED: URL host does not match profile\n"; $device_verification_url = undef; next; } open_device_url_on_browser_machine($device_verification_url, $device_authorization_code); warn " Before approving, confirm the browser address bar shows $expected_identity_center_host\n"; $credentials_forwarded_to_browser = 1; } } last if $cli_output_selector->count == 0; } alarm 0; }; if ($@ && $@ eq "TIMEOUT\n") { $login_timed_out = 1; kill 'TERM', $aws_cli_process_id; } waitpid($aws_cli_process_id, 0); return 0 if $login_timed_out; return ($? >> 8) == 0;}
# --- main ---my $authenticated_profile_count = 0;for my $aws_profile_name (@aws_sso_profile_names) { $authenticated_profile_count++ if authenticate_single_aws_sso_profile($aws_profile_name);}# Wipe on every outcome — a partial run must not leave a code behind.wipe_browser_machine_clipboard();print "Result: $authenticated_profile_count/" . scalar(@aws_sso_profile_names) . " profiles authenticated.\n";The core technique: IPC::Open3 spawns the AWS CLI as a subprocess, and IO::Select reads its output without blocking — character by character as it arrives. The browser opens the moment the code and URL appear, before the CLI finishes printing. By the time the browser tab loads, the code is already in the clipboard
The captured URL passes two checks before it reaches ssh: the shape allowlist, then a host pin against that profile's own Start URL host. No directory IDs live in the script — ~/.aws/config is the map, legacy or sso_session style
The URL crosses to the browser machine single-quoted, so the remote shell gets one literal argument. Terminal output is stripped before it prints. Each login carries a timeout. The clipboard is wiped once every profile lands. Cache-directory repair, tab-closing, and a --self-test mode are in the version I use

demo: multi-org sso in action
$ sso
[12:33:39] AWS SSO Login — headless workstation → browser machine[12:33:39] ────────────────────────────────────────────────────────────[12:33:39] Starting: video-infrastructure[12:33:40] → Code: RQVN-JDPG (copied to clipboard)[12:33:40] → URL opened on browser machine. Paste code and click Submit.Successfully logged into Start URL: https://d-xxxxxxxx.awsapps.com/start[12:34:01] ✓ video-infrastructure: success
[12:34:01] Starting: community-websites[12:34:02] → Code: WDFV-RZJS (copied to clipboard)[12:34:02] → URL opened on browser machine. Paste code and click Submit.Successfully logged into Start URL: https://d-yyyyyyyy.awsapps.com/start[12:34:21] ✓ community-websites: success
[12:34:21] Starting: ai-ml-workloads[12:34:22] → Code: XMGC-FDZQ (copied to clipboard)[12:34:22] → URL opened on browser machine. Paste code and click Submit.Successfully logged into Start URL: https://d-zzzzzzzz.awsapps.com/start[12:34:44] ✓ ai-ml-workloads: success
[12:34:44] ────────────────────────────────────────────────────────────[12:34:44] Result: 3/3 profiles authenticated.adapting per Operating System or use case
The script assumes SSH key-based authentication to a machine with a browser, which is a topic for another post. Changing the target machine means pointing
$browser_machine_ssh_alias at any host defined in ~/.ssh/config — edit the variable, or export SSO_BROWSER_SSH_ALIAS and leave the file alone. Only two remote commands are OS-specific — opening a URL and writing the clipboard. macOS uses open and pbcopy ; Linux with a desktop uses xdg-open and xclip (or xsel ); Microsoft Windows over SSH uses cmd /c start and clip . The pattern is the same regardless of operating system on either endAdding profiles means adding entries to the
@aws_sso_profile_names array. Each must be a named profile in ~/.aws/config with sso_start_url , sso_region , sso_account_id , and sso_role_name configured. I run an automated script perl aws-sso-login-all.pl --self-test after any edit —exercising the checks offline with no ssh and no AWS calls
AWS Kiro-CLI connection
The AI interaction tool from AWS — authenticates through the same IAM Identity Center infrastructure. Same device-code flow flag, same Start URL we use to authenticate AWS, same browser approval process
kiro-cli login --use-device-flow triggers a familiar same handshake:$ kiro-cli login --use-device-flow✓ Select login method · Use with Your Organization✓ Enter Start URL · https://d-xxxxxxxx.awsapps.com/start✓ Enter Region · us-east-2
Confirm the following code in the browserCode: FHKQ-KCZJOpen this URL: https://d-xxxxxxxx.awsapps.com/start/#/device?user_code=FHKQ-KCZJLogging in...--use-device-flow flag forces RFC 8628 instead of attempting to open a local browser — necessary on headless machines. This logs you into a kiro subscription - it is unrelated to giving your kiro-cli agents access to your aws environments which we'll tackle with AWS MCP
AWS Kiro semantic memory via S3 Vectors and MCP
Kiro's agents generate code. But code generation is more useful when the agent remembers project context across sessions — architectural decisions, deployment patterns, what broke last time. Making that work takes four components wired together
S3 Vectors — AWS service. Text goes in as 3072-dimensional vector embedding; the text becomes searchable by meaning. Ask "how was the last deployment structured" and get back stored context that semantically matches, ranked by cosine similarity. The storage backend is an S3 bucket with a vector index
MCP (Model Context Protocol) — Standard interface for connecting AI agents to external tools. An MCP server is a process that exposes operations (like "search" and "store") over a defined protocol. The agent speaks MCP; the server translates those calls into API calls against the underlying service
A bridge — Process that translates between transport formats. Kiro speaks stdio (reads stdin, writes stdout). The S3 Vectors MCP server speaks HTTP. The bridge connects the two using an open-source adapter called
supergateway A launcher — Shell script (
run.sh ) that resolves and executes bridge scripts by name, so the Kiro config never needs to know where bridge scripts live on disk. From remote machines, the launcher SSHes to the workstation to run the bridge there (where the server and AWS credentials live)
aws sso login --profile ai-ml-workloads → temporary credentials cached at ~/.aws/sso/cache/ → boto3 Session(profile_name="ai-ml-workloads") resolves cached creds → S3 Vectors API (put_vectors, query_vectors) authenticates → Bedrock API (invoke_model for embeddings) authenticates → MCP server exposes find/store tools over HTTP → supergateway bridge translates HTTP ↔ stdio → Kiro agent calls find/store via stdio pipeA standard
~/.aws/config entry for an SSO-authenticated must be logged in before starting the MCP server:[profile ai-ml-workloads]sso_start_url = https://d-xxxxxxxx.awsapps.com/startsso_region = us-east-2sso_account_id = 123456789012sso_role_name = S3VectorsWorkloadAccessregion = us-west-2output = jsonField | Purpose |
|---|---|
sso_start_url | Identity Center instance URL — same one used for browser approval |
sso_region | Region where the Identity Center instance lives |
sso_account_id | AWS account the role belongs to |
sso_role_name | Permission set name (what access the temporary creds grant) |
region | Default region for API calls (S3 Vectors + Bedrock land here) |
The role here is a permission set scoped to what this server actually calls (Bedrock
invoke_model , S3 Vectors reads and writes) — AdministratorAccess also works, but should not be the driver behind the wheelaws sso login --profile ai-ml-workloadsThis caches temporary credentials at
~/.aws/sso/cache/ . Every AWS pythonic Software Development Kit boto3 session using this profile resolves credentials from that cache — no long-lived keys, no passwords on disk. Credentials live as long as the permission-set session allows ( 12 hours max ); when they die, the server needs a fresh login and a restartCached files are plaintext JSON. That is how the AWS CLI works, not a choice this setup makes: any process running as your user can read them and reuse the temporary keys until they expire
One failure to learn from: the cache used to be a symlink into tmpfs, which does not survive a reboot. After one, the link dangled and every login died with
File exists before any code was issued. The login script needs to repair that at startup — a dangling link is replaced with a directory before any profile runs2 things that do not fix this: encrypting the file itself (the CLI rewrites plaintext JSON there on every refresh), and transparent per-file crypto (fscrypt, eCryptfs), which is invisible to same-uid processes. Full-disk encryption only covers a powered-off stolen disk — general hygiene, not mitigation
Mitigation efforts include short session durations,
aws sso logout when done, and never copying the cache off the workstation. The cache directory itself is mode 0700 and holds only the plaintext JSON described aboveNone of our measures stops a same-uid process attack on one of my devices — accepted risk by me inside this trust boundary for convenience and time. Containers read the same tokens through a read-only mount (see below), so they can never rewrite the host cache

S3 Vectors MCP server
A Python process (port 8180) exposes two MCP tools behind a bearer-token gate:
-
find(query)— embed the query text, search the vector index by cosine similarity, return ranked matches
-
store(information, metadata)— embed the text, store the vector + payload in S3 Vectors
Every call makes two AWS API calls: one to Bedrock (
invoke_model with Nova 2 multimodal embeddings for the embedding) and one to S3 Vectors ( put_vectors or query_vectors for storage/retrieval). The server, abridged (the live file adds metadata budgeting; same tools, same transport):"""S3 Vectors MCP ServerTransport: streamable-http on port 8180Embedding: amazon.nova-2-multimodal-embeddings-v1:0 (3072-dim float32)Storage: s3vectors bucket, cosine index, 3072 dimensions"""
import jsonimport osimport uuidfrom datetime import datetime, timezone
import boto3from mcp.server.fastmcp import FastMCP
REGION = os.environ.get("AWS_REGION", "us-west-2")PROFILE = os.environ.get("AWS_PROFILE", "ai-ml-workloads")VECTORS_BUCKET = os.environ.get("S3V_BUCKET", "my-vectors-bucket")VECTORS_INDEX = os.environ.get("S3V_INDEX", "my-knowledge-index")EMBED_MODEL_ID = "amazon.nova-2-multimodal-embeddings-v1:0"EMBED_DIMENSION = 3072TOP_K = int(os.environ.get("S3V_TOP_K", "5"))# authenticated localhost port: every /mcp/ request must carry the bearer# token in S3V_MCP_AUTH_TOKEN (the server refuses to start without it).# (the length check below also skips a wasted Bedrock call on absurd input.)MAX_INFORMATION_CHARS = int(os.environ.get("S3V_MAX_CHARS", "20000"))
def _session(): """Create a boto3 session using the configured SSO profile. boto3 resolves credentials from ~/.aws/sso/cache/ automatically.""" return boto3.Session(region_name=REGION, profile_name=PROFILE)
def _bedrock_client(): return _session().client("bedrock-runtime", region_name=REGION)
def _s3vectors_client(): return _session().client("s3vectors", region_name=REGION)
def embed_text(text: str) -> list[float]: """Embed text via Nova 2 multimodal embeddings. Returns 3072-dim float32 vector.""" client = _bedrock_client() body = json.dumps({"inputText": text}) response = client.invoke_model( modelId=EMBED_MODEL_ID, contentType="application/json", accept="application/json", body=body, ) result = json.loads(response["body"].read()) return result["embedding"]
def store_vector(key: str, vector: list[float], data: dict) -> None: """Store a vector with payload in S3 Vectors.""" client = _s3vectors_client() client.put_vectors( vectorBucketName=VECTORS_BUCKET, indexName=VECTORS_INDEX, vectors=[{"key": key, "data": {"float32": vector}, "metadata": data}], )
def query_vectors(vector: list[float], top_k: int = TOP_K) -> list[dict]: """Query S3 Vectors by embedding similarity.""" client = _s3vectors_client() response = client.query_vectors( vectorBucketName=VECTORS_BUCKET, indexName=VECTORS_INDEX, queryVector={"float32": vector}, topK=top_k, returnMetadata=True, ) return response.get("vectors", [])
# --- MCP server definition ---
mcp = FastMCP( "s3vectors", stateless_http=True, # critical — see "Stateless mode" in operational lessons instructions="S3 Vectors knowledge store. Use 'find' to search and 'store' to persist.",)
@mcp.tool()def find(query: str) -> str: """Search stored knowledge by semantic similarity.""" vector = embed_text(query) results = query_vectors(vector) if not results: return "No matching results found." output_lines = [] for i, hit in enumerate(results, 1): metadata = hit.get("metadata", {}) information = metadata.get("information", "(no text)") source = metadata.get("source", "unknown") score = hit.get("distance", None) entry = f"[{i}] {information}" if score is not None: entry += f"\n score={score:.4f} source={source}" output_lines.append(entry) return "\n\n".join(output_lines)
def check_information_length(information: str) -> str | None: """Refuse absurdly large payloads before any AWS call.""" if len(information) > MAX_INFORMATION_CHARS: return f"Refused: {len(information)} chars exceeds {MAX_INFORMATION_CHARS}." return None
@mcp.tool()def store(information: str, metadata: dict | None = None) -> str: """Store new knowledge with semantic embedding.""" refusal = check_information_length(information) if refusal is not None: return refusal vector = embed_text(information) key = str(uuid.uuid4()) now = datetime.now(timezone.utc).isoformat() payload = {"information": information, "source": "kiro-agent", "timestamp": now} if metadata: for k, v in metadata.items(): if k not in ("information", "source", "timestamp"): payload[k] = str(v) if not isinstance(v, str) else v store_vector(key, vector, payload) return f"Stored. key={key} ts={now}"
if __name__ == "__main__": import uvicorn port = int(os.environ.get("S3V_PORT", "8180")) # live source wraps the app in a bearer-token gate (fail-closed when # S3V_MCP_AUTH_TOKEN is unset) — abridged out here. Health GET / open. app = mcp.streamable_http_app() # localhost only: the bridge runs on this same host, so the server # must never bind all interfaces. Remote access goes over SSH, # never direct to this port (see trust boundary below). uvicorn.run(app, host="127.0.0.1", port=port)Dependencies ( requirements.txt ):
boto3>=1.43.0mcp==1.9.2uvicorn==0.34.0Start the server with the desired profile:
AWS_PROFILE=ai-ml-workloads python server.py# listening on http://127.0.0.1:8180Off-host access is an SSH tunnel (
ssh -L 8180:127.0.0.1:8180 user@workstation.local ), never a direct connection to this port. The server gates every /mcp/ request on a bearer token shared via ~/mcp-launchers/.env ; localhost binding plus the host firewall is the second layer. The AWS_PROFILE environment variable is the link between SSO credentials and the server. boto3 reads the named profile from ~/.aws/config , finds the SSO configuration, resolves temporary credentials from ~/.aws/sso/cache/ , and authenticates every API call. No keys in environment variables. No credentials on disk beyond the cached SSO tokensBridge Script
AWS Kiro communicates with MCP servers via stdio (standard input/output streams). The S3 Vectors server speaks HTTP on port 8180. Something must translate between the two. That translator is
supergateway — an open-source Node.js tool that connects an HTTP MCP endpoint to a stdio pipe. The bridge script ( s3vectors-bridge.sh ) wraps supergateway with a health check:#!/usr/bin/env bash# s3vectors-bridge.sh — stdio-to-HTTP bridge for the S3 Vectors MCP server## What this does:# 1. Waits up to 30 seconds for the HTTP server to respond# 2. Launches supergateway, which connects to http://localhost:8180/mcp/# 3. supergateway translates: stdin from kiro → HTTP POST to server# HTTP response from server → stdout to kiro## The `exec` replaces this shell process with supergateway directly.# Kiro's stdio pipe connects to supergateway with no intermediate process.
set -euo pipefail
# Auth: the server gates every /mcp/ request on a bearer token kept in# ~/mcp-launchers/.env (mode 600). Refuse to run without it.if [ -f "$HOME/mcp-launchers/.env" ]; then . "$HOME/mcp-launchers/.env"fi[ -n "${S3V_MCP_AUTH_TOKEN:-}" ] || { echo "s3vectors-bridge: token not set" >&2; exit 1; }
S3VECTORS_URL="http://localhost:8180/mcp/"
# Health probe: hit / (returns 404 = alive).# Do NOT probe /mcp/ — that endpoint allocates session state as a side effect.S3VECTORS_HEALTH="http://localhost:8180/"attempts=0while ! curl -s -o /dev/null --max-time 2 "$S3VECTORS_HEALTH" 2>/dev/null; do attempts=$((attempts + 1)) if [ $attempts -ge 20 ]; then echo "s3vectors-bridge: server not reachable after 30s" >&2 exit 1 fi sleep 1.5done
exec supergateway --streamableHttp "$S3VECTORS_URL" --oauth2Bearer "$S3V_MCP_AUTH_TOKEN"Install supergateway pinned —
npm install -g supergateway@3.4.3 , the version this setup runs. A floating global install drifts over time; a pinned one does not. Reinstalling the pinned version changes nothing running and proves the pin resolves. Node.js is the JavaScript runtime supergateway executes on — v18+ is its minimum version (modern fetch and web-stream support). npm is Node's package manager; -g installs the supergateway binary onto PATH so the bridge script can exec it by name. supergateway itself is a transport adapter: it sits on Kiro's stdio pipe, translates each MCP message into an HTTP POST against /mcp/ , and streams the response back to stdout. One process, no config file. The bridge script above is just health-check plus exec — supergateway does the actual protocol work- Python, same direction (stdio-facing client → remote HTTP):
mcp-stdio-proxy(pip install mcp-stdio-proxy, nuwax-ai/mcp-proxy ) converts remote SSE/Streamable HTTP endpoints into a local stdio pipe — the direct analog of thesupergateway --streamableHttpline above.
- Python, opposite direction (local stdio server → SSE endpoint): sparfenyuk/mcp-proxy (
pipx install mcp-proxy). Useful if you invert the topology (serve local tools outward), not as a drop-in here. Two cautions:npx mcp-proxyresolves to an unrelated npm package — it must be pip/pipx-installed — and version pins against themcpSDK have bitten before, so pin and test.
- Rust: vinhjaxt/mcp-proxy is a single static binary bridging local stdio to SSE/Streamable HTTP — again the server direction, same caveat as sparfenyuk. No client-mode Rust single binary is verified here; a small bridge on the official Rust MCP SDK is the build you'd have to write yourself if you want Rust in this slot.
- No bridge at all: if the agent speaks HTTP natively, skip the adapter — Claude Code's
type: httpserver entry points straight at the URL. Or run the MCP server over stdio directly (tradeoffs in "Why not direct stdio" above).
Launcher Dispatcher
A central
run.sh script finds and executes bridge scripts by filename, so the Kiro config never needs to know where bridge scripts live on disk, we use deterministic software rather than wasting context#!/bin/bash# run.sh — MCP launcher dispatcher# Given a script name (e.g. "s3vectors-bridge.sh"), finds it in the launchers# directory tree and executes it.
set -euo pipefail
LAUNCHERS_ROOT="/path/to/mcp-launchers"SCRIPT_NAME="$(basename "${1:-}")"
if [ -z "$SCRIPT_NAME" ]; then echo "Usage: run.sh <script-name>.sh" >&2 exit 1fi
# allow-map: only these bridge names ever execute. A name not on# the list — typo or otherwise — is refused before ssh is attempted.# Add names here as new bridges are adopted.case "$SCRIPT_NAME" in s3vectors-bridge.sh) ;; *) echo "Error: launcher '$SCRIPT_NAME' not allowed" >&2; exit 1 ;;esac
SCRIPT_PATH="$LAUNCHERS_ROOT/$SCRIPT_NAME"if [ ! -f "$SCRIPT_PATH" ]; then echo "Error: launcher '$SCRIPT_NAME' not found in $LAUNCHERS_ROOT" >&2 exit 1fi
CURRENT_HOST="$(hostname 2>/dev/null || true)"if [ "$CURRENT_HOST" = "my-workstation" ]; then # local execution — server and credentials are here exec "$SCRIPT_PATH"else # remote execution — SSH to the workstation where the server runs. # the path is single-quoted: the allow-map above excludes quotes, # so the remote shell receives one literal argument. exec ssh -o BatchMode=yes -o ForwardAgent=no user@workstation.local \ "export PATH=\$HOME/.local/bin:\$PATH && '$SCRIPT_PATH'"fiWhere the MCP server runs,
run.sh executes the bridge script directly. From a laptop or any other machine, run.sh SSHes to the workstation and runs the bridge script there. SSH hygiene for this launcher is a dedicated ed25519 key for the workstation hop (not your GitHub or deploy key), BatchMode=yes so a stolen key can never fall back to password prompts, ForwardAgent no , and a private tailnet or LAN address rather than a public one. The dispatcher still keeps a full shell — a compromised caller owns the workstation shell and the token cache, as the trust-boundary section states. The allow-map above narrows what it can be talked into running; a per-command command="..." restriction in ~/.ssh/authorized_keys narrows it furthermcp.json entry
~/.kiro/settings/mcp.json tells Kiro how to reach each MCP server. When Kiro starts a session, it spawns each configured command as a child process and communicates via the resulting stdio pipe. s3vectors entry:{ "mcpServers": { "s3vectors": { "command": "bash", "args": ["-c", "/absolute/path/to/run.sh s3vectors-bridge.sh"] } }}Field | Meaning |
|---|---|
"command": "bash" | Kiro spawns a bash process |
"args": ["-c", "..."] | bash executes the given command string |
/absolute/path/to/run.sh | The launcher dispatcher (must be an absolute path — see operational lessons) |
s3vectors-bridge.sh | The bridge script name that run.sh will find and execute |
on session start: Kiro spawns bash → bash runs
run.sh s3vectors-bridge.sh → run.sh finds the bridge script → bridge waits for the server → bridge exec s supergateway → supergateway connects to http://localhost:8180/mcp/ → Kiro's stdio pipe is live. The find and store tools appear in the agent's available toolsetCredential Resolution Path
┌─────────────────────────────────────────────────────────────┐│ aws sso login --profile ai-ml-workloads ││ → browser approval → tokens cached at ~/.aws/sso/cache/ │└─────────────────────────────────────────────────────────────┘ ↓┌─────────────────────────────────────────────────────────────┐│ AWS_PROFILE=ai-ml-workloads python server.py ││ → boto3.Session(profile_name="ai-ml-workloads") ││ → reads ~/.aws/config for sso_* fields ││ → resolves temp creds from ~/.aws/sso/cache/ │└─────────────────────────────────────────────────────────────┘ ↓┌─────────────────────────────────────────────────────────────┐│ Every API call (put_vectors, query_vectors, invoke_model) ││ → uses the resolved temporary credentials ││ → credentials expire with the permission-set session ││ → on expiry: re-run aws sso login, restart server │└─────────────────────────────────────────────────────────────┘3 SSO profiles logged in simultaneously (AI workloads, video infrastructure, community websites), each MCP server is pinned to one profile at startup, plus Kiro CLI for AI-assisted development

Series: Information Technology: Managed Service Provider Flows (3 articles)
- 3Hastening AWS Org Sign-ins This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article