Skip to content

TypeScript Strands Agent

Filter this guide Pick generator option values to hide sections that don't apply.

Generate a TypeScript Strands Agent for building AI agents with tools, and optionally deploy it to Amazon Bedrock AgentCore Runtime. By default, the generator uses tRPC over WebSocket to leverage AgentCore’s bidirectional streaming support for real-time, type-safe communication. Alternatively, you can choose the Agent-to-Agent (A2A) protocol for interoperability with other A2A-compatible agents.

Strands is a lightweight framework for building AI agents. Key features include:

  • Lightweight and customizable: Simple agent loop that gets out of your way
  • Production ready: Full observability, tracing, and deployment options for scale
  • Model and provider agnostic: Supports many different models from various providers
  • Community-driven tools: Powerful set of community-contributed tools
  • Multi-agent support: Advanced techniques like agent teams and autonomous agents
  • Flexible interaction modes: Conversational, streaming, and non-streaming support

You can generate a TypeScript Strands Agent in two ways:

  1. Install the Nx Console VSCode Plugin if you haven't already
  2. Open the Nx Console in VSCode
  3. Click Generate (UI) in the "Common Nx Commands" section
  4. Search for @aws/nx-plugin - ts#strands-agent
  5. Fill in the required parameters
    • Click Generate
    Parameter Type Default Description
    project Required string - The project to add the Strands Agent to
    computeType string BedrockAgentCoreRuntime The type of compute to host your Strands Agent.
    name string - The name of your Strands Agent (default: agent)
    auth string IAM The method used to authenticate with your Strands Agent. Choose between IAM (default) or Cognito.
    protocol string HTTP The server protocol for your Strands Agent. HTTP exposes a tRPC/WebSocket server. A2A exposes an Agent-to-Agent protocol server. AG-UI is not yet supported for TypeScript agents.
    iacProvider string Inherit The preferred IaC provider. By default this is inherited from your initial selection.

    The generator will add the following files to your existing TypeScript project. The files generated depend on the chosen protocol:

    protocol = HTTP
    • Directoryyour-project/
      • Directorysrc/
        • Directoryagent/ (or custom name if specified)
          • index.ts Entry point for Bedrock AgentCore Runtime (tRPC/WebSocket server)
          • init.ts tRPC initialization
          • router.ts tRPC router with agent procedures
          • agent.ts Main agent definition with sample tools
          • client.ts Vended client for invoking your agent
          • agent-core-trpc-client.ts Client factory for connecting to agents on AgentCore Runtime
          • Dockerfile Entry point for hosting your agent (excluded when computeType is set to None)
      • package.json Updated with Strands dependencies
      • project.json Updated with agent serve targets
    protocol = A2A

    The entry point uses the Strands A2A Express Server instead of tRPC:

    • Directoryyour-project/
      • Directorysrc/
        • Directoryagent/ (or custom name if specified)
          • index.ts A2A Express server entry point
          • agent.ts Main agent definition with sample tools
          • Dockerfile Entry point for hosting your agent (excluded when computeType is set to None)
      • package.json Updated with Strands and Express dependencies
      • project.json Updated with agent serve targets
    computeType = BedrockAgentCoreRuntime

    Since this generator vends infrastructure as code based on your chosen iacProvider, it will create a project in packages/common which includes the relevant CDK constructs or Terraform modules.

    The common infrastructure as code project is structured as follows:

    • Directorypackages/common/constructs
      • Directorysrc
        • Directoryapp/ Constructs for infrastructure specific to a project/generator
        • Directorycore/ Generic constructs which are reused by constructs in app
        • index.ts Entry point exporting constructs from app
      • project.json Project build targets and configuration

    For deploying your Strands Agent, the following files are generated:

    • Directorypackages/common/constructs/src
      • Directoryapp
        • Directoryagents
          • Directory<project-name>
            • <project-name>.ts CDK construct for deploying your agent
    computeType = None

    If you selected None for computeType, no CDK constructs or Terraform modules are generated — the Strands Agent can only be run locally.

    Your agent’s server protocol determines how it communicates. You can choose between:

    • HTTP (default): Uses tRPC over WebSocket for real-time, type-safe communication. Best for custom client integrations and fine-grained control over the agent’s API.
    • A2A: Uses the Agent-to-Agent (A2A) protocol for standardized inter-agent communication. Best when your agent needs to be discoverable and invokable by other A2A-compatible agents.

    The protocol is set in the CDK/Terraform infrastructure, and the application code is generated accordingly.

    protocol = HTTP

    The TypeScript Strands Agent uses tRPC over WebSocket, leveraging AgentCore’s bidirectional streaming support to enable real-time, type-safe communication between clients and your agent.

    Since tRPC supports Query, Mutation and Subscription procedures over WebSocket, you can define any number of procedures. By default, a single subscription procedure named invoke is defined for you in router.ts.

    Tools are functions that the AI agent can call to perform actions. You can add new tools in the agent.ts file:

    import { Agent, tool } from '@strands-agents/sdk';
    import { z } from 'zod';
    const letterCounter = tool({
    name: 'letter_counter',
    description: 'Count occurrences of a specific letter in a word',
    inputSchema: z.object({
    word: z.string().describe('The input word to search in'),
    letter: z.string().length(1).describe('The specific letter to count'),
    }),
    callback: (input) => {
    const { word, letter } = input;
    const count = word.toLowerCase().split(letter.toLowerCase()).length - 1;
    return `The letter '${letter}' appears ${count} time(s) in '${word}'`;
    },
    });
    // Add tools to your agent
    export const getAgent = async (sessionId: string) => {
    return new Agent({
    systemPrompt: 'You are a helpful assistant with access to various tools.',
    tools: [letterCounter],
    });
    };

    The Strands framework automatically handles:

    • Input validation using Zod schemas
    • JSON schema generation for tool calling
    • Error handling and response formatting

    By default, Strands agents use Claude 4 Sonnet, but you can easily switch between model providers:

    import { Agent } from '@strands-agents/sdk';
    import { BedrockModel } from '@strands-agents/sdk/models/bedrock';
    import { OpenAIModel } from '@strands-agents/sdk/models/openai';
    // Use Bedrock
    const bedrockModel = new BedrockModel({
    modelId: 'anthropic.claude-sonnet-4-20250514-v1:0',
    });
    let agent = new Agent({ model: bedrockModel });
    let response = await agent.invoke('What can you help me with?');
    // Alternatively, use OpenAI by just switching model provider
    const openaiModel = new OpenAIModel({
    apiKey: process.env.OPENAI_API_KEY,
    modelId: 'gpt-4o',
    });
    agent = new Agent({ model: openaiModel });
    response = await agent.invoke('What can you help me with?');

    See the Strands documentation on model providers for more configuration options.

    You can add tools from MCP servers to your Strands agent.

    For consuming MCP Servers which you have created using the py#mcp-server or ts#mcp-server generators you can make use of the connection generator.

    1. Install the Nx Console VSCode Plugin if you haven't already
    2. Open the Nx Console in VSCode
    3. Click Generate (UI) in the "Common Nx Commands" section
    4. Search for @aws/nx-plugin - connection
    5. Fill in the required parameters
      • Click Generate

      Refer to the connection generator guide for details about how the connection is set up.

      For other MCP servers, please refer to the Strands Documentation.

      For a more in-depth guide to writing Strands agents, refer to the Strands documentation.

      protocol = A2A

      The generated index.ts mounts the Strands A2A Express Server onto an Express app so the generated agent exposes the A2A protocol endpoints alongside a /ping health check. When deployed to AgentCore, the entry point resolves the runtime’s public ARN from AppConfig and advertises it in the agent card.

      Most users will not need to modify this file — edit agent.ts to change tools or the system prompt. A2A agents listen on port 9000 (vs 8080 for HTTP), which the generated Dockerfile and infrastructure are already configured for.

      The generator configures a target named <your-agent-name>-serve, which starts your Strands Agent locally for development and testing.

      Terminal window
      pnpm nx agent-serve your-project

      This command uses tsx --watch to automatically restart the server when files change. The agent will be available at http://localhost:8081 (or the assigned port if you have multiple agents).

      The generator configures a <your-agent-name>-chat Nx target that depends on <your-agent-name>-serve-local. Running it starts the agent locally and drops you into an interactive terminal chat:

      Terminal window
      pnpm nx run your-project:agent-chat

      For HTTP (tRPC over WebSocket) agents, the generator also emits a tiny scripts/<your-agent-name>/chat.ts that wraps the generated <Agent>Client.local({ url }) so you can customize it as you evolve the agent’s input shape.

      computeType = BedrockAgentCoreRuntime

      Deploying Your Strands Agent to Bedrock AgentCore Runtime

      Section titled “Deploying Your Strands Agent to Bedrock AgentCore Runtime”

      If you selected BedrockAgentCoreRuntime for computeType, the relevant CDK or Terraform infrastructure is generated which you can use to deploy your Strands Agent to Amazon Bedrock AgentCore Runtime.

      A CDK construct is generated for your agent, named based on the name you chose when running the generator, or <ProjectName>Agent by default.

      You can use this CDK construct in a CDK application:

      import { MyProjectAgent } from ':my-scope/common-constructs';
      export class ExampleStack extends Stack {
      constructor(scope: Construct, id: string) {
      new MyProjectAgent(this, 'MyProjectAgent');
      }
      }

      The generator provides an auth option to configure authentication for your Strands Agent. You can choose between IAM (default) or Cognito authentication when generating your agent.

      By default, your Strands Agent will be secured using IAM authentication, simply deploy it without any arguments:

      import { MyProjectAgent } from ':my-scope/common-constructs';
      export class ExampleStack extends Stack {
      constructor(scope: Construct, id: string) {
      new MyProjectAgent(this, 'MyProjectAgent');
      }
      }

      You can grant access to invoke your agent on Bedrock AgentCore Runtime using the grantInvokeAccess method, for example:

      import { MyProjectAgent } from ':my-scope/common-constructs';
      export class ExampleStack extends Stack {
      constructor(scope: Construct, id: string) {
      const agent = new MyProjectAgent(this, 'MyProjectAgent');
      const lambdaFunction = new Function(this, ...);
      agent.grantInvokeAccess(lambdaFunction);
      }
      }

      When you select Cognito authentication, the generator configures the agent to use Cognito for authentication.

      The generated construct accepts an identity prop which configures Cognito authentication:

      import { MyProjectAgent, UserIdentity } from ':my-scope/common-constructs';
      export class ExampleStack extends Stack {
      constructor(scope: Construct, id: string) {
      const identity = new UserIdentity(this, 'Identity');
      new MyProjectAgent(this, 'MyProjectAgent', {
      identity,
      });
      }
      }

      The UserIdentity construct can be generated using the ts#react-website#auth generator, or you can create your own CDK UserPool and UserPoolClient.

      The generator automatically configures a bundle target which uses Rolldown to create a deployment package:

      Terminal window
      pnpm nx bundle <project-name>

      Rolldown configuration can be found in rolldown.config.ts, with an entry per bundle to generate. Rolldown manages creating multiple bundles in parallel if defined.

      The bundle target uses index.ts as the entrypoint for the WebSocket server to host on Bedrock AgentCore Runtime.

      The generator configures a <your-agent-name>-docker target which copies the Dockerfile from your agent source directory into the bundle output directory. This co-locates the Dockerfile with the bundled artifacts, allowing CDK to build the Docker image directly using AgentRuntimeArtifact.fromAsset.

      A docker target is also generated which prepares the docker context for all agents if you have multiple defined.

      Your agent is automatically configured with observability using the AWS Distro for Open Telemetry (ADOT), by configuring auto-instrumentation in your Dockerfile.

      You can find traces in the CloudWatch AWS Console, by selecting “GenAI Observability” in the menu. Note that for traces to be populated you will need to enable Transaction Search.

      For more details, refer to the AgentCore documentation on observability.

      Agent communication is transmitted via tRPC over WebSocket. As such, it’s recommended to use the generated type-safe client factory in client.ts.

      protocol = HTTP

      You can invoke a locally running agent using the .local factory method from the client factory.

      You can, for example create a file named scripts/test.ts in your workspace which imports the client:

      scripts/test.ts
      import { AgentClient } from '../packages/<project>/src/agent/client.js';
      const client = AgentClient.local({ url: 'http://localhost:8081/ws' });
      client.invoke.subscribe({ message: 'what is 1 plus 1?' }, { onData: console.log });

      To invoke your Agent deployed to Bedrock AgentCore Runtime, you can send a POST request to the Bedrock AgentCore Runtime dataplane endpoint with your URL-encoded runtime ARN.

      You can obtain the runtime ARN from your infrastructure as follows:

      import { CfnOutput } from 'aws-cdk-lib';
      import { MyProjectAgent } from ':my-scope/common-constructs';
      export class ExampleStack extends Stack {
      constructor(scope: Construct, id: string) {
      const agent = new MyProjectAgent(this, 'MyProjectAgent');
      new CfnOutput(this, 'AgentArn', {
      value: agent.agentCoreRuntime.agentRuntimeArn,
      });
      }
      }

      The ARN will have the following format: arn:aws:bedrock-agentcore:<region>:<account>:runtime/<agent-runtime-id>.

      You can then URL-encode the ARN by replacing : with %3A and / with %2F.

      The Bedrock AgentCore Runtime dataplane URL for invoking the agent is as follows:

      https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocations

      The exact way to invoke this URL depends upon the authentication method used.

      The generated client.ts file includes a type-safe client factory which can be used to invoke your deployed agent.

      You can invoke your deployed agent by passing its ARN to the withIamAuth factory method:

      import { AgentClient } from './agent/client.js';
      const client = AgentClient.withIamAuth({
      agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
      });
      client.invoke.subscribe({ message: 'what is 1 plus 1?' }, {
      onData: (message) => console.log(message),
      onError: (error) => console.error(error),
      onComplete: () => console.log('Done'),
      });

      For invoking your Strands Agent from a React website, you can make use of the connection generator, which automatically sets up a tRPC WebSocket client with the correct authentication (IAM or Cognito).

      1. Install the Nx Console VSCode Plugin if you haven't already
      2. Open the Nx Console in VSCode
      3. Click Generate (UI) in the "Common Nx Commands" section
      4. Search for @aws/nx-plugin - connection
      5. Fill in the required parameters
        • Click Generate

        Refer to the connection generator guide for details about how the connection is set up.

        protocol = A2A

        To delegate work from this agent to a remote A2A agent (either TypeScript or Python), use the connection generator. It vends a SigV4-authenticated client for the target agent and AST-transforms this agent’s agent.ts to register the remote A2A agent as a Strands tool.

        1. Install the Nx Console VSCode Plugin if you haven't already
        2. Open the Nx Console in VSCode
        3. Click Generate (UI) in the "Common Nx Commands" section
        4. Search for @aws/nx-plugin - connection
        5. Fill in the required parameters
          • Click Generate

          Refer to the connection generator guide for details about how the connection is set up.