Skip to content

TypeScript Strands Agent

Generate a TypeScript Strands Agent for building AI agents with tools, and optionally deploy it to Amazon Bedrock AgentCore Runtime. The generator uses tRPC over WebSocket to leverage AgentCore’s bidirectional streaming support for real-time, type-safe communication.

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.
    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:

    • Directoryyour-project/
      • Directorysrc/
        • Directoryagent/ (or custom name if specified)
          • index.ts Entry point for Bedrock AgentCore Runtime
          • 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

    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
            • Dockerfile Passthrough docker file used by the CDK construct

    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.

      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).

      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) {
      // Add the agent to your stack
      const agent = new MyProjectAgent(this, 'MyProjectAgent');
      // Grant permissions to invoke the relevant models in bedrock
      agent.agentCoreRuntime.addToRolePolicy(
      new PolicyStatement({
      actions: [
      'bedrock:InvokeModel',
      'bedrock:InvokeModelWithResponseStream',
      ],
      // You can scope the below down to the specific models you use
      resources: [
      'arn:aws:bedrock:*:*:foundation-model/*',
      'arn:aws:bedrock:*:*:inference-profile/*',
      ],
      }),
      );
      }
      }

      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 runs the bundled WebSocket server on port 8080 as per the AgentCore runtime contract.

      A docker target is also generated which runs the docker build 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.

      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'),
      });

      Use the withJwtAuth factory method to authenticate with the JWT / Cognito access token.

      const client = AgentClient.withJwtAuth({
      agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
      accessTokenProvider: async () => `<access-token>`,
      });
      client.invoke.subscribe({ message: 'what is 1 plus 1?' }, {
      onData: console.log,
      });

      The accessTokenProvider must return the token used to authenticate the request. You can, for example, obtain a token within this method to ensure that fresh credentials are reused when tRPC restarts a WebSocket connection. The below demonstrates using the AWS SDK to obtain the token from Cognito:

      import { CognitoIdentityProvider } from "@aws-sdk/client-cognito-identity-provider";
      const cognito = new CognitoIdentityProvider();
      const jwtClient = AgentClient.withJwtAuth({
      agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',
      accessTokenProvider: async () => {
      const response = await cognito.adminInitiateAuth({
      UserPoolId: '<user-pool-id>',
      ClientId: '<user-pool-client-id>',
      AuthFlow: 'ADMIN_NO_SRP_AUTH',
      AuthParameters: {
      USERNAME: '<username>',
      PASSWORD: '<password>',
      },
      });
      return response.AuthenticationResult!.AccessToken!;
      },
      });

      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.