# Sample Code for Amazon WorkSpaces Applications with agent access Build autonomous agents that automate desktop workflows on [Amazon WorkSpaces Applications with agent access](https://docs.aws.amazon.com/appstream2/latest/developerguide/agent-access.html). Agents interact with any combination of applications — filling forms, transferring data between apps, navigating multi-step processes — using the Strands Agents SDK and Claude with screenshot, mouse and keyboard tools. Amazon WorkSpaces Applications enables agents to connect to streaming sessions and interact with desktop applications through [a managed Model Context Protocol (MCP) service](https://docs.aws.amazon.com/appstream2/latest/developerguide/agent-access-mcp-server.html). ## Prerequisites The Quick Start helps you get setup with: - **AWS account** with permission to create Amazon WorkSpaces Applications fleets/stacks and invoke Amazon Bedrock - **AWS CLI v2** — [install guide](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) - **Python 3.10+** — [install guide](https://www.python.org/downloads/) - **Valid AWS credentials** configured (run `aws sts get-caller-identity` to verify) - **bash** on Windows — the deploy step runs via [Git for Windows](https://git-scm.com/download/win) (`winget install -e --id Git.Git`) or WSL (`wsl --install`) > **Note:** Creating a fleet requires the `AmazonAppStreamServiceAccess` service role in your account. WorkSpaces Applications creates it for you when you choose **Get started** in the [WorkSpaces Applications console](https://console.aws.amazon.com/appstream2/home). To check whether your account already has it, or to create it yourself, see [Checking for the AmazonAppStreamServiceAccess service role](https://docs.aws.amazon.com/appstream2/latest/developerguide/controlling-access-checking-for-iam-service-access.html). ## Quick Start Clone the repo and run the setup script from the repository root. Agents log their output and store screenshots in the relative agent folders (`agents/generic_cua/screenshots` and `agents/generic_cua/logs`). ### macOS / Linux ```bash git clone https://github.com/aws-samples/sample-code-for-workspaces-agent-access.git cd sample-code-for-workspaces-agent-access ./scripts/setup.sh ``` ### Windows (PowerShell) ```powershell git clone https://github.com/aws-samples/sample-code-for-workspaces-agent-access.git cd sample-code-for-workspaces-agent-access powershell -ExecutionPolicy Bypass -File scripts\setup.ps1 ``` `setup.sh` / `setup.ps1` installs dependencies, deploys WorkSpaces resources (VPC, Fleet, Stack with AgentAccessConfig), waits for the fleet to reach RUNNING state, generates a streaming URL, and runs the demo agent. ### Run agents again after setup Use the helper to mint a fresh streaming URL (default validity: 1 hour): ```bash source venv/bin/activate STREAMING_URL=$(scripts/streaming_url.sh) python3 agents/application_validation/agent.py --streaming-url "$STREAMING_URL" ``` ## Demo Agents ```bash source venv/bin/activate # App validation — tests desktop applications python3 agents/application_validation/agent.py --streaming-url "$STREAMING_URL" # Interactive — REPL for arbitrary desktop tasks python3 agents/generic_cua/agent.py --streaming-url "$STREAMING_URL" # MCP tool forwarding — uses forwarded filesystem + fetch tools (requires a forwarding fleet) python3 agents/mcp_forwarding_demo/agent.py --streaming-url "$STREAMING_URL" ``` ### Replay Session Replay Session records what an agent does on a stack and, after the session ends, delivers a video, a transcript, and a report to your own S3 bucket for review. It works with any agent: the agent needs no changes to be recorded. 1. Turn it on for the stack that `setup.sh` deploys. The script creates a private recordings bucket (re-applying its settings on a re-run), or reuses the one in the stack's `S3BucketArn` (which screenshot uploads also use), and sets `ReplaySessionEnabled`. When the stack is updated, WorkSpaces Applications checks that it can list the bucket, so the script's bucket policy allows `s3:ListBucket` for `appstream.amazonaws.com` from your account; a bucket you pass with `--bucket` needs the same statement. Pass `--kms` to also create a customer managed key for the captured frames; on a re-run the key is reused and its policy is replaced. ```bash ./scripts/setup_replay_session.sh --region us-east-1 ``` 2. Run the agent with `--save-replay`. Before the task starts, it checks that it can read the stack's recordings bucket, and stops with the reason if it can't. When the task is done, or when you exit an interactive session, the agent ends its MCP session, which starts delivery, then waits for the recording (usually about a minute for a short session, up to 10 minutes), downloads it to `recordings//`, and prints the session summary and each recorded action. ```bash STREAMING_URL=$(scripts/streaming_url.sh) python3 agents/generic_cua/agent.py --streaming-url "$STREAMING_URL" --expire-session-on-exit --save-replay ``` The bucket is read from the `S3BucketArn` of the stack the streaming URL was created for, in that stack's Region, both read from the URL (or of the `--stack-arn` stack on a domain-joined fleet). If the agent used more than one MCP session (a retried connection, or new stateless sessions during the run), each session that ran a tool call is saved too, within the same 10-minute wait. Open `replay_session_report.html` in a browser to play the video alongside the transcript. 3. If the recording hasn't arrived when the agent gives up, or you press Ctrl-C while it waits, it prints a `scripts/get_replay_session.py` command; run it later. The script also fetches recordings of other agents' sessions by their MCP session ID (each run of this repo's agents prints `MCP server session: `, or `MCP session (stateless): ` over stateless MCP): ```bash python3 scripts/get_replay_session.py --session-id --region us-east-1 ``` It reads the bucket the same way (pass `--stack-name` or `--bucket` for another stack) and searches yesterday's and today's partitions, so pass `--session-date YYYY-MM-DD` (UTC) for an older session; that day and the day before are searched. The command the agent prints already has it. The recording is delivered under `agentaccess/replay-session/year=YYYY/month=MM/day=DD//`, where the date is the session's start date in UTC: | File | What it is | |---|---| | `replay_session_video.mp4` | Screen recording of the session, one frame per action | | `replay_session_transcript.json` | Each action (tool and arguments) with an AI-generated description of its intent, plus a session summary | | `replay_session_report.html` | Self-contained report that plays the video next to a searchable transcript | - **Your own agent:** if it isn't built on this repo's `lib/`, get the ID from the `mcpSessionId` field of the `get_session_info` tool. End the MCP session when the agent finishes (HTTP `DELETE` over stateful MCP, `close_session` over stateless), so delivery starts. - **Blocked actions:** capture is fail-closed. If a frame can't be recorded, the action doesn't run and the tool returns an error starting with `Replay Session enabled but action blocked`. Retrying won't help; when the message names a KMS error, fix the key policy of the stack's `KmsKeyArn`. Tell your agent to report the error and stop. - **Recordings contain everything on screen and everything the agent types.** Keep the bucket private, scope who can read `agentaccess/replay-session/`, and don't give the agent tasks that type secrets. - **Delivered files use the bucket's default encryption.** A `KmsKeyArn` on the stack protects the captured frames while they're processed; it isn't applied to the delivered files. To encrypt recordings with your own key, set SSE-KMS as the bucket's default encryption. - **A `replay_fallback_content/` folder** means processing failed; it holds the raw frames and per-action metadata instead of the video. Its files are uploaded in parallel with no marker for the last one, so the agent saves them once the listing stops changing; fetch them again later to be sure you have every file. - **No recording?** Check that the stack's `ReplaySessionEnabled` is `true` and that the session started after it was turned on; the setting applies to new sessions only. - **Permissions:** reading the recording needs `appstream:DescribeStacks` on the stack (unless you pass `--bucket`) and `s3:ListBucket` and `s3:GetObject` on the delivery prefix. ### MCP tool forwarding Fleets can expose additional tools beyond desktop interaction via MCP tool forwarding. When enabled, `tools/list` returns both desktop tools (`screenshot`, `left_click`, etc.) and forwarded tools (prefixed with `forwarded___`). These forwarded tools call external APIs or services configured on the fleet — your agent uses them like any other MCP tool. To set up a fleet with custom MCP servers (requires ~30 min for AMI build + import): ```bash ./scripts/setup_mcp_forwarding.sh --region us-east-1 ``` This builds a Windows Server 2025 image with Python + FastMCP and two example servers (`filesystem`, `fetch`), imports it to WorkSpaces, and creates a fleet with `FORWARD_MCP_TOOLS` enabled. See `mcp_servers/` for the server source code. > **Validate first:** before building a custom image, check that your MCP servers will forward correctly with the compatibility tester in [`utils/mcpforwardingtester/`](utils/mcpforwardingtester/). It catches the common failures (a server that lists no tools, a config saved with a BOM, or `env`/`cwd` keys that get silently ignored) before the ~30-minute image build. Once the forwarding fleet is running, `agents/mcp_forwarding_demo/` drives the forwarded tools end to end — it lists and reads seeded files, fetches a web page, writes a report file, and confirms the result on the desktop: ```bash STREAMING_URL=$(aws appstream create-streaming-url \ --stack-name MCPForwardingStack --fleet-name MCPForwarding \ --user-id test --validity 3600 \ --query StreamingURL --output text) python3 agents/mcp_forwarding_demo/agent.py --streaming-url "$STREAMING_URL" ``` ### Domain Join (AD-joined fleets) For fleets joined to an Active Directory domain, agents authenticate with a SAML assertion and the stack ARN instead of a streaming URL. Both are sent in the MCP `_meta` field of every request, and the request is SigV4-signed after they are added. Keep the assertion in a file only you can read: ```bash chmod 600 assertion.b64 python3 agents/generic_cua/agent.py \ --saml-assertion-file assertion.b64 \ --stack-arn "arn:aws:appstream:us-east-1:123456789012:stack/MyDJStack" ``` Prerequisites: - WorkSpaces Applications fleet joined to an AD domain with Certificate-Based Authentication (CBA) enabled - IAM SAML provider registered with your IdP certificate - IAM role trusting the SAML provider - Base64-encoded SAML assertion from your IdP (Okta, Entra ID, Ping, etc.), exactly as the IdP issued it - AWS credentials that sign the MCP requests (`--mcp-profile`, or your default credentials), expected to be from the account that owns the stack Things to know: - **Start the agent right after you get the assertion.** SAML assertions are short-lived (typically minutes) and the agent sends the same one with every request. A request that carries an expired assertion is refused (HTTP 400, `SAML assertion has expired`), and this sample re-sends the assertion it started with, so it stops working when that assertion expires (an idle REPL included). When the service refuses the assertion, while connecting or mid-run, the agent prints the service's message and stops instead of retrying. - `--streaming-url` is not used; the MCP server provisions a desktop session bound to the AD user identity in the assertion. The two are mutually exclusive. - The assertion is read from `--saml-assertion-file` (or, if that is not given, the `AGENTACCESS_SAML_ASSERTION` environment variable), never from the command line, where other local users could see it in the process list. It is not printed or logged. - Supported by `generic_cua`, `application_validation` and `mcp_forwarding_demo`. The other samples (`quickstart.py`, the AgentCore sample) take a streaming URL only. - A live domain-joined fleet accepted the `_meta` keys this sample sends (`aws.agentaccess/workspacesApplicationsSamlAssertion` and `aws.agentaccess/workspacesApplicationsStackArn`). The AWS developer guide's example uses other names (`saml_response` / `stack_arn`), which were not tried here. #### Without a SAML assertion (federated identity) The service can also sign in to the desktop as the AD user of the federated AWS identity that signs the MCP requests. The client then sends only the stack ARN, in the `aws.agentaccess/workspacesApplicationsStackArn` `_meta` key or the `X-Amzn-AgentAccess-Workspaces-Applications-Stack-Arn` header, and no SAML assertion. The demo agents don't support this yet; use any MCP client that signs with your own credentials, such as `mcp-proxy-for-aws` (see [AGENTS.md](AGENTS.md#domain-joined-fleets-without-a-saml-assertion)). Pass the ARN with `--header`, which the SigV4 signature covers, not `--metadata`, which edits the body after signing. `--header` needs `mcp-proxy-for-aws` 1.7.0 or later. The proxy needs mcp 1.x, so run it with `uvx` rather than in this repo's environment, which uses mcp 2.x: ```bash uvx --from mcp-proxy-for-aws==1.7.0 mcp-proxy-for-aws https://agentaccess-mcp.us-east-1.api.aws/mcp \ --service agentaccess-mcp --region us-east-1 \ --profile my-federated-role \ --header "X-Amzn-AgentAccess-Workspaces-Applications-Stack-Arn=arn:aws:appstream:us-east-1:123456789012:stack/MyDJStack" ``` The signing identity must be a role session federated from your IdP, with the AD user in two session tags, `UserPrincipalName` and `ObjectSid`. The role's trust policy must allow `sts:TagSession`. Either kind of IdP works: - **SAML.** The IdP sends the tags as `https://aws.amazon.com/SAML/Attributes/PrincipalTag:UserPrincipalName` and `https://aws.amazon.com/SAML/Attributes/PrincipalTag:ObjectSid` attributes. Pass the IdP's SAML response to `AssumeRoleWithSAML` (for example `aws sts assume-role-with-saml`), and sign the MCP requests with the role session credentials it returns, for example from an AWS CLI profile. The SAML assertion goes to AWS STS only; Agent Access sees the signed requests and the stack ARN. - **OIDC.** The IdP puts the tags in the token's `https://aws.amazon.com/tags` claim, and the role is assumed with `AssumeRoleWithWebIdentity`. An AWS CLI profile with `role_arn` and `web_identity_token_file` does this for you: ```ini [profile my-federated-role] role_arn = arn:aws:iam::123456789012:role/MyDJAgentRole web_identity_token_file = /path/to/oidc-token.jwt ``` For an agent acting for a signed-in user, get the OIDC token from an on-behalf-of (OBO) exchange: exchange the user's token for one issued to the agent, with [Okta On-Behalf-Of Token Exchange](https://developer.okta.com/docs/guides/set-up-token-exchange/main/) (RFC 8693) or [Microsoft Entra OBO](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-on-behalf-of-flow), then use the exchanged access token as the OIDC token above. Configure the IdP to put the tags claim on the exchanged token; on Entra that is a claims-mapping policy on the resource app, and on Okta a claim on a custom authorization server. The service takes the AD user from the tags, never from the token's `sub`. See [Pass session tags in AWS STS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) for both claim formats. Prerequisites: - WorkSpaces Applications fleet joined to an AD domain with Certificate-Based Authentication (CBA) enabled - IAM SAML or OIDC identity provider for your IdP - IAM role that trusts the provider, allows `sts:TagSession`, and has `agentaccess-mcp:*` permissions - The stack must be in the caller's account ## Create Your Own Agent There's a library provided in `lib/agent_common.py` that you can use to create your own agent. We've also provided an agent creator with prompts to describe your workflow: ```bash python3 agents/agent_creator/agent.py ``` The agent creator interviews you about your workflow, then generates skill files, prompts, and an `agent.py`. Iterate: ```bash python3 agents//agent.py --streaming-url "$STREAMING_URL" python3 agents/agent_creator/agent.py --update agents/ ``` ## Supported MCP Protocol Versions AgentAccess supports these MCP protocol versions: 1. `2025-03-26` 2. `2025-06-18` 3. `2025-11-25` 4. `2026-07-28` (stateless) **Note:** With stateless MCP, session management moves out of the protocol. The only difference customers will notice is how a session is closed: - **Stateful:** the client calls `mcp.close()`, which sends HTTP `DELETE` to close the session. - **Stateless:** the agent calls the new `agentaccess___close_session` tool to close the session. ## Computer-use interfaces By default the model is offered the Agent Access desktop tools (`left_click`, `type_text`, ...) as ordinary function tools. With `--computer-use-interface`, it is offered the computer-use tools a model was trained on instead, and the service converts each call. The agent sends the value in the `X-Amzn-AgentAccess-Computer-Use-Interface-Id` header on every MCP request; the service lists that interface's tools in place of the Agent Access desktop tools and converts each call into the desktop action it stands for (`lib/computer_use_interface.py`). The service's other tools, such as `agentaccess___wait`, stay listed. ```bash python3 agents/generic_cua/agent.py --streaming-url "$STREAMING_URL" \ --computer-use-interface ANTHROPIC_COMPUTER_20251124 ``` | Value | Tools in the shape of | How this agent offers them to the model | |-------|-----------------------|-----------------------------------------| | `ANTHROPIC_COMPUTER_20251124` | Anthropic's `computer_20251124` tool (one `computer` tool) | Claude's typed `computer_20251124` tool, with its beta header (Claude models only) | | `ANTHROPIC_COMPUTER_TOOLSET_20260801` | Anthropic's `computer_toolset_20260801` (one tool per action) | Claude's typed `computer_toolset_20260801`, no beta header (Sonnet 5 / Opus 5 models and later) | | `ANTHROPIC_COMPUTER_20250124` | Anthropic's older `computer_20250124` tool | The function tools the service lists | | `OPENAI_COMPUTER_V1` | OpenAI's computer-use tool (the action is in `type`) | The function tools the service lists | | `GOOGLE_COMPUTER_USE_3X_DESKTOP_V1` | Google Gemini's computer-use desktop tools (coordinates on a 0-999 grid) | The function tools the service lists | Values are case-sensitive. The service rejects actions the desktop cannot do, such as `wait`, `zoom` and `cursor_position`. With `ANTHROPIC_COMPUTER_20251124` the model pauses with the service's `agentaccess___wait` tool; with `ANTHROPIC_COMPUTER_TOOLSET_20260801` the toolset's own `wait` tool, which the service does not list, runs in the agent. If the service does not enable computer-use interfaces for your account, it lists the Agent Access desktop tools and the agent stops with an error that says so. Run metrics record each Claude call as the Agent Access action it stands for (`left_click` with `x`/`y`, not `computer`), and `computer_tool` in the metrics file says which tool shape a run used. ## Tool sequencing `agentaccess___execute_sequence` runs several tool calls in one request, in order, instead of one call per round-trip. Each action is an object with a `type` naming the tool to run, written the same way you call that tool directly, and that tool's own arguments beside it. Here it opens Notepad from the Run dialog and types a line, all in one call: ```json { "actions": [ {"type": "agentaccess___key", "keys": "super+r"}, {"type": "agentaccess___wait", "duration": 1}, {"type": "agentaccess___type_text", "text": "notepad"}, {"type": "agentaccess___wait", "duration": 1}, {"type": "agentaccess___key", "keys": "Return"}, {"type": "agentaccess___wait", "duration": 3}, {"type": "agentaccess___type_text", "text": "Opened and typed by one execute_sequence call."} ] } ``` The service runs the actions in order and stops at the first failure. The result's first content block is JSON with `sequence_summary` and `action_results`; a successful call also returns the final screenshot, as an inline image: ```json { "sequence_summary": {"submitted": 7, "executed": 7, "succeeded": 7, "guidance": ""}, "action_results": [ {"index": 0, "action": "key", "status": "success", "duration_ms": 2}, {"index": 1, "action": "wait", "status": "success", "duration_ms": 1000}, {"index": 2, "action": "type_text", "status": "success", "duration_ms": 2}, {"index": 3, "action": "wait", "status": "success", "duration_ms": 1002}, {"index": 4, "action": "key", "status": "success", "duration_ms": 3}, {"index": 5, "action": "wait", "status": "success", "duration_ms": 3001}, {"index": 6, "action": "type_text", "status": "success", "duration_ms": 2} ], "terminal_screenshot": {"status": "success", "duration_ms": 88} } ``` ### Limits Two limits are in the tool schema, so you can read them from `tools/list`: the action count (`execute_sequence`'s `actions.maxItems`, 20) and the per-wait range (`wait`'s `duration` `minimum`/`maximum`, 0.001 to 5 seconds). Three more are stated only in the `execute_sequence` description: all waits together at most 10 seconds, all `agentaccess___type_text` text together at most 10,000 characters, and a 60-second deadline for the whole sequence. `agentaccess___screenshot` and `agentaccess___execute_sequence` cannot be sub-actions. A sequence over the action count, a wait limit or the typed-text limit is rejected before any action runs: `isError` is set, every action is `skipped`, and `sequence_summary` carries the `stop_reason` and `guidance`. The deadline is checked as the sequence runs instead: once 60 seconds have passed, no further action starts, the rest are `skipped`, and the call returns `isError` with text only (`Deadline reached before action N`). The `stop_reason` of a rejection names the limit: - `too many actions: 21 > 20` - `action 0: wait duration must be a number between 0.001 and 5.0 seconds` - `cumulative wait 15.0s exceeds 10.0s` - `cumulative type_text length 11000 exceeds 10000` ```json { "sequence_summary": { "submitted": 3, "executed": 0, "succeeded": 0, "stopped_at_index": 0, "stop_reason": "CLIENT_ERROR: Rejected before dispatch: cumulative wait 15.0s exceeds 10.0s", "guidance": "Correct the sequence and retry. No desktop action ran, so no screenshot is needed." }, "action_results": [ {"index": 0, "action": "wait", "status": "skipped", "reason": "sequence rejected before dispatch"}, {"index": 1, "action": "wait", "status": "skipped", "reason": "sequence rejected before dispatch"}, {"index": 2, "action": "wait", "status": "skipped", "reason": "sequence rejected before dispatch"} ] } ``` Batch only actions you can plan without seeing intermediate results. Connect with a screenshot first so the desktop is attached, then batch. [`tool_sequencing.py`](tool_sequencing.py) is a self-contained example: it opens Notepad and types a note with one `execute_sequence`, reads these limits from `tools/list`, and shows one sequence rejected for each limit. ```bash STREAMING_URL=$(scripts/streaming_url.sh) python3 tool_sequencing.py "$STREAMING_URL" ``` For an agent that batches actions itself, run `generic_cua` with the sequencing task. The model opens Notepad with one `execute_sequence`, checks the screenshot it returns, then types a note with a second one: ```bash python3 agents/generic_cua/agent.py --streaming-url "$STREAMING_URL" \ --task-prompt agents/generic_cua/prompts/sequencing_task_prompt.md ``` ## Run metrics Every run of `generic_cua`, `application_validation` and `mcp_forwarding_demo` that finishes writes `agents//metrics/metrics_.json` (its log and screenshots sit beside it; a run killed before it finishes leaves a log but no metrics file): each model and tool call with its duration, failed tool calls with their error text, tokens including prompt-cache reads and writes, and the versions of the prompts that have frontmatter. Counts are per model call, not per turn: a turn in which the model uses a tool takes at least two model calls, so per-turn token figures run higher than per-call ones. The other samples (`agent_creator`, `quickstart.py`, the AgentCore sample) write none. To compare two batches of runs, for example before and after a change: ```bash python3 scripts/analyze_metrics.py --dir agents/application_validation/metrics --since 20261001_120000 --table ``` This prints one line per run (seconds, model calls, tool calls, failures, screenshots, tokens) and the means. Leave out `--table` for the full report. ## Running and stopping tasks Desktop actions run one at a time, in the order the model asks for them. If one fails, the rest of that model turn is skipped (the model is told, and looks at the screen again). `--max-turns` and `--max-seconds` are off unless set; they bound each task (an interactive `generic_cua` session gives every task you type a fresh budget), and a task that reaches one stops with a message naming the flag, and is not retried. A single desktop action that gets no answer is given up on after `--tool-timeout`; the service may keep executing it, so later actions can queue behind it. Keep `--tool-timeout` longer than the longest action a task needs (`hold_key` allows up to 30 seconds). Press Ctrl-C once to stop the running task: the current action finishes, the metrics are written, and an interactive session returns to its prompt. Press it again to quit at once. With `--max-seconds` set, a model call that never answers is not covered; it ends when the Bedrock client's own timeout does. ## CLI Reference | Flag | Default | Description | |------|---------|-------------| | `--streaming-url URL` | *(required unless a SAML assertion is given)* | WorkSpaces Applications streaming URL for the desktop session | | `--model-id ID` | `global.anthropic.claude-sonnet-5-5` | Bedrock model ID (`global.anthropic.claude-sonnet-4-6` also works) | | `--computer-use-interface INTERFACE` | off | Ask the service to list and run this computer-use interface's tools. See [Computer-use interfaces](#computer-use-interfaces) | | `--effort low\|medium\|high` | model default | Reasoning effort for Claude models that support it (sends adaptive thinking and `output_config.effort`) | | `--mcp-timeout SECS` | `180` | MCP client startup timeout | | `--mcp-retries N` | `3` | Number of MCP connection retries | | `--max-turns N` | off | Stop a task after N model calls | | `--max-seconds S` | off | Stop a task after S seconds | | `--expire-session-on-exit` | off | When the agent disconnects, also expire the WorkSpaces Applications streaming session (sends `X-Amzn-AgentAccess-Expire-Streaming-Session-On-Delete: true`). The desktop and everything open on it is discarded and the fleet scales per its policy; by default the session keeps running until its disconnect timeout. | | `--tool-timeout S` | `120` | Give up on one desktop action after S seconds (keep it above the longest `hold_key`/wait a task uses) | | `--region REGION` | auto-detect | AWS region for Bedrock calls | | `--mcp-region REGION` | `AWS_REGION` (or `mcp.region` in `scripts/config.json`) | AWS region for MCP SigV4 signing and the endpoint's `{region}`. Must match the fleet's region, which can differ from `--region` (Bedrock) | | `--no-screenshot-pruning` | off | Keep all screenshots in conversation context | | `--keep-screenshots N` | `3` | Screenshots kept in context; older ones become a text placeholder (the files stay on disk) | | `--prune-batch N` | `10` with prompt caching, `1` without | Prune once N screenshots beyond `--keep-screenshots` have piled up; `1` prunes before every model call. In a 540-run comparison on a live desktop, 10 cut the cost per run by about 45% at the same success | | `--prompt-cache` / `--no-prompt-cache` | on | Bedrock prompt caching (Claude models); `--no-prompt-cache` turns it off | | `--max-tokens N` | model default | Maximum tokens per model response | | `--mcp-profile PROFILE` | default | AWS profile for SigV4 signing to the MCP endpoint | | `--mcp-protocol stateless\|stateful` | per agent (`stateless` for `generic_cua`) | `stateless` (`2026-07-28`, the agent calls `close_session`; falls back to stateful when the endpoint has no `2026-07-28`) or `stateful` (the client closes the session). See [Supported MCP Protocol Versions](#supported-mcp-protocol-versions) | | `--llm-profile PROFILE` | default | AWS profile for Bedrock LLM calls | | `--mcp-endpoint URL` | `mcp.endpoint` in `scripts/config.json` | Agent Access MCP endpoint; `{region}` is replaced with the MCP region | | `--bedrock-api-key KEY` | `AWS_BEARER_TOKEN_BEDROCK`, else a short-term key minted from your credentials | Bedrock API key for non-Claude models (bedrock-mantle); not used for Claude | | `--saml-assertion-file PATH` | | File holding the base64 SAML assertion for Domain Join (replaces `--streaming-url`). `AGENTACCESS_SAML_ASSERTION` is read when this is not given | | `--stack-arn ARN` | | WorkSpaces Applications stack ARN (required with the assertion) | `generic_cua` also takes `--system-prompt`, `--task-prompt`, `--skill` and `--plain`; see [its README](agents/generic_cua/README.md). ## Project Structure ``` sample-code-for-workspaces-agent-access/ ├── quickstart.py # Minimal self-contained stateless example (~100 lines) ├── tool_sequencing.py # Self-contained execute_sequence example (batch desktop actions) ├── AGENTS.md # Developer guide (tools, architecture, IDE setup) ├── agents/ │ ├── agent_creator/ # Interactive agent builder │ ├── application_validation/ # Single-app validation │ ├── generic_cua/ # Interactive REPL agent │ └── mcp_forwarding_demo/ # Forwarded MCP tools (filesystem + fetch) demo ├── lib/ │ ├── agent_common.py # Shared infrastructure (re-exports from sub-modules) │ ├── agent_factory.py # The one place desktop agents are built; explicit auth modes │ ├── model.py # Bedrock model creation + multi-model support │ ├── mcp_client.py # MCP transport, endpoint resolution, tool names │ ├── domain_join_auth.py # Domain Join: adds the SAML assertion to _meta before SigV4 signing │ ├── saml_assertion.py # Domain Join inputs: assertion file, validation, log redaction │ ├── retry.py # Connection retry logic, error classification │ ├── screenshot_pruning_manager.py # Token-saving screenshot manager │ ├── computer_tool.py # Claude's typed computer tools for the Anthropic interfaces; how their calls are logged │ ├── computer_use_interface.py # Computer-use interfaces converted by the service (--computer-use-interface) │ ├── wait_tool.py # Local wait tool until the service offers one │ ├── replay_session.py # Find and download Replay Session recordings (--save-replay) │ ├── streaming_url.py # Stack and Region a streaming URL was created for (--save-replay) │ ├── terminal_ui.py # generic_cua's interactive terminal │ └── strands_logger.py # Metrics and logging ├── scripts/ │ ├── config.json # Fleet, stack, VPC, MCP endpoint config │ ├── setup.sh # One-step setup (macOS / Linux) │ ├── setup.ps1 # One-step setup (Windows) │ ├── streaming_url.sh # Mint a fresh WorkSpaces Applications streaming URL │ ├── setup_replay_session.sh # Turn on Replay Session for the stack │ ├── get_replay_session.py # Download a session's Replay Session recording │ ├── deploy.sh # Deploy VPC + Fleet + Stack │ ├── cleanup.sh # Tear down all resources │ ├── deploy_agentcore.sh # Deploy agent to Bedrock AgentCore Runtime │ ├── install.sh # Install Python dependencies (macOS / Linux) │ ├── install.ps1 # Install Python dependencies (Windows) │ ├── ci_local.sh # Run CI checks locally (compile + validate skill JSON) ├── skills/ │ └── workspace-skill-creator/ # Skill for creating new app skills ├── utils/ │ └── mcpforwardingtester/ # Validate MCP servers forward correctly before building an image └── requirements.txt ``` ## Troubleshooting **"The Agent Access MCP Server failed to connect"** - Check that the streaming URL hasn't expired (default: 1 hour) - Verify your AWS credentials: `aws sts get-caller-identity` **"timed out" / "Channel not connected"** - The desktop session may still be initializing. The agent retries automatically (3 attempts with increasing wait times). - If all retries fail, generate a fresh streaming URL and try again. **"Another agentic client is already connected" / `CONNECTION_LIMIT_REACHED`** - Only one agent can be attached to a desktop session. A session that an agent left attached, for example one whose process was killed with `kill -9` (older versions of this sample also left it attached after every normal exit), refuses the next connection with this message. This sample now ends its MCP session on exit, on Ctrl-C and on `SIGTERM`. - A connection attempt that failed part-way also left its session attached, so every retry and every later run was refused although the WorkSpaces Applications session showed as connected. This happened on stacks with application settings persistence: the first `tools/list` waits for the user's profile to load, and that took longer than the 30-second HTTP timeout this sample used to have. The agent now waits up to 300 seconds and ends the MCP session of a failed attempt, so the retry can connect. - To recover, wait for the session to time out, or expire it (`aws appstream expire-session --session-id `, ids from `aws appstream describe-sessions`) and start a new one; a fresh streaming URL for the same user then gets a new desktop. **`unrecognized arguments:` followed by `command not found: --saml-assertion-file` (or another flag)** - A space came after the `\` that continues a line, so the shell passed a blank argument to the agent and ran the next line as its own command. Remove the trailing space, or put the whole command on one line. **"400 Bad Request" from MCP endpoint** - The fleet's region and the MCP signing region must match. If your fleet is in `us-east-1` but you're signing requests for `us-west-2` (or vice versa), the service rejects them as cross-region. - Check `AWS_REGION` matches the fleet region, or pass `--mcp-region ` explicitly. **"400 Bad Request ... Invalid streaming URL: streaming URL has expired"** - The service refused the streaming URL (expired or invalid). Every later request is refused the same way, so the agent stops the task at the first refusal. Create a new URL and start the agent again; `create-streaming-url --validity` defaults to 60 seconds, and the examples here use 3600. **"401 Unauthorized" from MCP endpoint** - Your AWS credentials can't sign requests. Run `aws sts get-caller-identity` to verify. - If using profiles: `--mcp-profile ` for MCP, `--llm-profile ` for Bedrock. **"403 Forbidden" from MCP endpoint** - Check that your IAM credentials have the required permissions for the Agent Access MCP Server. - Domain Join: the credentials that sign the requests are expected to belong to the account that owns the `--stack-arn` stack. **Domain Join: the service reports that the SAML assertion has expired** - The assertion is short-lived. Get a new one and start the agent right away; retrying an expired assertion cannot work, so the agent stops at the first refusal. **"AccessDeniedException" from Bedrock** - Your credentials don't have `bedrock:InvokeModel` permission. - Check that the model ID is available in your region. **Agent runs but doesn't interact with the desktop** - Confirm the Stack was created with AgentAccessConfig (COMPUTER_INPUT, COMPUTER_VISION all ENABLED). - Recreate the stack if needed — see `scripts/deploy.sh`. **Fleet fails to start or "AccessDeniedException" from AppStream** - Your account may be missing the `AmazonAppStreamServiceAccess` service role, which WorkSpaces Applications needs to create fleets (see the note under [Prerequisites](#prerequisites)). - Check if it exists: `aws iam get-role --role-name AmazonAppStreamServiceAccess` - If missing, choose **Get started** in the [WorkSpaces Applications console](https://console.aws.amazon.com/appstream2/home), which creates it, or see [Checking for the AmazonAppStreamServiceAccess service role](https://docs.aws.amazon.com/appstream2/latest/developerguide/controlling-access-checking-for-iam-service-access.html). **Screenshot pruning** - By default, screenshots older than the newest three are replaced by a text placeholder before each model call, to reduce token usage. Use `--no-screenshot-pruning` to keep them all (useful for debugging). - Claude 5.x signs each thinking block against the conversation before it and rejects a request whose earlier content has changed (`Invalid signature in thinking block`). The agent edits its history (pruned screenshots, trimmed messages), so it removes the model's thinking blocks from the history before every model call; the model keeps what it did and saw, not its earlier reasoning. - Prompt caching (on by default for Claude models; `--no-prompt-cache` turns it off) reads the unchanged start of each request (tools, system prompt, earlier turns) at about a tenth of the normal input price; writing new content to the cache costs about 1.25x once. Pruning a screenshot changes the request from that message onward, and `--prune-batch` controls how often that happens. An AWS write-up of a similar agent (`--keep-screenshots 1`, pruning before every call) measured about 88% lower cost and 36% lower latency with caching, In a 540-run comparison on a live desktop (20 read-only tasks, 3 runs each), pruning every 10 screenshots instead of every call cut the cost by about 45% at the same success, and keeping only 1 screenshot lowered success (93% against 98%) and raised the cost. The `cache_read` and `cache_write` totals in the run metrics show what a run got. The cache expires after about 5 minutes without a hit, so the first model call after a long pause in an interactive session pays the write price again. ## Cleanup Remove all deployed AWS resources: ```bash ./scripts/cleanup.sh ``` This tears down the stack, fleet, VPC, subnets, NAT gateway, and security groups in reverse order. ## Appendix: Deploy to Bedrock AgentCore Runtime Deploy an agent to Bedrock AgentCore Runtime for managed hosting: ```bash ./scripts/deploy_agentcore.sh ./scripts/deploy_agentcore.sh --agent application_validation --name MyValidationAgent ``` Prerequisites: Node.js 20+, `agentcore` CLI (`npm install -g @aws/agentcore`), `uv` (Python package manager). Invoke: ```bash cd .agentcore-build/WorkspacesAgentDemo agentcore invoke '{"streaming_url": ""}' --stream ``` View logs: ```bash # Local CLI logs agentcore logs # CloudWatch logs (runtime) aws logs tail "/aws/bedrock-agentcore/runtimes/WorkspacesAgentDemo" --region us-east-1 --follow ``` Cleanup: ```bash ./scripts/deploy_agentcore.sh --cleanup ``` > **Note:** The AgentCore execution role must have access to the MCP Server endpoint. The deploy script automatically attaches the required IAM policy. **Security: single-principal deployment only** The AgentCore handler accepts `streaming_url` directly from the invocation payload. Anyone with permission to invoke the runtime can drive any WorkSpaces Applications session the execution role can reach — there is no cross-invoker isolation in this demo. **Do not expose the runtime to more than one principal.** Recommended configurations: - Single trusted caller (human operator or orchestration service) with `bedrock-agentcore:InvokeAgentRuntime` scoped to that principal. - No resource-based policies that grant broad cross-account invoke access. For production multi-tenant deployments, add a signed-grant flow: the caller passes an opaque `session_id`, the handler resolves it against a DynamoDB table that records the issuing principal, and rejects cross-principal lookups. ## Appendix: Integrate Into Your Own Agent If you already have a WorkSpaces Applications fleet deployed and want to add agent access to your own codebase, see [`quickstart.py`](quickstart.py) — a self-contained ~100-line stateless example with no dependencies on this repo's `lib/`: ```bash pip install strands-agents "mcp>=2" boto3 STREAMING_URL=$(scripts/streaming_url.sh) python3 quickstart.py "$STREAMING_URL" ``` The full framework in `agents/` and `lib/` adds retry logic, screenshot pruning, metrics, and multi-model support — but `quickstart.py` is all you need to connect an existing agent to a remote desktop. ## References - [Amazon WorkSpaces Applications — Administration Guide](https://docs.aws.amazon.com/appstream2/latest/developerguide/) — fleets, stacks, image builders, streaming URLs - [Amazon WorkSpaces Applications — Getting Started](https://docs.aws.amazon.com/appstream2/latest/developerguide/getting-started.html) — end-to-end setup with sample applications - [Amazon WorkSpaces Applications — API Reference](https://docs.aws.amazon.com/appstream2/latest/APIReference/Welcome.html) — SDK and CLI operations - [Amazon Bedrock — Claude models](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html) — model IDs, inference parameters, regional availability - [Strands Agents SDK](https://strandsagents.com/) — the agent framework this sample builds on