I built a Nova Sonic phone agent twice: first with the AWS CLI, then with one cdk deploy

In June I deployed an Amazon Connect voice agent with Nova 2 Sonic and MCP tools mostly through CLI commands, and in November it became one cdk deploy. Lessons on AgentCore Gateway auth, Lambda cold starts on live calls, and tool validation that keeps a speech model from inventing orders.

AI Engineering | Cloud Architecture | AWS Solutions Architect
In June I built my first voice agent on Amazon Connect. A caller phones a pizza line, talks to Amazon Nova 2 Sonic in Chilean Spanish, and the agent takes the order by calling three tools over MCP. I wanted the whole thing in CDK, with one command to deploy it and one to tear it down.
That isn't what happened. On  aws-cdk-lib  2.200.1, the first  cdk deploy  failed on the AI prompt with "Prompt is not in expected YAML format". Then the gateway target failed with "extraneous key [Lambda] is not permitted", because the CloudFormation schema for  GatewayTarget  only accepted OpenAPI and Smithy targets back then. I commented out both constructs, opened a terminal, and started a runbook. The runbook ended up being the real deployment, and the CDK app only laid the groundwork.
In November I rebuilt it. CDK 2.277.0 had caught up, and everything I had typed by hand fits in one  cdk deploy . This post is about both builds: what the CLI version taught me, why MCP was worth the trouble, the latency work that made the agent sound like a person on the phone, and the validation that keeps a speech model from inventing pizzas.
The rebuilt version is public, with a fictional brand (Forno Pizza):  https://github.com/marcosferr/connect-nova-sonic-voice-agent 

What the CLI version looked like

The runbook from June has a step for every piece that CloudFormation couldn't do yet. Nova Sonic on the Lex bot was one of them:
aws lexv2-models update-bot-locale --bot-id $BOT --bot-version DRAFT --locale-id es_US \
--nlu-intent-confidence-threshold 0.4 \
--unified-speech-settings '{"speechFoundationModel":{"modelArn":"arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-2-sonic-v1:0","voiceId":"Lupe"}}'
aws lexv2-models build-bot-locale --bot-id $BOT --bot-version DRAFT --locale-id es_US
# then re-create the bot version and repoint the alias
That locale says  es_US  because my first attempt was  es_419 , the Latin American Spanish locale, and Lex answered "Speech to Speech is not supported in locale es_419". The Spanish Nova Sonic voice, Lupe, only exists on  es_US . And if you pass  voiceSettings  together with  unifiedSpeechSettings , Lex refuses that too, because the speech-to-speech model replaces the Polly voice.
The orchestration prompt had to be YAML wrapped inside a JSON string inside a shell argument, so I let Python do the escaping:
YAML=$(python -c "import json;print(json.dumps(open('prompts/orchestration.yaml',encoding='utf-8').read()))")
aws qconnect create-ai-prompt --assistant-id $ASSIST \
--name orchestrator-sonic-v1 --type ORCHESTRATION --api-format MESSAGES \
--model-id us.amazon.nova-pro-v1:0 --template-type TEXT --visibility-status PUBLISHED \
--template-configuration "{\"textFullAIPromptEditTemplateConfiguration\":{\"text\":$YAML}}"
The YAML itself has a strict shape: a  system:  block, then a  messages:  list whose only element is  "{{$.conversationHistory}}" . Anything else fails with a message that tells you exactly that, which made it one of the friendlier errors.
 create-ai-agent  failed next with "Assistant does not associate with Connect instance", because the Q in Connect assistant needs a  WISDOM_ASSISTANT  integration association with the instance first. A failed stack rollback also left an orphan Connect instance in  ACTIVE , so the next deploy said "Instance alias is already used" until I deleted it by hand and waited for  list-instances  to come back empty.
None of these were hard once I knew the answer. The cost was that every one of them lived in a markdown file, outside the stack, and drifted from what CDK thought it had deployed.

MCP: the day the agent had zero tools

