Manage the integration
The stack's dashboard shows tool calls through its gateway, including targets you
add: the 10 busiest tools, overall success and latency. Of its alarms, only
Tool calls failing (ToolCallsFailingAlarm) covers
added targets.
Monitor the integration
Each stack creates a CloudWatch dashboard, named
,
that shows whether agents' tool calls work. Open it from the stack's
stack-name-region-healthHealthDashboardUrl output. Its first line names the stack's template
version and points to Upgrade the template.
The following image shows the dashboard's Contacts and agent experience and System health widgets over six hours of test contacts.
The dashboard has three parts, from top to bottom:
-
Contacts and agent experience: the chats and voice calls on the instance and the account lookups the guide made, as totals and per minute; Tool calls succeeding (%); and the end-to-end tool-call latency (average, tm90, tm95 and tm99, the average of the fastest 90, 95 and 99 percent of calls).
-
System health, for the gateway, Salesforce and the token refresh: Salesforce token refreshes: succeeding (%) and sign-ins, Consumer secret: days since it last changed and Salesforce API allowance left (%), then tool calls per second for all tools and the 10 busiest, the gateway's errors as a share of tool calls, the time Salesforce takes for the 10 slowest tools, the daily allowance used, and Salesforce sign-ins per hour. A text panel says what to do when a tile reads low. The token refresh function reads the allowance every five minutes.
-
Alarms: the stack's four alarms.
Operations or targets you add appear without a change. If the allowance tile
shows no data, check the token refresh function's log for Salesforce API
usage call failed. To print the function's log group, expand this block, copy it, and paste it at the prompt; it asks for the Region and the stack name:
( R=${AWS_REGION:-us-east-1} printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R} printf 'Stack name [connect-sf-real-time]: '; read -r STACK; STACK=${STACK:-connect-sf-real-time} aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" --query 'Stacks[0].StackStatus' --output text > /dev/null \ || { echo "No stack named $STACK in $REGION. Check the stack name and the Region."; exit 1; } out() { aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" \ --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue | [0]" --output text; } aws lambda get-function-configuration --region "$REGION" --function-name "$(out TokenRefreshFunctionName)" \ --query LoggingConfig.LogGroup --output text )
Four alarms publish to the change-alert topic, the ChangeAlertTopicArn
output. The topic also gets alerts for changes to
other gateways and applications in the account and Region, so filter them before you
send it to a pager.
-
Tool calls failing: more than 5 percent of tool calls failed in three five-minute periods in a row, each with at least 20 calls. The guide reads the account view in one
compositecall, and a step of it that Salesforce refuses still counts as a successful call, so this alarm doesn't count a failed account read. -
Salesforce API allowance: the org has used more than 90 percent of its daily API allocation. For what happens when your org reaches its allocation, see API Request Limits and Allocations
in the Salesforce documentation. -
Token refresh: the token refresh failed in two five-minute periods in a row, so the stack can't sign in to Salesforce.
-
Run As user changed: a token refresh got a token for a Run As user other than the one the last deployment recorded. Every tool call runs as that other user. What to do:
If you didn't change the External Client App's Run As user, change it back in Salesforce.
If you did, update the stack with Optional: integration username (Run As user) set to the new user's username. An update that changes a Salesforce setting records the new user. That update raises the alarm once more, because it records a different user, and the alarm then clears.
With the integration username set, the stack stores no token for the other user, and tool calls fail once the stored token expires.
To subscribe to alerts
-
Subscribe a team email address to the topic. In the Amazon SNS console, open the topic from the
ChangeAlertTopicArnoutput and choose Create subscription, Email. Or expand the block that follows, copy it, and paste it at the prompt; it asks for the Region, the stack name and the email address:
( R=${AWS_REGION:-us-east-1} printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R} printf 'Stack name [connect-sf-real-time]: '; read -r STACK; STACK=${STACK:-connect-sf-real-time} aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" --query 'Stacks[0].StackStatus' --output text > /dev/null \ || { echo "No stack named $STACK in $REGION. Check the stack name and the Region."; exit 1; } out() { aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" \ --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue | [0]" --output text; } printf 'Team email address for alerts: '; read -r EMAIL [ -n "$EMAIL" ] || { echo "No email address entered; nothing was subscribed."; exit 1; } TOPIC=$(out ChangeAlertTopicArn) || exit 1 aws sns subscribe --region "$REGION" --protocol email --topic-arn "$TOPIC" \ --notification-endpoint "$EMAIL" --query SubscriptionArn --output text )
It prints pending confirmation.
To finish subscribing
-
Confirm the subscription from the email that arrives.
-
Run the command in the stack's
VerifyTrailoutput. If it lists no trail, the stack sends no change alerts. See CloudFormation template reference.
Each stack's dashboard, its four alarms and the token refresh function's custom
metrics are CloudWatch resources; see Amazon CloudWatch
pricing
Rotate the credentials
The stack keeps no copy of the Salesforce consumer secret. Its token refresh function reads your Secrets Manager secret every five minutes. A stack update doesn't rotate the secret.
-
Create a new secret in your system, for example a new consumer secret on the Salesforce External Client App. Don't revoke the old secret until a test chat works with the new one.
-
Store the new secret where the integration reads it:
-
Salesforce, through the stack: put the new value in your Secrets Manager secret, under the same key, and then run the token refresh function so it gets a token with the new value at once. The function's name is the stack's
TokenRefreshFunctionNameoutput. Expand The secret rotation script after these steps, copy it, and paste it at the prompt. It asks for the Region, the stack name and the new consumer secret, reads the secret's ARN and the function's name from the stack, keeps the secret's other keys, and never puts the secret on screen or on the command line: -
Another system with the client secret in AgentCore Identity: update its OAuth client, as the next step describes.
-
Another system with Provide Client secret via Secrets Manager: put the new value in that secret. Then, in the AgentCore Identity console, open the OAuth client, choose Edit, keep the same secret reference, and choose Save. Don't use the script in the next step for this client: it stores the secret in the OAuth client itself.
-
Another system with an API key: update the API key in AgentCore Identity, and skip the next step. At the prompt, paste this block; it asks for the Region, the credential provider's name and the new key, which it doesn't show, and prints the provider's name when it's done. It needs
bedrock-agentcore:UpdateApiKeyCredentialProvideron the provider,arn:aws:bedrock-agentcore:, and on its token vault,region:account:token-vault/vault-id/apikeycredentialprovider/namearn:aws:bedrock-agentcore:, andregion:account:token-vault/vault-idsecretsmanager:PutSecretValueon the secret AgentCore Identity keeps the key in:( umask 077; D=$(mktemp -d); trap 'rm -rf "$D"' EXIT R=${AWS_REGION:-us-east-1} printf 'Region of the gateway [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R} printf 'API key credential provider name [my-system-api-key]: '; read -r NAME; NAME=${NAME:-my-system-api-key} printf 'New API key (input hidden: paste and press Enter): '; read -rs KEY; echo printf '%s' "$KEY" > "$D/key"; unset KEY [ -s "$D/key" ] || { echo "No key entered; nothing changed."; exit 1; } aws bedrock-agentcore-control update-api-key-credential-provider --region "$REGION" --name "$NAME" \ --api-key "file://$D/key" --query name --output text )
-
-
For another system with its client secret in AgentCore Identity only: update its OAuth client with the AWS CLI. Skip this step for Salesforce. Expand The script that updates the OAuth client's secret after these steps, copy it, and paste it at the prompt. It asks for the Region, the OAuth client's name and the new client secret, keeps the client's discovery settings and client ID, and sends the new secret from a file that only you can read:
-
Start a test chat, or place a test call and choose Search for the caller's number, to confirm the guide still reads your records, and then revoke the old secret in your system. If the old secret might have leaked, also end the integration user's sessions in Salesforce, and then run the token refresh function immediately.
-
After you revoke the old secret, run the token refresh function again, or wait five minutes, and test again with a chat or a call. If it fails, store the secret again with the right value.
( umask 077; D=$(mktemp -d); trap 'rm -rf "$D"' EXIT R=${AWS_REGION:-us-east-1} printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R} printf 'Stack name [connect-sf-real-time]: '; read -r STACK; STACK=${STACK:-connect-sf-real-time} aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" --query 'Stacks[0].StackStatus' --output text > /dev/null \ || { echo "No stack named $STACK in $REGION. Check the stack name and the Region."; exit 1; } out() { aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" \ --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue | [0]" --output text; } SECRET_ARN=$(aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" \ --query "Stacks[0].Parameters[?ParameterKey=='SalesforceClientSecretArn'].ParameterValue | [0]" --output text) || exit 1 FUNCTION=$(out TokenRefreshFunctionName) printf 'New consumer secret (input hidden: paste and press Enter): '; read -rs SF_SECRET; echo printf '%s' "$SF_SECRET" > "$D/secret"; unset SF_SECRET [ -s "$D/secret" ] || { echo "No secret entered; nothing changed."; exit 1; } aws secretsmanager get-secret-value --region "$REGION" --secret-id "$SECRET_ARN" \ --query SecretString --output text > "$D/stored.json" || exit 1 python3 -I - "$D" <<'PY' || exit 1 import json, sys d = sys.argv[1] value = json.load(open(d + "/stored.json")) key = "consumerSecret" if "consumerSecret" in value and "clientSecret" not in value else "clientSecret" value[key] = open(d + "/secret").read().strip() json.dump(value, open(d + "/value.json", "w")) PY aws secretsmanager put-secret-value --region "$REGION" --secret-id "$SECRET_ARN" \ --secret-string "file://$D/value.json" > /dev/null || exit 1 aws lambda invoke --region "$REGION" --function-name "$FUNCTION" "$D/out.json" > /dev/null || exit 1 python3 -I - "$D/out.json" <<'PY' import json, sys r = json.load(open(sys.argv[1])) if isinstance(r, dict) and r.get("token") in ("updated", "unchanged"): print("OK: the secret is stored and the stack got a Salesforce token with it.") else: print("FAILED: the secret is stored, but the token refresh failed: %s" % (r.get("errorMessage") if isinstance(r, dict) else r)) PY )
It prints OK: the secret is stored and the stack got a
Salesforce token with it. If it prints
FAILED:, the new secret is stored but Salesforce
refused it; check the value and run the block again.
The function reads the key clientSecret, or
consumerSecret for a secret in the Secrets Manager
Salesforce format. If the refresh
fails, the output names Salesforce's error code. The person
who rotates needs secretsmanager:GetSecretValue and
secretsmanager:PutSecretValue on your secret, and
lambda:InvokeFunction on the token refresh
function.
( umask 077; D=$(mktemp -d); trap 'rm -rf "$D"' EXIT R=${AWS_REGION:-us-east-1} printf 'Region of the gateway [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R} printf 'OAuth client name [my-system-oauth]: '; read -r NAME; NAME=${NAME:-my-system-oauth} aws bedrock-agentcore-control get-oauth2-credential-provider --region "$REGION" --name "$NAME" \ --query oauth2ProviderConfigOutput.customOauth2ProviderConfig --output json > "$D/current.json" || exit 1 printf 'New client secret (input hidden: paste and press Enter): '; read -rs SYSTEM_SECRET; echo printf '%s' "$SYSTEM_SECRET" > "$D/secret"; unset SYSTEM_SECRET [ -s "$D/secret" ] || { echo "No secret entered; nothing changed."; exit 1; } python3 -I - "$D" "$NAME" <<'PY' || exit 1 import json, sys d, name = sys.argv[1:] current = json.load(open(d + "/current.json")) config = {"oauthDiscovery": current["oauthDiscovery"], "clientId": current["clientId"], "clientSecret": open(d + "/secret").read().strip()} json.dump({"name": name, "credentialProviderVendor": "CustomOauth2", "oauth2ProviderConfigInput": {"customOauth2ProviderConfig": config}}, open(d + "/input.json", "w")) PY aws bedrock-agentcore-control update-oauth2-credential-provider --region "$REGION" \ --cli-input-json "file://$D/input.json" > /dev/null && echo "Updated the client secret of $NAME." )
The update replaces the whole configuration; an update without the client secret removes the stored secret.
The person who rotates needs:
-
bedrock-agentcore:GetTokenVaultontoken-vault/default. -
bedrock-agentcore:GetOauth2CredentialProviderandbedrock-agentcore:UpdateOauth2CredentialProviderontoken-vault/defaultandtoken-vault/default/oauth2credentialprovider/.oauth-client-name -
secretsmanager:PutSecretValueon the secret the gateway holds,bedrock-agentcore-identity!default/oauth2/.oauth-client-name-????????-??????
Stop the integration immediately
To stop every call to a connected system, use one of the following:
-
Disable the integration user's credentials that the gateway uses. In Salesforce, freeze the integration user or revoke the External Client App's access. To make calls fail at once, also end the integration user's sessions.
-
Stop starting the guide: remove the Set event flow block for the guide from your inbound flows and publish them. Contacts already in progress keep their guide. AI agents that have the gateway's tools can still call them, so remove the tools from those AI agents too.
-
Remove the integration, as in the next procedure, or delete the stack.
Re-enable the credentials, or publish the inbound flows again, to resume.
Remove the integration
To remove the stack
-
Remove the Set event flow blocks for the guide and the wrap-up from your inbound flows, and the Transfer to flow blocks that send contacts to the AI self-service flow, and publish them.
-
If you did the AI console steps, run the console steps script with
remove, as in Finish the AI setup after each create or update. Otherwise the delete fails on the AI agents' security profiles. -
If you added the stack's
security profile to agents, remove it from them in Users, User management. Otherwise the delete fails withstack-name-ai-agent-assist-toolsDELETE_FAILEDon that security profile; then remove it and delete again. -
Delete the stack. The delete keeps a Connect assistant that the stack created; delete it in the console if no other flow uses it.
-
Delete the consumer secret that you stored in Secrets Manager, and, if you created a staging bucket only for this stack, empty and delete it. Expand the block that follows, copy it, and paste it at the prompt; it asks for the Region, the secret's name or ARN and the bucket, which you can leave empty, then asks you to confirm; type
yesto delete:
( R=${AWS_REGION:-us-east-1} printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R} printf 'Secret name or ARN [connect-sf-real-time/client]: '; read -r SECRET; SECRET=${SECRET:-connect-sf-real-time/client} printf 'Staging bucket to empty and delete, or Enter for none []: '; read -r BUCKET printf 'Delete the secret %s%s? yes or no [no]: ' "$SECRET" "${BUCKET:+ and empty and delete the bucket $BUCKET}"; read -r OK [ "$OK" = yes ] || { echo "Nothing was deleted."; exit 0; } aws secretsmanager delete-secret --region "$REGION" --secret-id "$SECRET" \ --query 'join(``, [`Deleted `, Name, `; you can restore it until `, to_string(DeletionDate)])' --output text || exit 1 [ -z "$BUCKET" ] || aws s3 rb --region "$REGION" "s3://$BUCKET" --force )
The script prints the date until which you can restore the secret; see Delete an AWS Secrets Manager secret.
To remove the test agent
-
If you created the test agent with the test setup script in Step 1, run it again, as in Create the test agent and its Modern layout. Enter
removeat the second prompt, accept the instance, enter or accept the username you used, and typeyesto confirm. It deletes the workspacertdi-modern, the test agent's user, the security profilertdi-test-agent, the routing profilertdi-test-routingand the queuertdi-test-queue. It deletes only resources that it created.It is done when it prints
DONE, after aDeletedorSkippedline for each resource. AFailedline means that resource is still there. If the script printsNOT DONEwith a count, fix the error that the AWS CLI printed above eachFailedline, and run the script withremoveagain. If you created the test agent in the admin website, delete those resources there.
To remove the Salesforce access
-
In Salesforce, delete the External Client App in Setup: in External Client App Manager, open the app, and choose Delete in the menu next to Disable. Then delete the integration user's permission set assignment and, if no other stack's user has the permission set, the permission set, remove any permission set license assignment you gave the user, and deactivate the integration user.
The following removal script does all of this in one run, and changes nothing if any part fails. Run it the way you ran the setup script: in the Developer Console's Execute Anonymous window with Debug Only selected in the log, or by saving it as
integration-user-remove.apexand running the block after it with the Salesforce CLI. Setusername,psNameandpermissionSetLicenseto the values you used in the setup script; the script removes only that permission set license assignment. It keeps the permission set if another user still has it. SetdeactivateUsertofalsefor a user you reused throughreuseExistingUser, or one that other integrations use, so the user stays active:
// Real-time data integration with Agent workspace: removes the access the setup script gave the integration user, // and deactivates the user. It changes nothing unless every step succeeds. String username = 'connect-integration@yourcompany.com'; // the integration user's username String psName = 'Connect_Real_Time_Data_Integration'; // the permission set the setup script created String permissionSetLicense = ''; // the permissionSetLicense value you gave the setup script, if any Boolean deactivateUser = true; // false for a user you reused or that other integrations use // Every line the script prints starts with LDI. void say(String line) { System.debug(LoggingLevel.ERROR, 'LDI' + ' ' + line); } if (username.contains('yourcompany.com')) { say('STOPPED: nothing was changed. Set username at the top of the script to the integration user\'s username, and run it again.'); return; } List<String> progress = new List<String>(); Savepoint sp = Database.setSavepoint(); try { List<User> users = [SELECT Id, IsActive FROM User WHERE Username = :username]; List<PermissionSet> sets = [SELECT Id FROM PermissionSet WHERE Name = :psName]; if (users.isEmpty()) progress.add('No user named ' + username + '.'); if (sets.isEmpty()) progress.add('No permission set named ' + psName + '.'); if (!users.isEmpty() && !sets.isEmpty()) { List<PermissionSetAssignment> mine = [SELECT Id FROM PermissionSetAssignment WHERE AssigneeId = :users[0].Id AND PermissionSetId = :sets[0].Id]; delete mine; progress.add('Removed ' + mine.size() + ' assignment of ' + psName + ' from ' + username + '.'); } if (!sets.isEmpty()) { Integer others = [SELECT COUNT() FROM PermissionSetAssignment WHERE PermissionSetId = :sets[0].Id]; if (others == 0) { delete sets[0]; progress.add('Deleted the permission set ' + psName + '.'); } else progress.add('Kept the permission set ' + psName + ': ' + others + ' other users still have it.'); } if (!users.isEmpty()) { if (!String.isBlank(permissionSetLicense)) { List<PermissionSetLicenseAssign> licenses = [SELECT Id FROM PermissionSetLicenseAssign WHERE AssigneeId = :users[0].Id AND (PermissionSetLicense.MasterLabel = :permissionSetLicense OR PermissionSetLicense.DeveloperName = :permissionSetLicense)]; delete licenses; progress.add('Removed ' + licenses.size() + ' assignment of the permission set license ' + permissionSetLicense + ' from ' + username + '.'); } if (deactivateUser) { if (users[0].IsActive) { users[0].IsActive = false; update users[0]; } progress.add('Deactivated ' + username + '.'); } else { progress.add('Kept ' + username + ' active, because deactivateUser is false.'); } } for (String line : progress) say(line); say('DONE'); } catch (Exception e) { Database.rollback(sp); say('STOPPED: nothing was changed. Salesforce returned: ' + e.getMessage()); }
With the Salesforce CLI, run this block in the folder where you saved it:
( sf apex run --file integration-user-remove.apex > integration-user-remove.log 2>&1 if grep -q 'LDI ' integration-user-remove.log; then grep -o 'LDI .*' integration-user-remove.log else echo "The script printed no LDI lines. Salesforce reported:" grep -v '^Execute Anonymous:' integration-user-remove.log | grep -iE -A2 'error|exception' | head -20 fi )
It ends with DONE, after one line for each change. If it
prints STOPPED: nothing was changed, the message names what
Salesforce refused.
Also delete the test accounts, contacts, cases and case comments you created while testing.
To remove a system you added
-
Before you delete the stack, delete the targets and the OAuth clients or API keys you added. The stack can't delete a gateway that still has targets it didn't create.
-
Deactivate the API credentials and the integration user in that system.