View a markdown version of this page

Example: add your own Salesforce operations - Amazon Connect Customer

Example: add your own Salesforce operations

The stack's salesforce target has the following operations. To add your own, describe them in an OpenAPI file, and the stack adds them as a second OpenAPI target. For another system's target, change its OpenAPI document or add a target, as in Connect another system with an API.

The salesforce target of a stack of the template with the account and case guide has the following 28 operations. The gateway-only template's target has 26: all but composite and searchRecords, which only the guide's flows send. Each operation runs as the integration user, so its Salesforce permissions decide what each operation can read or change.

Operations of the stack's salesforce target
Records Operations

Case

getCase, createCase, updateCase, deleteCase and createCaseComment

Account

getAccount, createAccount, updateAccount and queryAccounts, which runs only 13 fixed queries (the 12 that the account and case guide's flows and modules send, and an account read with its five most recent cases, for your own flows) and refuses any other query

Contact

getContact, createContact and updateContact

Any object, including custom objects

getRecord, createRecord, updateRecord and describeObject, which lists an object's fields, including custom fields

The guide's batched requests and search (template with the account and case guide only)

composite, which sends 2 to 6 of the guide's own requests in one call, such as each Create case, each New customer, and each Edit customer or Edit contact save, and refuses any other request. It also accepts Read the account's request from templates 1.0.0 to 1.1.0 (the accountView102 shape), for flows copied from them, through 1.x; and searchRecords, Salesforce's parameterized search of Account, Contact and Case, which the guide's free-text search and New customer's duplicate check send. It accepts spellCorrection only as false; without it, Salesforce corrects the spelling of the search term

Flows and actions

listFlows, describeFlow and runFlow for autolaunched flows; runApexAction for invocable Apex; listStandardActions and runStandardAction for Salesforce's standard actions; listQuickActions and runQuickAction; listApprovals and submitApproval

Every operation of the salesforce target takes domainName, your org's My Domain name, the part of its host before the first dot. The server URL limits it with an enum that holds only your org's name, so a call can't send the token to another host. The same holds for a salesforce-custom file that generate-custom-operations.sh builds, because the script copies the stack's servers. If you write the file yourself or edit servers, keep that enum.

The get operations take a fields list, such as Subject,Status, and return the fields the integration user can read. To write custom fields, use createRecord and updateRecord, or generate typed operations; see Custom fields.

Autolaunched flows let a guide run Salesforce logic in one call and show the result. Common uses:

  • Escalate a case: raise its priority and notify the owner.

  • Log the interaction as a Task linked to the case and contact.

  • Change several related records in one transaction, such as a case and its related records.

  • Look up a value and return it, such as entitlement status or customer tier.

  • Start a Salesforce process, such as an approval or an email to the customer.

For the flow types that runFlow can run, see Flows.

Updates of an account or a contact

The guide's edits and the Update a record module update one account or one contact through composite. Any caller of the gateway can make these updates, as the integration user, within the access your Salesforce administrator gives that user.

  • composite takes an update of one Account or one Contact by Id, and reads of the Account's and a contact's LastModifiedDate. queryAccounts also takes those two reads.

  • An update takes BillingCity and Phone, each up to 40 characters, and names with no minimum length.

  • An update's Email may be empty, which clears it, or hold an apostrophe, such as o'brien@example.com. Create a customer refuses an apostrophe in its email.

  • A Contact update also takes AccountId, which moves the contact to another account, as updateContact allows. The guide and Update a record never send it. To control who can move a contact, your Salesforce administrator sets the integration user's edit access to Contact Account Name.

Add your own Salesforce operations

To add operations the salesforce target doesn't have, describe them in an OpenAPI file in Amazon S3 and set the stack's CustomOperationsS3Uri parameter to the file. The stack adds a second target, salesforce-custom, that reads the file and uses the same Salesforce token. The salesforce target doesn't change, so the account and case guide keeps working. A flow calls your operations as gateway_gateway-id__salesforce-custom___operation.

You can generate the file from your org or write it yourself.

To generate typed operations with your custom fields

The following script writes createObjectWithCustomFields and updateObjectWithCustomFields for each object you name. Their inputs are the object's standard and custom fields, with booleans and numbers typed, so a flow can set Created_By_Connect__c as an input like any other field. The first time, the script uploads the file and updates the stack with CustomOperationsS3Uri. After that, it uploads the new file and updates the salesforce-custom target. The script describes each object as the Salesforce CLI user, so it includes only the fields that this user can access. A call that sets a field the integration user can't edit fails; run the setup script in Step 2 again after you add fields. Run it on your own computer, in bash (on macOS, type bash first). It needs:

  • The Salesforce CLI, signed in to your org.

  • The AWS CLI, signed in to the stack's account, and python3.

  • AWS permissions, which depend on the run:

    • When the stack doesn't read this file yet, the script updates the stack, which creates the salesforce-custom target. If the stack deploys with a deployer role, CloudFormation runs the update as that role. You need the later runs' permissions, plus cloudformation:UpdateStack on the stack; CloudFormation uses the stack's role even if you can't pass it. See UpdateStack in the CloudFormation API Reference. Otherwise, run it as the administrator who deploys the stack.

    • Each later run updates only the target. It needs cloudformation:DescribeStacks, bedrock-agentcore:GetGateway, bedrock-agentcore:GetGatewayTarget, bedrock-agentcore:UpdateGatewayTarget, and s3:PutObject on the file.

It uploads only to a bucket in the stack's account, and ends by checking the gateway's allowed audience, as the VerifyAudience output does. Save the following script as generate-custom-operations.sh, run chmod +x generate-custom-operations.sh, and then run ./generate-custom-operations.sh. It asks for the Salesforce CLI org, the Region, the stack name, the bucket and the objects, such as Case Shipment__c, prints The salesforce-custom target reads and the file's S3 URI, and ends with Gateway audience: and the gateway's ID, followed by (correct):

#!/usr/bin/env bash # Real-time data integration with Agent workspace: builds an OpenAPI file of typed create and update operations # that include your org's custom fields, uploads it to Amazon S3, and points the stack's salesforce-custom target at it. # # For each object you name, it adds create<Object>WithCustomFields and update<Object>WithCustomFields, whose inputs # are every field the Salesforce CLI user can create or update, standard and custom. Run it again after you add fields. # # Run it on your own computer, signed in to the Salesforce CLI and the AWS CLI: ./generate-custom-operations.sh # It asks for each value, with its default in brackets. Needs the Salesforce CLI (sf), the AWS CLI and python3. set -euo pipefail R=${AWS_REGION:-us-east-1} printf 'Salesforce CLI org alias or username [your default org]: '; read -r ORG 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} printf "S3 bucket in the stack's account and Region (with the deployer policy, its STAGING_BUCKET): "; read -r BUCKET [ -n "$BUCKET" ] || { echo "No bucket entered; nothing changed."; exit 1; } printf 'Objects, by API name and separated by spaces [Case]: '; read -r OBJECTS; OBJECTS=${OBJECTS:-Case} ORG_ARG=(); [ -z "$ORG" ] || ORG_ARG=(--target-org "$ORG") KEY=salesforce-custom-operations.json URI="s3://$BUCKET/$KEY" W=$(mktemp -d); trap 'rm -rf "$W"' EXIT out() { aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue | [0]" --output text; } GATEWAY=$(out GatewayId) # The stack's own target: its server URL, and the operation names the custom file must not reuse. aws bedrock-agentcore-control get-gateway-target --region "$REGION" --gateway-identifier "$GATEWAY" \ --target-id "$(out GatewayTargetId)" --query targetConfiguration.mcp.openApiSchema.inlinePayload --output text > "$W/stack.json" for OBJECT in $OBJECTS; do sf sobject describe ${ORG_ARG[@]+"${ORG_ARG[@]}"} --sobject "$OBJECT" --json > "$W/describe-$OBJECT.json" done python3 -I - "$W" "$KEY" $OBJECTS <<'PY' import json, sys w, key, objects = sys.argv[1], sys.argv[2], sys.argv[3:] stack = json.load(open(w + "/stack.json")) def prop(field): # Field types: Salesforce booleans and numbers keep their JSON type; everything else is a string. kind = "boolean" if field["type"] == "boolean" else ( "number" if field["type"] in ("int", "double", "currency", "percent", "long") else "string") return {"description": field["label"], "type": kind} def body(described, flag): fields = {f["name"]: prop(f) for f in described["fields"] if f.get(flag)} return {"required": True, "content": {"application/json": {"schema": {"type": "object", "properties": fields}}}} paths = {} for obj in objects: described = json.load(open("%s/describe-%s.json" % (w, obj)))["result"] name = obj.replace("__", "_") paths["/sobjects/" + obj] = {"post": {"operationId": "create" + name + "WithCustomFields", "description": "Create a %s record, with any of its standard and custom fields." % described["label"], "requestBody": body(described, "createable"), "responses": {"201": {"description": "The new record ID"}}}} paths["/sobjects/" + obj + "/{id}"] = {"patch": {"operationId": "update" + name + "WithCustomFields", "description": "Update a %s record's standard and custom fields." % described["label"], "parameters": [{"name": "id", "in": "path", "required": True, "description": "The record ID", "schema": {"type": "string", "pattern": "^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$"}}], "requestBody": body(described, "updateable"), "responses": {"204": {"description": "Updated"}}}} ours = {op["operationId"] for item in stack["paths"].values() for op in item.values() if isinstance(op, dict) and "operationId" in op} repeated = sorted({op["operationId"] for item in paths.values() for op in item.values()} & ours) if repeated: sys.exit("These operations are already on the stack's salesforce target: " + ", ".join(repeated)) json.dump({"openapi": stack["openapi"], "info": {"title": "Salesforce operations with custom fields", "version": "1"}, "servers": stack["servers"], "paths": paths}, open(key, "w"), indent=2) print("Wrote %s: %d operations" % (key, sum(len(item) for item in paths.values()))) PY ACCOUNT=$(aws sts get-caller-identity --region "$REGION" --query Account --output text) # --expected-bucket-owner: the upload fails unless the bucket is in the stack's account. aws s3api put-object --region "$REGION" --bucket "$BUCKET" --key "$KEY" --body "$KEY" \ --server-side-encryption AES256 --expected-bucket-owner "$ACCOUNT" --query VersionId --output text CURRENT=$(aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" \ --query "Stacks[0].Parameters[?ParameterKey=='CustomOperationsS3Uri'].ParameterValue | [0]" --output text) if [ "$CURRENT" = "$URI" ]; then # The stack already reads this file: update the target so the gateway reads the new version. TARGET=$(out CustomTargetId) aws bedrock-agentcore-control get-gateway-target --region "$REGION" --gateway-identifier "$GATEWAY" --target-id "$TARGET" \ --query '{name: name, targetConfiguration: targetConfiguration, credentialProviderConfigurations: credentialProviderConfigurations}' > "$W/target.json" aws bedrock-agentcore-control update-gateway-target --region "$REGION" --gateway-identifier "$GATEWAY" \ --target-id "$TARGET" --cli-input-json "file://$W/target.json" --query status --output text else PARAMS=() for P in $(aws cloudformation describe-stacks --region "$REGION" --stack-name "$STACK" --query 'Stacks[0].Parameters[].ParameterKey' --output text); do if [ "$P" = CustomOperationsS3Uri ]; then PARAMS+=("ParameterKey=$P,ParameterValue=$URI"); else PARAMS+=("ParameterKey=$P,UsePreviousValue=true"); fi done aws cloudformation update-stack --region "$REGION" --stack-name "$STACK" --use-previous-template \ --capabilities CAPABILITY_IAM --parameters "${PARAMS[@]}" --query StackId --output text aws cloudformation wait stack-update-complete --region "$REGION" --stack-name "$STACK" fi echo "The salesforce-custom target reads $URI" # The VerifyAudience output's check: the gateway's allowed audience must be its own ID, or tool calls fail. AUD=$(aws bedrock-agentcore-control get-gateway --region "$REGION" --gateway-identifier "$GATEWAY" \ --query authorizerConfiguration.customJWTAuthorizer.allowedAudience --output text) if [ "$AUD" = "$GATEWAY" ]; then echo "Gateway audience: $AUD (correct)." else echo "Gateway audience: $AUD. It must be $GATEWAY; tool calls fail until it is. See the help guide's troubleshooting."; exit 1; fi
To write the operations file yourself
  • Write the OpenAPI file. Start from the stack's target, which has your org's server URL, and replace its operations with yours. Give each operation an operationId that the salesforce target doesn't use. Expand the block that follows, copy it, and paste it at the prompt. It asks for the Region and the stack name, and writes salesforce.json, the stack's target, and salesforce-custom-operations.json, a copy with no operations, in the current folder:

( 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 bedrock-agentcore-control get-gateway-target --region "$REGION" --gateway-identifier "$(out GatewayId)" \ --target-id "$(out GatewayTargetId)" --query targetConfiguration.mcp.openApiSchema.inlinePayload \ --output text > salesforce.json || exit 1 python3 -I -c ' import json s = json.load(open("salesforce.json")) s["paths"] = {} s.setdefault("info", {"version": "1"})["title"] = "My Salesforce operations" json.dump(s, open("salesforce-custom-operations.json", "w"), indent=2) print("Wrote salesforce-custom-operations.json, with the server URL " + s["servers"][0]["url"])' )

Add your operations under paths in salesforce-custom-operations.json. Then check that no operationId repeats one of the stack's; this command prints OK or the repeated names:

python3 -I -c ' import json def ids(f): return {op["operationId"] for item in json.load(open(f))["paths"].values() for op in item.values() if isinstance(op, dict) and "operationId" in op} repeated = sorted(ids("salesforce-custom-operations.json") & ids("salesforce.json")) print("Repeated: " + ", ".join(repeated) if repeated else "OK: no operationId repeats one of the stack target'"'"'s.")'
To add the operations file to the stack
  1. Upload the file to a bucket in the stack's account, encrypted with Amazon S3 managed keys. If you deploy with the deployer policy, use the policy's STAGING_BUCKET. This block asks for the Region and the bucket, uploads only if the bucket is in your account, and prints the S3 URI to enter:

    ( R=${AWS_REGION:-us-east-1} printf 'Region of the stack [%s]: ' "$R"; read -r REGION; REGION=${REGION:-$R} printf "S3 bucket in the stack's account and Region: "; read -r BUCKET ACCOUNT=$(aws sts get-caller-identity --region "$REGION" --query Account --output text) || exit 1 aws s3api put-object --region "$REGION" --bucket "$BUCKET" --key salesforce-custom-operations.json \ --body salesforce-custom-operations.json --server-side-encryption AES256 --expected-bucket-owner "$ACCOUNT" > /dev/null \ && echo "Uploaded. CustomOperationsS3Uri: s3://$BUCKET/salesforce-custom-operations.json" )
  2. Update the stack with CustomOperationsS3Uri set to s3://bucket/salesforce-custom-operations.json, and keep the other parameter values. When the update finishes, the CustomTargetId output shows the new target. Run the VerifyAudience output's command, as after every stack update.

To change your operations later, upload the new file to the same S3 URI, then update the target so the gateway reads the file again. Uploading the file alone doesn't change the gateway. Expand this block, copy it, and paste it at the prompt. It asks for the Region and the stack name, and prints the target's status, UPDATING:

( 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; } G=$(out GatewayId); T=$(out CustomTargetId) aws bedrock-agentcore-control get-gateway-target --region "$REGION" --gateway-identifier "$G" --target-id "$T" \ --query '{name: name, targetConfiguration: targetConfiguration, credentialProviderConfigurations: credentialProviderConfigurations}' \ > "$D/target.json" || exit 1 aws bedrock-agentcore-control update-gateway-target --region "$REGION" --gateway-identifier "$G" --target-id "$T" \ --cli-input-json "file://$D/target.json" --query status --output text )

The gateway sends the Salesforce access token to the servers URL in the file. The stack's change alerts report the target update. They don't report writes to the file in S3, and anyone who can write the file can change your operations and that URL at the next target update. For controlling who can write an object, see Bucket policies for Amazon S3.