The tools are three Python Lambdas:  validate_customer ,  get_menu  and  create_order . I put them behind Amazon Bedrock AgentCore Gateway as MCP targets, so the Connect AI agent could discover and call them over MCP. The gateway authenticates the agent with a JWT that Connect itself mints.
When I configured the gateway's JWT authorizer, I set  allowedAudience  to the gateway id. It's the obvious choice and CloudFormation accepted it. Then I registered the gateway in Connect as an MCP server, opened the AI agent designer, and saw zero tools. No error, no log line, just an empty list.
On June 4 I found the cause: Connect's token doesn't carry the gateway id as its audience, so the gateway rejected every request and Connect quietly listed nothing. The fix is to validate the issuer, which is the Connect instance URL:
authorizerConfiguration: {
customJwtAuthorizer: {
discoveryUrl: props.jwtDiscoveryUrl,
customClaims: [{
inboundTokenClaimName: 'iss',
inboundTokenClaimValueType: 'STRING',
authorizingClaimMatchValue: {
claimMatchOperator: 'EQUALS',
claimMatchValue: { matchValueString: props.jwtIssuer },
},
}],
},
},
Attaching the tools to the agent was the other wall. I tried  update-ai-agent  with the gateway target ARN as the tool id and got:
ValidationException: MCP tool with ID 'arn:aws:bedrock-agentcore:…:gateway/…/target/…' not found in MCP tools
Connect keeps its own registry of MCP tools. To fill it, you register the gateway as an MCP server and then pick the tools in the AI agent designer, in the console. Registering from the CLI needed AWS CLI 2.34 or later, because the 2.32 model for  appintegrations  had no MCP application type. Once the gateway was registered, the ids turned out to follow a pattern:
  • the agent's tool id is  gateway_<gatewayId>__<target>___<tool>  (two underscores, then three)
  • the security profile permission is  <target>___<tool> , under an application whose namespace is the gateway id
Knowing that pattern is what later let me put the whole thing in CloudFormation.
With all of that, MCP was still the right call. The tools are plain Lambdas with JSON schemas, behind a gateway that only accepts tokens from my Connect instance. I can test them with  aws lambda invoke , change one without touching the agent, and the same gateway could serve another agent later. Without a valid token the gateway answers  401 , which I checked both with no token and with one I signed myself.

Latency: silence sounds like a dropped call

When the agent calls a tool, the caller hears nothing until the tool answers. In a chat UI a slow tool shows a spinner. On a phone, two seconds of silence makes people say "hello?" and start talking over the agent.
In the first version, tool calls over MCP took 2 to 4 seconds. A single order can touch all three tools, and each one is a separate function that can be cold on its own. Provisioned concurrency brought those calls down to 200 to 400 milliseconds.
When I rebuilt it, I measured the Lambda part on its own to see whether something cheaper would do. These are the deployed tools (Python 3.12, arm64, us-east-1):
Config
Cold penalty
Warm
256 MB
init 0.38-0.50 s, plus ~0.17 s on the first DynamoDB call
10-15 ms
512 / 1024 MB
init 0.48-0.49 s
8-9 ms
SnapStart
restore 0.46 s
19 ms
Provisioned concurrency (1)
none
10 ms
More memory and SnapStart made no difference, because these handlers have almost nothing to initialize. Provisioned concurrency was the only setting that removed the cold start. One instance at 256 MB costs a few dollars a month per function.
You also need fewer provisioned instances than the call volume suggests. A tool runs for milliseconds inside a conversation turn of several seconds, so even a busy line keeps only a handful of executions in flight. In the repo it's one setting:
TOOL_WARM_MODE=provisioned
TOOL_PROVISIONED_CONCURRENCY=1
Everything that calls a tool (the gateway targets, the Lambda permissions, the contact flow) goes through a  live  alias, so switching warm modes doesn't change any ARN that another stack depends on. If your traffic follows business hours, scheduled scaling plus target tracking on  ProvisionedConcurrencyUtilization  keeps the bill in line with the calls.

Making a speech model safe to take orders

