Sub topic 15
Testing and troubleshooting the integration
You have now built every piece of the integration: token request, session creation, messaging, streaming, and cleanup. This chapter covers how to verify that these pieces work together and how to find the cause when they don't.
This chapter assumes you have completed the earlier chapters. You should have an active agent with a known agent ID and an External Client App that uses the client credentials flow. You should also have the Python and curl examples working at least once.
Test in layers
An Agent API call passes through several stages, and each can fail for its own reasons. Test them in order and stop at the first failure.
- Token. Can you get an access token from your My Domain?
- Session. Does the token let you create a session for this agent?
- Message. Does the agent reply to a simple message?
- Cleanup. Does the session end without error?
If you test only the final behavior ("my app shows no reply"), you can't tell an OAuth misconfiguration from an inactive agent. Layered testing narrows the cause to one stage.
A smoke test script
A smoke test is a short script that runs the whole path once and reports where it failed. Run it after any change to credentials, scopes, or the agent. It also works as a post-deployment check.
The script below reports the HTTP status and response body of the failing step. It never prints the token or the secret.
import os
import sys
import uuid
import requests
API_BASE = "https://api.salesforce.com/einstein/ai-agent/v1"
MY_DOMAIN = os.environ["SF_MY_DOMAIN"]
AGENT_ID = os.environ["SF_AGENT_ID"]
def fail(step: str, response: requests.Response) -> None:
print(f"FAIL at {step}: HTTP {response.status_code}")
print(response.text[:500])
sys.exit(1)
def main() -> None:
# Layer 1: token
token_response = requests.post(
f"{MY_DOMAIN}/services/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": os.environ["SF_CLIENT_ID"],
"client_secret": os.environ["SF_CLIENT_SECRET"],
},
timeout=30,
)
if not token_response.ok:
fail("token request", token_response)
headers = {
"Authorization": f"Bearer {token_response.json()['access_token']}",
"Content-Type": "application/json",
}
print("OK token")
# Layer 2: session
session = requests.post(
f"{API_BASE}/agents/{AGENT_ID}/sessions",
headers=headers,
json={
"externalSessionKey": str(uuid.uuid4()),
"instanceConfig": {"endpoint": MY_DOMAIN},
"streamingCapabilities": {"chunkTypes": ["Text"]},
"bypassUser": True,
},
timeout=30,
)
if not session.ok:
fail("create session", session)
session_id = session.json()["sessionId"]
print("OK session", session_id)
try:
# Layer 3: message
reply = requests.post(
f"{API_BASE}/sessions/{session_id}/messages",
headers=headers,
json={"message": {"sequenceId": 1, "type": "Text", "text": "Hello"}},
timeout=60,
)
if not reply.ok:
fail("send message", reply)
messages = reply.json().get("messages", [])
if not messages:
print("FAIL at parse reply: no messages in response")
sys.exit(1)
print("OK reply:", messages[0]["message"][:80])
finally:
# Layer 4: cleanup
end = requests.delete(
f"{API_BASE}/sessions/{session_id}",
headers={**headers, "x-session-end-reason": "UserRequest"},
timeout=30,
)
print("OK session ended" if end.ok else f"WARN end session: HTTP {end.status_code}")
if __name__ == "__main__":
main()The script ends the session in a finally block, so a failed message step does not leave a session open. sys.exit raises SystemExit, which still runs the finally block.
Symptoms and likely causes
The table maps what you see to the most probable cause. The exact error text can vary, so rely on the HTTP status and the stage where it appears.
| Stage | Symptom | Likely cause | Fix |
|---|---|---|---|
| Token | `400` with an error such as `invalid_client` or `unsupported_grant_type` | Wrong client ID or secret, or the client credentials flow is not enabled on the app | Re-copy the credentials and confirm the flow is enabled in the External Client App |
| Token | Connection error or HTML page returned | The URL is not your My Domain, or it has a typo | Use the full My Domain URL, not a generic login URL |
| Token | `400` mentioning the run-as user | No run-as user is set for the client credentials flow | Assign a valid, active user in the app's OAuth policies |
| Session | `401` | Token expired, or the token was not sent as `Bearer` | Request a new token and check the header format |
| Session | `403` | The app lacks a required scope, or the run-as user lacks access | Add the Agent API scopes and review the user's permissions |
| Session | `404` | Wrong agent ID, or the agent is not active | Copy the ID again and activate the agent |
| Message | `400` | Malformed JSON, missing `message` object, or a bad `sequenceId` | Compare the body with the working example |
| Message | `404` or an error about the session | The session ended, expired, or the ID is wrong | Create a new session |
| Message | Request times out | The agent is slow, or your client timeout is too short | Raise the timeout or switch to streaming |
Tokens that work but permissions that don't
A token request that succeeds does not prove the integration is correctly configured. The token request only checks the client ID, secret, and flow. Scopes and the run-as user's access are checked later, when you create the session. A smoke test that stops after the token step misses the most common setup mistakes.
For the Agent API, an External Client App typically needs the api, chatbot_api, and sfap_api scopes. Check the current Salesforce documentation for the exact list, because scope requirements can change between releases. After you change scopes or policies, request a new token. An old token keeps the scopes it was issued with.
Check each layer by hand
When the script reports a failure, repeat that single step with curl. Taking your application code out of the picture shows whether the problem lies in the request itself or in how your code builds it.
curl -s -o /dev/null -w "%{http_code}\n" -X POST "$SF_MY_DOMAIN/services/oauth2/token" \
-d "grant_type=client_credentials" \
-d "client_id=$SF_CLIENT_ID" \
-d "client_secret=$SF_CLIENT_SECRET"This prints only the status code, so the token never appears in your terminal history or logs. A 200 means the credentials and flow are correct. Drop -o /dev/null and -w to see the response body when you need the error description.
Common mistakes in the message loop
Some failures only appear on the second or third message, so a single-message test can pass while real conversations fail.
- Reusing a sequence ID. Each message in a session needs a
sequenceIdthat is greater than the previous one. Keep a counter per session. Don't generate it per request without state. - Sharing one session across users. A session holds one conversation's history. Create one per end user or per conversation, or the agent will mix up their context.
- Assuming one message in the reply. The response contains a
messageslist. Code that reads only the first item will drop content when the agent returns more than one entry. Check thetypeof each entry, as covered in the response-parsing chapter. - Ignoring the token lifetime. A long conversation can outlive the token. Catch a
401, request a new token, and retry the call once. - Skipping the session end. Sessions that you never end waste resources and clutter your testing. Always end them in
finally. - Setting a short timeout on messages. An agent that calls actions or queries data takes longer than a plain text reply. A 60-second timeout, as used in the examples, is a sensible starting point.
Testing the streaming path
Test streaming separately from the synchronous path. A working /messages call does not prove that /messages/stream works.
- Create a session and keep its ID.
- Send a message with the curl streaming example, using
-Nso curl does not buffer output. - Confirm that events arrive one after another, not all at once at the end.
- Confirm that the
Accept: text/event-streamheader is present. Without it, you may get a normal response instead of a stream.
If all the events arrive at the same moment, something between you and Salesforce is buffering the response. Corporate proxies and some HTTP client defaults do this. Test from a network without the proxy to confirm.
Automated tests
For repeatable testing, split your code into two kinds of tests.
- Unit tests replace the HTTP calls with fakes. They check your parsing, your retry-on-
401logic, and your sequence counter without touching Salesforce. They run in milliseconds and don't consume agent usage. - Integration tests call a real sandbox org with a test agent, like the smoke test above. Run them less often, for example before a release. Use a dedicated test agent with predictable behavior so you can assert on the reply.
Avoid asserting on the exact wording of an agent's answer. Generated text varies between runs. Assert on stable properties instead: the status code, that the messages list is not empty, that the type is what you expect, or that the reply contains a known keyword from a tightly scoped test topic.
Debugging notes
When you log for debugging, record the step name, HTTP status, session ID, and a truncated response body. Do not log the access token, the client secret, or full user messages if they may contain personal data. Keeping the session ID in your logs lets you match your records with the session in Salesforce when you ask an admin to investigate.
Exercise
Your smoke test prints "OK token" and then "FAIL at create session: HTTP 404". Name two likely causes and what you would check for each.
Show answer
The agent ID may be wrong, so copy it again from the agent in Salesforce and compare it with the SFAGENTID value. The agent may also not be active, so activate it and run the test again. A successful token rules out the client ID, the secret, and the flow, so you don't need to check those.
Exercise
Your first message in a session works, but the second returns a 400 error. The request body is otherwise identical. What is the most likely mistake, and how do you fix it?
Show answer
The sequenceId was reused. Each message in a session needs a higher sequenceId than the one before, so keep a per-session counter and increment it for every message (1, then 2, and so on).