Give each person their own HubSpot sign-in through AgentCore Gateway
Part 4 of 5: HubSpot's MCP server only accepts each person's own OAuth sign-in. AgentCore Gateway can do that, but several settings have to line up first, and its errors don't say which one is missing. This is the order that worked.

AgentCore Gateway can give every person their own HubSpot sign-in, so HubSpot applies their permissions rather than a shared account’s. HubSpot’s MCP server insists on it: it takes only OAuth, per person. Several settings have to line up before it works, and the gateway’s error doesn’t say which one is missing. This guide sets them up in the order that worked.
The short version
- HubSpot’s MCP connector needs AgentCore’s callback URL, so you create the credential provider before the connector.
- You host a small return page. AgentCore sends each browser there after HubSpot, and the page confirms who signed in.
- The gateway’s workload identity must allow that return page, and the gateway must offer MCP protocol 2025-11-25.
- The admin signs in once when the target is made. Each person signs in on their first call, through a link the gateway sends.
- Our gateway’s logs were off, and every failure read “An internal error occurred”. Next time we’d turn them on first.
This builds on our AgentCore Gateway guide and the GitHub guide, whose role policy this reuses. Metomic Boundary, our invented 900-person payments company, wants its sales team to ask Claude about their own accounts, such as the invented customer Calloway Freight.
The AgentCore Gateway series, in order:
- Put Claude Code on Bedrock behind your own sign-in
- Run Claude Desktop through the same gateway
- Add GitHub’s MCP server with a read-only token
- Give each person their own HubSpot sign-in (this guide)
- Count what the MCP tool definitions cost per model call
How does a per-person sign-in flow through the gateway?
1. Claude calls hubspot___search_crm_objects through the gateway, with the person's ID token
2. No HubSpot token for this person yet: the gateway answers MCP error -32042 with a sign-in link
3. The person opens it and signs in to HubSpot (AgentCore's callback receives the code)
4. AgentCore sends the browser to your return page with ?session_id=…
5. Your page calls CompleteResourceTokenAuth(session, the person's ID token)
6. From then on the gateway calls HubSpot with that person's own token
The admin goes through the same steps once when the target is created. The gateway uses that sign-in to list HubSpot’s tools.
Step 1: How do you get AgentCore’s callback URL for HubSpot?
HubSpot’s connector needs a redirect URL, and AgentCore only gives you one when you create the credential provider. So create the provider first, with placeholders, at the endpoints mcp.hubspot.com publishes.
# hubspot_provider.py: python3 hubspot_provider.py create (placeholders)
# python3 hubspot_provider.py update (the connector's real ID and secret)
import boto3, os, sys
c = boto3.client("bedrock-agentcore-control", region_name=os.environ["AWS_REGION"])
read = lambda f: open(os.path.expanduser(f)).read().strip()
real = sys.argv[1] == "update"
config = {"customOauth2ProviderConfig": {
"oauthDiscovery": {"authorizationServerMetadata": {
"issuer": "https://mcp.hubspot.com",
"authorizationEndpoint": "https://mcp.hubspot.com/oauth/authorize/user",
"tokenEndpoint": "https://mcp.hubspot.com/oauth/v3/token",
"responseTypes": ["code"]}},
"clientId": read("~/.hubspot-client-id") if real else "placeholder",
"clientSecret": read("~/.hubspot-client-secret") if real else "placeholder",
"clientAuthenticationMethod": "CLIENT_SECRET_POST"}}
call = c.update_oauth2_credential_provider if real else c.create_oauth2_credential_provider
p = call(name="boundary-hubspot", credentialProviderVendor="CustomOauth2", oauth2ProviderConfigInput=config)
print("provider:", p["credentialProviderArn"])
print("secret: ", p["clientSecretArn"]["secretArn"])
print("callback:", p["callbackUrl"])
python3 hubspot_provider.py create
Check: the callback looks like https://bedrock-agentcore.eu-west-2.amazonaws.com/identities/oauth2/callback/<uuid>. It stays the same when you update the provider.
Don’t pass tokenEndpointAuthMethods in the server metadata as well as clientAuthenticationMethod. AgentCore refuses the pair.
Step 2: How do you create the HubSpot connector?
In HubSpot, go to Development → MCP Connectors and create one. Use the callback from step 1 as its redirect URL. Then save its client ID and a client secret without either appearing on screen:
umask 077; pbpaste > ~/.hubspot-client-id # copy the client ID first
umask 077; pbpaste > ~/.hubspot-client-secret # then the secret
python3 hubspot_provider.py update
HubSpot requires PKCE on this flow. AgentCore’s sign-in handled that without any setting from us.
Step 3: Where does each browser come back to?
Something has to receive the browser after HubSpot and confirm the sign-in. In a real deployment it’s a page of your own app. For a first test, this local page does the job. It needs AWS credentials allowed to call bedrock-agentcore:CompleteResourceTokenAuth.
# return_page.py: python3 return_page.py (needs AWS_REGION, GATEWAY_ID and AWS credentials allowed CompleteResourceTokenAuth)
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs, urlparse
import boto3
region, gateway = os.environ["AWS_REGION"], os.environ["GATEWAY_ID"]
control = boto3.client("bedrock-agentcore-control", region_name=region)
agentcore = boto3.client("bedrock-agentcore", region_name=region)
def identities():
"""Who the sign-in can belong to: a target's own user while it waits for the admin, then the person's ID token."""
for target in control.list_gateway_targets(gatewayIdentifier=gateway)["items"]:
got = control.get_gateway_target(gatewayIdentifier=gateway, targetId=target["targetId"])
user = (got.get("authorizationData") or {}).get("oauth2", {}).get("userId")
if user:
yield "admin, for target " + target["name"], {"userId": user}
yield "you", {"userToken": open(os.path.expanduser("~/.agentcore-id-token")).read().strip()}
class Return(BaseHTTPRequestHandler):
def do_GET(self):
session = parse_qs(urlparse(self.path).query).get("session_id", [None])[0]
if not session:
return self.reply(400, "No session_id in the return address.")
for who, identity in identities():
try:
agentcore.complete_resource_token_auth(userIdentifier=identity, sessionUri=session)
except Exception as error:
print(f"not {who}: {type(error).__name__}", flush=True)
continue
print(f"signed in as {who}", flush=True)
return self.reply(200, "Signed in. You can close this tab.")
self.reply(502, "AgentCore didn't confirm the sign-in. See the terminal.")
def reply(self, status, text):
self.send_response(status)
self.send_header("content-type", "text/plain; charset=utf-8")
self.end_headers()
self.wfile.write(text.encode())
def log_message(self, *args):
pass
print("listening on http://127.0.0.1:53190/oauth-return", flush=True)
HTTPServer(("127.0.0.1", 53190), Return).serve_forever()
Start it in its own terminal and leave it running: python3 return_page.py.
Step 4: Which gateway settings must be in place first?
Three, and missing any of them gives the same “An internal error occurred. Please retry later.”
The workload identity must allow the return page. The gateway has a workload identity named after its ID. Its list of allowed return URLs starts empty.
aws bedrock-agentcore-control update-workload-identity --name $GATEWAY_ID \
--allowed-resource-oauth2-return-urls "http://127.0.0.1:53190/oauth-return"
The gateway must offer MCP protocol 2025-11-25. If you followed our first guide, it already does. If not, add it with update_gateway, carrying every other setting over as the GitHub guide shows.
The role must read the HubSpot credential. Add the secret ARN from step 1 to the secretsmanager:GetSecretValue statement of the read-target-credentials policy from the GitHub guide. Its AgentCore actions already include GetResourceOauth2Token.
Check: aws bedrock-agentcore-control get-workload-identity --name $GATEWAY_ID lists your return URL.
Step 5: How do you add HubSpot as a target?
# hubspot_target.py
import boto3, os
c = boto3.client("bedrock-agentcore-control", region_name=os.environ["AWS_REGION"])
t = c.create_gateway_target(gatewayIdentifier=os.environ["GATEWAY_ID"], name="hubspot",
targetConfiguration={"mcp": {"mcpServer": {"endpoint": "https://mcp.hubspot.com/"}}},
credentialProviderConfigurations=[{"credentialProviderType": "OAUTH", "credentialProvider": {"oauthCredentialProvider": {
"providerArn": os.environ["PROVIDER_ARN"], "scopes": [], "grantType": "AUTHORIZATION_CODE",
"defaultReturnUrl": "http://127.0.0.1:53190/oauth-return"}}}])
print(t["targetId"])
PROVIDER_ARN=<the provider ARN from step 1> python3 hubspot_target.py
The target goes to CREATE_PENDING_AUTH. It’s waiting for the admin’s sign-in, which it uses to list HubSpot’s tools.
Step 6: How does the admin sign in the first time?
aws bedrock-agentcore-control get-gateway-target --gateway-identifier $GATEWAY_ID --target-id <target id> \
--query 'authorizationData.oauth2.authorizationUrl' --output text
Open that link straight away and sign in to HubSpot. These links expire within minutes, and an old one says “The request has expired”. When HubSpot hands back, the return page’s terminal prints signed in as admin, for target hubspot.
Check: the target reaches READY. Our HubSpot target listed 41 tools.
Step 7: How does each person sign in on their first call?
The gateway sends the sign-in link only to a client in an MCP 2025-11-25 session that says it can open links. This script opens one, makes one call, and prints either the answer or the link.
# first_call.py: python3 first_call.py <tool> '<arguments as JSON>' (needs GW and a fresh ~/.agentcore-id-token)
import json, os, sys, urllib.error, urllib.request
URL = os.environ["GW"] + "/mcp"
TOKEN = open(os.path.expanduser(os.environ.get("AGENTCORE_TOKEN_FILE", "~/.agentcore-id-token"))).read().strip()
VERSION = "2025-11-25" # the version whose sessions can receive a sign-in link
def rpc(body, session=None):
headers = {"authorization": "Bearer " + TOKEN, "content-type": "application/json",
"accept": "application/json, text/event-stream", "mcp-protocol-version": VERSION}
if session:
headers["mcp-session-id"] = session
request = urllib.request.Request(URL, data=json.dumps(body).encode(), method="POST", headers=headers)
try:
with urllib.request.urlopen(request, timeout=60) as answer:
text, session = answer.read().decode(), answer.headers.get("mcp-session-id") or session
except urllib.error.HTTPError as error:
text = error.read().decode()
if text.lstrip().startswith(("event:", "data:")):
text = "\n".join(line[5:].strip() for line in text.splitlines() if line.startswith("data:"))
return (json.loads(text) if text.strip() else {}), session
started, session = rpc({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
"protocolVersion": VERSION, "capabilities": {"elicitation": {"form": {}, "url": {}}},
"clientInfo": {"name": "first-call", "version": "1"}}})
print("protocol:", started["result"]["protocolVersion"])
rpc({"jsonrpc": "2.0", "method": "notifications/initialized"}, session)
answer, _ = rpc({"jsonrpc": "2.0", "id": 2, "method": "tools/call",
"params": {"name": sys.argv[1], "arguments": json.loads(sys.argv[2])}}, session)
if "error" in answer:
error = answer["error"]
print("error", error.get("code"), error.get("message"))
for item in (error.get("data") or {}).get("elicitations") or []:
print("sign in here, now (the link lasts minutes):", item.get("url"))
else:
print("".join(part.get("text", "") for part in answer["result"].get("content", []))[:400])
python3 first_call.py hubspot___search_crm_objects '{"objectType":"companies","query":"Calloway Freight","limit":1}'
The first time, you’ll see:
protocol: 2025-11-25
error -32042 This request requires more information.
sign in here, now (the link lasts minutes): https://…
Open the link and sign in to HubSpot as yourself. The return page prints signed in as you. Run the same command again.
Check: the second run prints HubSpot’s answer, with only what your HubSpot user may see. In our test, Claude Desktop’s HubSpot calls through the gateway then used that person’s token too.
What goes wrong, and what does it mean?
| You see | It means | Do |
|---|---|---|
| “An internal error occurred. Please retry later.” on every HubSpot call | No allowed return URL, no 2025-11-25 on the gateway, or a client session on an older version | Step 4, then call through first_call.py |
| “The request has expired” on HubSpot’s page | The link is a short-lived pushed authorisation request | Make a fresh one and open it at once |
CREATE_PENDING_AUTH that never changes |
Nobody finished the admin’s sign-in | Step 6 |
| “can’t be performed … in Create_Pending_Auth state” | You tried to change the gateway or target before the admin signed in | Sign in first |
UPDATE_PENDING_AUTH, then UPDATE_UNSUCCESSFUL |
Any target update needs the admin’s sign-in again | Avoid needless updates. The earlier tools stayed listed for us |
| “WorkloadIdentity is linked to a service” | You tried to get the gateway’s workload token yourself | You can’t. Debug through the gateway |
What’s still hard?
- The errors. Three different gaps gave the same “internal error”. We’d turn the gateway’s logs on before anything else next time, though we haven’t yet seen what they show.
- Clients that can’t show the link. Claude Desktop connected on MCP 2025-03-26, so it never received the sign-in link. Each person needs one run of a script like
first_call.py, or a page that does the same. - How long a sign-in lasts. We don’t know yet how long a person’s HubSpot token lasts before they must sign in again. HubSpot’s refresh tokens are single use.
- The return page is real infrastructure. In production it’s a page of your app. It must know who’s signed in, and hold AWS credentials to confirm it.
- What each person can read, Claude can read. HubSpot’s permissions now apply per person. That’s the point, and it also means a sales rep’s whole book of contacts can enter a chat. We’ve written about where that data goes next.
What do you have now?
- HubSpot behind your gateway, where every call uses the asking person’s own HubSpot token.
- A return page that confirms each sign-in, and a script for each person’s first one.
- A map of which error means which missing setting.
Per-person sign-in gets HubSpot’s own permissions applied, which is the point. What a rep’s whole book of contacts does once it is in a chat is the next question, and the one our governed MCP gateway is built for. We’re working with a small number of security teams on governing what agents do with CRM data. If you’ve got Claude showing the sign-in link itself, we’d like to hear how.
Frequently asked questions
- Why does every HubSpot call through AgentCore Gateway say an internal error occurred?
- In our setup, "An internal error occurred. Please retry later." had three causes. The gateway's workload identity had no allowed return URL, the gateway didn't offer MCP protocol 2025-11-25, or the client hadn't opened a 2025-11-25 session. With all three fixed, the gateway answered with a sign-in link instead. Next time we'd turn the gateway's logs on first, because the error itself names none of them.
- What is MCP error -32042 from AgentCore Gateway?
- It's the gateway asking the person to sign in to the SaaS app first. The message reads "This request requires more information." and the sign-in link is in error.data.elicitations as a url. The gateway sends it only to a client in an MCP 2025-11-25 session that declared it can handle URL elicitation. Open the link quickly, because it expires within minutes.
- What does CompleteResourceTokenAuth do in AgentCore Identity?
- It's how your app confirms that a finished OAuth sign-in belongs to the person the gateway saw. After the SaaS app's consent page, AgentCore sends the browser to your return URL with a session_id. Your page calls CompleteResourceTokenAuth with that session and the person's identity: their gateway ID token, or the target's own userId for the admin's first sign-in. Only then is the token kept.
- Why did my HubSpot target go to UPDATE_UNSUCCESSFUL?
- Any update to an OAuth target sends it back to pending authorisation, waiting for the admin's sign-in. If nobody signs in in time, it fails with "The gateway owner did not complete authorization within the allowed time". In our case the earlier tools stayed listed and calls kept working. Avoid needless updates, and sign in promptly when you do change it.
- Does Claude Desktop show the HubSpot sign-in link from AgentCore Gateway?
- It didn't for us. Desktop connected to the gateway on MCP protocol 2025-03-26, and the gateway sends sign-in links only in 2025-11-25 sessions. We used a small script that opens a 2025-11-25 session, makes one call and prints the link. After the person signed in once, Desktop's calls used their HubSpot token.