A speech-to-speech model hears background noise and mumbled numbers, and it wants to please the caller. I wrote rules against that in the prompt, but the rules that hold are the ones the tools enforce. The model proposes an action, and the server checks it before anything is written.
The caller's identity never comes from the model. Connect knows the number from the phone network ( $.CustomerEndpoint.Address ). The contact flow passes it to a small Lambda that writes it into the Q in Connect session, and the prompt reads it as a variable:
TRUSTED CALL DATA (does not come from the caller; use it as is):
- Call phone number: {{$.Custom.customer_phone}}
- contactId: {{$.contactId}} → ALWAYS pass it as create_order.contactId (prevents duplicate orders).
Every tool returns errors in the same shape, and the  suggestedAction  field is written for the model to read:
{
"status": "error",
"code": "PIZZA_NOT_ON_MENU",
"message": "'bbq-chicken' is not on the menu.",
"suggestedAction": "Do not invent it or accept it: offer a pizza from 'catalog' and confirm the choice before retrying.",
"catalog": [
{"pizzaId": "muzzarella", "name": "Muzzarella", "price": 7990},
{"pizzaId": "napolitana", "name": "Napolitana", "price": 8990},
{"pizzaId": "hawaiana", "name": "Hawaiana", "price": 9490}
]
}
(The real response lists every active pizza; I trimmed it here.) When a caller asks for something off the menu, the agent gets the real catalog in the same response and can offer an alternative without another round trip. Without guidance, a model that gets an error tends to improvise: it apologizes and ends the call, retries with the same bad input, or carries on as if the order went through. With  suggestedAction  it asks the caller one clear question and tries again.
The other checks follow the same idea.  validate_customer  normalizes spoken phone numbers to E.164 and refuses anything that isn't plausible.  create_order  only accepts integer quantities from 1 to 10, so "dos" comes back as  INVALID_QUANTITY . It computes the total from the prices in DynamoDB, and the prompt tells the agent to read back that number and never its own arithmetic.
Retries were the last gap. If a tool call times out, the model calls it again, and the store gets two orders.  create_order  derives the order id from the contact and the order contents, and writes it with a conditional put:
signature = json.dumps(sorted((l["pizzaId"], l["quantity"]) for l in lines))
order_id = str(uuid.uuid5(_NS, f"{contact_id}|{signature}")) if contact_id else str(uuid.uuid4())

orders.put_item(
Item=order,
ConditionExpression="attribute_not_exists(orderId)",
ReturnValuesOnConditionCheckFailure="ALL_OLD",
)
A second identical call returns  "status": "duplicate"  and leaves one row in the table, which I checked against the deployed stack. The trade-off is that a caller who really wants the same order twice in one call gets it once. For a pizza line I'm fine with that.

November: the same agent in one cdk deploy

By November,  aws-cdk-lib  2.277.0 had L1 constructs for everything I had done by hand, and I rewrote the stack. This is the June runbook next to what replaced each step:
June (CLI or console after deploy)
November (CloudFormation)
 create-gateway-target  per tool +  lambda add-permission 
 AWS::BedrockAgentCore::GatewayTarget  ( Mcp.Lambda ) +  AWS::Lambda::Permission 
 update-gateway  to set the  iss  authorizer, drifting from CDK
 CustomJWTAuthorizer.CustomClaims  on  AWS::BedrockAgentCore::Gateway 
OIDC discovery URL copied into  .env  after Connect existed (two-phase deploy)
Derived from the instance alias, which is deterministic
 update-bot-locale --unified-speech-settings 
 BotLocale.UnifiedSpeechSettings  on  AWS::Lex::Bot 
 create-ai-prompt ,  create-ai-agent ,  create-ai-agent-version 
 AWS::Wisdom::AIPrompt ,  AIAgent ,  AIAgentVersion 
 create-integration-association WISDOM_ASSISTANT 
 AWS::Connect::IntegrationAssociation 
Register the MCP server (console, or CLI 2.34+)
 AWS::AppIntegrations::Application  ( MCP_SERVER ) + an  APPLICATION  association
Add tools in the AI agent designer and grant them in a security profile (console)
 ToolConfigurations  ( MODEL_CONTEXT_PROTOCOL ) +  AWS::Connect::SecurityProfile  with an MCP application
