TypeScript Strands Agent
Tạo một TypeScript Strands Agent để xây dựng các AI agent với công cụ, và tùy chọn triển khai nó lên Amazon Bedrock AgentCore Runtime. Generator sử dụng tRPC qua WebSocket để tận dụng hỗ trợ streaming hai chiều của AgentCore cho giao tiếp thời gian thực, type-safe.
Strands là gì?
Phần tiêu đề “Strands là gì?”Strands là một framework nhẹ để xây dựng các AI agent. Các tính năng chính bao gồm:
- Nhẹ và có thể tùy chỉnh: Vòng lặp agent đơn giản không cản trở bạn
- Sẵn sàng cho production: Khả năng quan sát đầy đủ, tracing, và các tùy chọn triển khai cho quy mô lớn
- Không phụ thuộc vào model và provider: Hỗ trợ nhiều model khác nhau từ nhiều provider
- Công cụ do cộng đồng đóng góp: Bộ công cụ mạnh mẽ do cộng đồng đóng góp
- Hỗ trợ đa agent: Các kỹ thuật nâng cao như nhóm agent và agent tự động
- Chế độ tương tác linh hoạt: Hỗ trợ hội thoại, streaming, và non-streaming
Sử dụng
Phần tiêu đề “Sử dụng”Tạo một Strands Agent
Phần tiêu đề “Tạo một Strands Agent”Bạn có thể tạo một TypeScript Strands Agent theo hai cách:
- Install the Nx Console VSCode Plugin if you haven't already
- Open the Nx Console in VSCode
- Click
Generate (UI)in the "Common Nx Commands" section - Search for
@aws/nx-plugin - ts#strands-agent - Fill in the required parameters
- Click
Generate
pnpm nx g @aws/nx-plugin:ts#strands-agentyarn nx g @aws/nx-plugin:ts#strands-agentnpx nx g @aws/nx-plugin:ts#strands-agentbunx nx g @aws/nx-plugin:ts#strands-agentYou can also perform a dry-run to see what files would be changed
pnpm nx g @aws/nx-plugin:ts#strands-agent --dry-runyarn nx g @aws/nx-plugin:ts#strands-agent --dry-runnpx nx g @aws/nx-plugin:ts#strands-agent --dry-runbunx nx g @aws/nx-plugin:ts#strands-agent --dry-runTùy chọn
Phần tiêu đề “Tùy chọn”| 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) |
| iacProvider | string | Inherit | The preferred IaC provider. By default this is inherited from your initial selection. |
Đầu ra của Generator
Phần tiêu đề “Đầu ra của Generator”Generator sẽ thêm các file sau vào dự án TypeScript hiện có của bạn:
Thư mụcyour-project/
Thư mụcsrc/
Thư mụcagent/ (hoặc tên tùy chỉnh nếu được chỉ định)
- index.ts Điểm vào cho Bedrock AgentCore Runtime
- init.ts Khởi tạo tRPC
- router.ts tRPC router với các agent procedure
- agent.ts Định nghĩa agent chính với các công cụ mẫu
- client.ts Client được cung cấp để gọi agent của bạn
- agent-core-trpc-client.ts Client factory để kết nối với các agent trên AgentCore Runtime
- agent-core-mcp-client.ts Client factory để kết nối với các MCP server trên AgentCore Runtime
- Dockerfile Điểm vào để host agent của bạn (loại trừ khi
computeTypeđược đặt thànhNone)
- package.json Được cập nhật với các dependency của Strands
- project.json Được cập nhật với các target serve agent
Hạ tầng
Phần tiêu đề “Hạ tầng”Vì generator này cung cấp infrastructure as code dựa trên iacProvider bạn đã chọn, nó sẽ tạo một dự án trong packages/common bao gồm các CDK constructs hoặc Terraform modules liên quan.
Dự án infrastructure as code chung được cấu trúc như sau:
Thư mụcpackages/common/constructs
Thư mụcsrc
Thư mụcapp/ Constructs cho infrastructure cụ thể của một dự án/generator
- …
Thư mụccore/ Constructs chung được tái sử dụng bởi các constructs trong
app- …
- index.ts Entry point xuất các constructs từ
app
- project.json Các build targets và cấu hình của dự án
Thư mụcpackages/common/terraform
Thư mụcsrc
Thư mụcapp/ Terraform modules cho infrastructure cụ thể của một dự án/generator
- …
Thư mụccore/ Modules chung được tái sử dụng bởi các modules trong
app- …
- project.json Các build targets và cấu hình của dự án
Để triển khai Strands Agent của bạn, các file sau được tạo ra:
Thư mụcpackages/common/constructs/src
Thư mụcapp
Thư mụcagents
Thư mục<project-name>
- <project-name>.ts CDK construct để triển khai agent của bạn
- Dockerfile File docker passthrough được sử dụng bởi CDK construct
Thư mụcpackages/common/terraform/src
Thư mụcapp
Thư mụcagents
Thư mục<project-name>
- <project-name>.tf Module để triển khai agent của bạn
Thư mụccore
Thư mụcagent-core
- runtime.tf Module chung để triển khai lên Bedrock AgentCore Runtime
Làm việc với Strands Agent của bạn
Phần tiêu đề “Làm việc với Strands Agent của bạn”tRPC qua WebSocket
Phần tiêu đề “tRPC qua WebSocket”TypeScript Strands Agent sử dụng tRPC qua WebSocket, tận dụng hỗ trợ streaming hai chiều của AgentCore để cho phép giao tiếp thời gian thực, type-safe giữa client và agent của bạn.
Vì tRPC hỗ trợ các procedure Query, Mutation và Subscription qua WebSocket, bạn có thể định nghĩa bất kỳ số lượng procedure nào. Mặc định, một subscription procedure duy nhất có tên invoke được định nghĩa cho bạn trong router.ts.
Thêm công cụ
Phần tiêu đề “Thêm công cụ”Công cụ là các hàm mà AI agent có thể gọi để thực hiện các hành động. Bạn có thể thêm công cụ mới trong file agent.ts:
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 agentexport const agent = new Agent({ systemPrompt: 'You are a helpful assistant with access to various tools.', tools: [letterCounter],});Framework Strands tự động xử lý:
- Xác thực đầu vào sử dụng Zod schema
- Tạo JSON schema cho việc gọi công cụ
- Xử lý lỗi và định dạng response
Cấu hình Model
Phần tiêu đề “Cấu hình Model”Mặc định, các Strands agent sử dụng Claude 4 Sonnet, nhưng bạn có thể dễ dàng chuyển đổi giữa các model provider:
import { Agent } from '@strands-agents/sdk';import { BedrockModel } from '@strands-agents/sdk/models/bedrock';import { OpenAIModel } from '@strands-agents/sdk/models/openai';
// Use Bedrockconst 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 providerconst 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?');Xem tài liệu Strands về các model provider để biết thêm các tùy chọn cấu hình.
Sử dụng MCP Server
Phần tiêu đề “Sử dụng MCP Server”Bạn có thể thêm công cụ từ các MCP server vào Strands agent của bạn.
Để sử dụng các MCP Server mà bạn đã tạo bằng generator py#mcp-server hoặc ts#mcp-server (hoặc các server khác được host trên Bedrock AgentCore Runtime), một client factory được tạo cho bạn trong agent-core-mcp-client.ts.
Bạn có thể cập nhật khởi tạo agent của bạn trong agent.ts để tạo MCP client và thêm công cụ. Ví dụ sau đây cho thấy cách thực hiện điều này với xác thực IAM (SigV4):
import { Agent } from '@strands-agents/sdk';import { AgentCoreMcpClient } from './agent-core-mcp-client.js';
const mcpClient = AgentCoreMcpClient.withIamAuth({ agentRuntimeArn: process.env.MCP_AGENTCORE_RUNTIME_ARN!, region: process.env.AWS_REGION || 'us-west-2', sessionId: 'my-session-id',});
export const agent = new Agent({ systemPrompt: '...', tools: [mcpClient],});Với ví dụ xác thực IAM ở trên, chúng ta cần cấu hình hai thứ trong hạ tầng của mình. Thứ nhất, chúng ta cần thêm biến môi trường mà agent của chúng ta đang sử dụng cho ARN của AgentCore Runtime của MCP server, và thứ hai chúng ta cần cấp quyền cho agent của chúng ta để gọi MCP server. Điều này có thể đạt được như sau:
import { MyProjectAgent, MyProjectMcpServer } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const mcpServer = new MyProjectMcpServer(this, 'MyProjectMcpServer');
const agent = new MyProjectAgent(this, 'MyProjectAgent', { environmentVariables: { MCP_AGENTCORE_RUNTIME_ARN: mcpServer.agentCoreRuntime.agentRuntimeArn, }, });
mcpServer.agentCoreRuntime.grantInvoke(agent.agentCoreRuntime); }}# MCP Servermodule "my_project_mcp_server" { source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"}
# Agentmodule "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"
env = { MCP_AGENTCORE_RUNTIME_ARN = module.my_project_mcp_server.agent_core_runtime_arn }
additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_mcp_server.agent_core_runtime_arn, "${module.my_project_mcp_server.agent_core_runtime_arn}/*" ] } ]}Để có hướng dẫn chi tiết hơn về viết Strands agent, tham khảo tài liệu Strands.
Chạy Strands Agent của bạn
Phần tiêu đề “Chạy Strands Agent của bạn”Phát triển Local
Phần tiêu đề “Phát triển Local”Generator cấu hình một target có tên <your-agent-name>-serve, khởi động Strands Agent của bạn locally để phát triển và kiểm thử.
pnpm nx run your-project:agent-serveyarn nx run your-project:agent-servenpx nx run your-project:agent-servebunx nx run your-project:agent-serveLệnh này sử dụng tsx --watch để tự động khởi động lại server khi các file thay đổi. Agent sẽ có sẵn tại http://localhost:8081 (hoặc cổng được gán nếu bạn có nhiều agent).
Triển khai Strands Agent của bạn lên Bedrock AgentCore Runtime
Phần tiêu đề “Triển khai Strands Agent của bạn lên Bedrock AgentCore Runtime”Infrastructure as Code
Phần tiêu đề “Infrastructure as Code”Nếu bạn đã chọn BedrockAgentCoreRuntime cho computeType, cơ sở hạ tầng CDK hoặc Terraform liên quan sẽ được tạo ra mà bạn có thể sử dụng để triển khai Strands Agent của mình lên Amazon Bedrock AgentCore Runtime.
Một CDK construct được tạo ra cho agent của bạn, được đặt tên dựa trên name bạn đã chọn khi chạy trình tạo, hoặc mặc định là <ProjectName>Agent.
Bạn có thể sử dụng CDK construct này trong một ứng dụng CDK:
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/*', ], }), ); }}Một module Terraform được tạo ra cho bạn, được đặt tên dựa trên name bạn đã chọn khi chạy trình tạo, hoặc mặc định là <ProjectName>-agent.
Bạn có thể sử dụng module terraform này trong một dự án Terraform:
# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"
# Grant permissions to invoke the relevant models in bedrock additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ] # You can scope the below down to the specific models you use Resource = [ "arn:aws:bedrock:*:*:foundation-model/*", "arn:aws:bedrock:*:*:inference-profile/*" ] } ]}Xác thực
Phần tiêu đề “Xác thực”Theo mặc định, Strands Agent của bạn sẽ được bảo mật bằng xác thực IAM, chỉ cần triển khai nó mà không cần bất kỳ tham số nào:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}Bạn có thể cấp quyền truy cập để gọi agent của mình trên Bedrock AgentCore Runtime bằng phương thức grantInvoke, ví dụ:
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.agentCoreRuntime.grantInvoke(lambdaFunction); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"}Để cấp quyền truy cập gọi agent của bạn, bạn sẽ cần thêm một policy như sau, tham chiếu đến output module.my_project_agent.agent_core_runtime_arn:
{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_agent.agent_core_runtime_arn, "${module.my_project_agent.agent_core_runtime_arn}/*" ]}Xác thực Cognito JWT
Phần tiêu đề “Xác thực Cognito JWT”Dưới đây minh họa cách cấu hình xác thực Cognito cho agent của bạn.
Để cấu hình xác thực JWT sử dụng Cognito, hãy sử dụng phương thức factory RuntimeAuthorizerConfiguration.usingCognito():
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const userPool = new UserPool(this, 'UserPool'); const client = userPool.addClient('Client', { authFlows: { userPassword: true, }, });
new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: RuntimeAuthorizerConfiguration.usingCognito( userPool, [client], ), }); }}Ngoài ra, để xác thực JWT tùy chỉnh với nhà cung cấp OIDC của riêng bạn, hãy sử dụng RuntimeAuthorizerConfiguration.usingJWT():
import { MyProjectAgent } from ':my-scope/common-constructs';import { RuntimeAuthorizerConfiguration } from '@aws-cdk/aws-bedrock-agentcore-alpha';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: RuntimeAuthorizerConfiguration.usingJWT( 'https://example.com/.well-known/openid-configuration', ['client1', 'client2'], // Allowed Client IDs (optional) ['audience1'], // Allowed Audiences (optional) ), }); }}Để cấu hình xác thực JWT, bạn có thể chỉnh sửa module agent của mình để cấu hình biến authorizer_configuration như sau:
data "aws_region" "current" {}
locals { aws_region = data.aws_region.current.id
# Replace with your user pool and client ids or expose as variables user_pool_id = "xxx" user_pool_client_ids = ["yyy"]}
module "agent_core_runtime" { source = "../../../core/agent-core" agent_runtime_name = "MyProjectAgent" docker_image_tag = "my-scope-my-project-agent:latest" server_protocol = "HTTP" authorizer_configuration = { custom_jwt_authorizer = { discovery_url = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration" allowed_clients = local.user_pool_client_ids } } env = var.env additional_iam_policy_statements = var.additional_iam_policy_statements tags = var.tags}Bundle Target
Phần tiêu đề “Bundle Target”Generator tự động cấu hình một target bundle sử dụng Rolldown để tạo gói triển khai:
pnpm nx run <project-name>:bundleyarn nx run <project-name>:bundlenpx nx run <project-name>:bundlebunx nx run <project-name>:bundleCấu hình Rolldown có thể được tìm thấy trong rolldown.config.ts, với một entry cho mỗi bundle cần tạo. Rolldown quản lý việc tạo nhiều bundle song song nếu được định nghĩa.
Bundle target sử dụng index.ts làm entrypoint cho WebSocket server để host trên Bedrock AgentCore Runtime.
Docker Target
Phần tiêu đề “Docker Target”Generator cấu hình một target <your-agent-name>-docker chạy WebSocket server đã được bundle trên cổng 8080 theo hợp đồng runtime của AgentCore.
Một target docker cũng được tạo ra để chạy docker build cho tất cả các agent nếu bạn có nhiều agent được định nghĩa.
Khả năng quan sát
Phần tiêu đề “Khả năng quan sát”Agent của bạn được tự động cấu hình với khả năng quan sát sử dụng AWS Distro for Open Telemetry (ADOT), bằng cách cấu hình auto-instrumentation trong Dockerfile của bạn.
Bạn có thể tìm thấy các trace trong CloudWatch AWS Console, bằng cách chọn “GenAI Observability” trong menu. Lưu ý rằng để các trace được điền, bạn sẽ cần bật Transaction Search.
Để biết thêm chi tiết, tham khảo tài liệu AgentCore về khả năng quan sát.
Gọi Strands Agent của bạn
Phần tiêu đề “Gọi Strands Agent của bạn”Giao tiếp với agent được truyền qua tRPC qua WebSocket. Do đó, nên sử dụng client factory type-safe được tạo ra trong client.ts.
Gọi Local Server
Phần tiêu đề “Gọi Local Server”Bạn có thể gọi một agent đang chạy locally sử dụng phương thức factory .local từ client factory.
Bạn có thể, ví dụ, tạo một file có tên scripts/test.ts trong workspace của bạn để import client:
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 });Gọi Agent đã triển khai
Phần tiêu đề “Gọi Agent đã triển khai”Để gọi Agent của bạn đã triển khai lên Bedrock AgentCore Runtime, bạn có thể gửi một yêu cầu POST đến điểm cuối dataplane của Bedrock AgentCore Runtime với ARN runtime đã được mã hóa URL.
Bạn có thể lấy ARN runtime từ cơ sở hạ tầng của mình như sau:
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, }); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"}
output "agent_arn" { value = module.my_project_agent.agent_core_runtime_arn}ARN sẽ có định dạng như sau: arn:aws:bedrock-agentcore:<region>:<account>:runtime/<agent-runtime-id>.
Sau đó, bạn có thể mã hóa URL cho ARN bằng cách thay thế : bằng %3A và / bằng %2F.
URL dataplane của Bedrock AgentCore Runtime để gọi agent như sau:
https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocationsCách chính xác để gọi URL này phụ thuộc vào phương thức xác thực được sử dụng.
NodeJS
Phần tiêu đề “NodeJS”File client.ts được tạo ra bao gồm một client factory type-safe có thể được sử dụng để gọi agent đã triển khai của bạn.
Xác thực IAM
Phần tiêu đề “Xác thực IAM”Bạn có thể gọi agent đã triển khai của bạn bằng cách truyền ARN của nó vào phương thức factory withIamAuth:
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'),});Xác thực JWT / Cognito
Phần tiêu đề “Xác thực JWT / Cognito”Sử dụng phương thức factory withJwtAuth để xác thực với 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,});accessTokenProvider phải trả về token được sử dụng để xác thực request. Bạn có thể, ví dụ, lấy token trong phương thức này để đảm bảo rằng credential mới được tái sử dụng khi tRPC khởi động lại kết nối WebSocket. Ví dụ dưới đây cho thấy việc sử dụng AWS SDK để lấy token từ 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!; },});Browser
Phần tiêu đề “Browser”WebSocket trong trình duyệt không hỗ trợ chỉ định header (ngoại trừ Sec-WebSocket-Protocol), và do đó client factory được tạo ra trong client.ts không thể được sử dụng trong trình duyệt (điều này thực sự sẽ dẫn đến lỗi biên dịch vì constructor WebSocket không chấp nhận header như nó làm trong NodeJS).
Xác thực JWT / Cognito
Phần tiêu đề “Xác thực JWT / Cognito”Xác thực IAM
Phần tiêu đề “Xác thực IAM”Để gọi agent của bạn từ trình duyệt, bạn cần tạo một presigned WebSocket URL sử dụng AWS SigV4.
Ví dụ dưới đây cho thấy luồng end-to-end của việc lấy credential, tạo presigned URL, và gọi agent:
import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';import { AwsClient } from 'aws4fetch';import { CognitoIdentityClient } from '@aws-sdk/client-cognito-identity';import { fromCognitoIdentityPool } from '@aws-sdk/credential-provider-cognito-identity';import type { AppRouter } from './your-agent/router';
// Build a presigned WebSocket URLasync function buildSignedUrl( agentRuntimeArn: string, idToken: string, region: string = 'us-west-2'): Promise<string> { // Get credentials from a Cognito Identity Pool (or other source) const credentials = fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region }), identityPoolId: 'us-west-2:xxxxx', logins: { [`cognito-idp.${region}.amazonaws.com/us-west-2_xxxxx`]: idToken, }, });
const cognitoIdentity = new CognitoIdentityClient({ credentials }); const credential = await cognitoIdentity.config.credentials();
// Create AWS SigV4 client const awsClient = new AwsClient({ ...credential, service: 'bedrock-agentcore', });
// Build WebSocket URL from ARN const wsUrl = `wss://bedrock-agentcore.${region}.amazonaws.com/runtimes/${agentRuntimeArn.replace(/:/g, '%3A').replace(/\//g, '%2F')}/ws`;
// Create presigned URL const signedRequest = await awsClient.sign(wsUrl, { method: 'GET', aws: { signQuery: true }, });
return signedRequest.url;}
// Create tRPC client with presigned WebSocket URLconst agentRuntimeArn = 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent';const idToken = '<your-id-token>';
const wsClient = createWSClient({ url: async () => buildSignedUrl(agentRuntimeArn, idToken),});
const trpcClient = createTRPCClient<AppRouter>({ links: [wsLink({ client: wsClient })],});
// Invoke the agenttrpcClient.invoke.subscribe({ message: 'what is 1 plus 1?' }, { onData: (message) => console.log(message),});