Contact flow built by hand in the console
 AWS::Connect::ContactFlow  with ARNs injected through  Fn::Sub 
 update-instance-attribute OUTBOUND_CALLS 
 Attributes.OutboundCalls: true 
The discovery URL change removed my least favorite step. The gateway needs Connect's OIDC URL, and in June that meant deploying Connect, copying the URL into  .env , and deploying again. The URL is built from the instance alias ( https://<alias>.my.connect.aws ), and I choose the alias, so CDK can compute it before the instance exists.
The tool wiring is now plain code, using the id pattern from June:
toolConfigurations: tools.map((t) => ({
toolName: t.toolName,
toolType: 'MODEL_CONTEXT_PROTOCOL',
toolId: t.toolId, // gateway_<gatewayId>__create-order___create_order
})),
The agent has to be created after the  MCP_SERVER  association exists, or Connect can't resolve those ids. The stack declares that dependency explicitly.
Lex needed one more trick.  AWS::Lex::BotVersion  only snapshots the DRAFT when it's created, so changing the locale configuration didn't produce a new version. The repo puts a hash of the locale configuration in the version description, so any change creates a new version and repoints the alias.
Two calls still have no CloudFormation resource: attaching the security profile to the AI agent ( connect:AssociateSecurityProfiles  with  EntityType=AI_AGENT ) and associating a phone number with a flow. Both run as  AwsCustomResource , the first with  installLatestAwsSdk: true  because  AI_AGENT  is newer than the SDK in the Lambda runtime. If you'd also like a native resource for the first one, I opened a  wishlist item  and votes help.

Testing it without picking up a phone

The validation runs before any DynamoDB access, so the guards have offline unit tests ( python -m unittest discover -s tests/unit -v ), next to CDK assertions that run in  npm test .
For full calls, the repo includes a synthetic caller that I brought over from another project. It opens  StartWebRTCContact  into the live flow from headless Chrome with the Chime SDK, plays caller clips generated with Polly, and picks the next clip by matching what the bot says. After the call it checks the order row in DynamoDB and the MCP tool calls the agent made, using Q in Connect  ListSpans . The test cases are JSON: one orders two napolitanas and a pepperoni (27,970), and the other asks for a pizza that isn't on the menu and has to end up with a hawaiana (9,490).
My first run of the synthetic caller failed with "Call throttle limit exceeded", and claiming a phone number failed with "The allowed limit for claimed phone numbers has been exceeded for your instance". An account can have an effective limit of zero for both, and you raise them through an AWS Support case. Open it before you schedule a demo.

If you're starting one of these now

  • Check the CloudFormation schema before reaching for the CLI. The Connect, Wisdom, Lex and AgentCore types change fast, and  aws cloudformation describe-type  tells you what your region supports today.
  • Validate  iss  on the AgentCore gateway when Connect is the caller, and leave  allowedAudience  out. The symptom of getting it wrong is an empty tool list with no error.
  • Use  es_US  with the voice Lupe for Nova Sonic in Spanish, and wrap everything the agent says in  <message>  tags, or it stays silent.
  • Measure cold starts on your own tools before paying to fix them. For small handlers, provisioned concurrency was the only thing that changed the number.
  • Put every rule that matters in a tool, return errors with a  suggestedAction , and make every write idempotent.
To try it:
cp .env.example .env # set AWS_ACCOUNT_ID; everything else has defaults
npm ci && npm run build && npm test
npx cdk deploy "Dev/*" # 8 stacks, about 10 minutes
python scripts/seed.py
scripts/teardown.sh # when you're done
You need us-east-1, a bootstrapped CDK environment, and Bedrock model access to Amazon Nova Pro and Amazon Nova 2 Sonic. A test run costs between a few cents and a few dollars, mostly Connect voice minutes and Bedrock tokens.
The repo also has the Claude Code skills I use for call UAT and for tracing which tools the agent called. If you build something similar, I'd like to hear how you handled the tool latency 🧉
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article