Have your agent act on your behalf
An agent can call Google, Microsoft, Salesforce or any OAuth 2.0 service as the person who sent the task, without ever seeing their password. An admin sets up the integration once. Each person connects their own account and approves the agent, which delegates access to it. While the task runs, the agent gets a short-lived access token for that person's account.
Requires Node SDK or Python SDK 1.0.25 or later.
How it works
- An organization admin adds an integration in Settings → Integrations. It holds the client ID and secret of the admin's own OAuth app at the service.
- The agent's developer lists the integration in the agent card under
connections. - When someone sends a task to the agent, they connect their account at the service and approve the agent. They do this once per agent.
- While the task runs, the handler asks Blocks for a token with
getToken. Blocks returns an access token for that person's account. - The person can see their connections, revoke an agent or disconnect at any time.
The integration must belong to the same organization as the agent.
Your company's private network: the flow is the same on Blocks Enterprise. Organizations typically map to your departments, so add the integration in the department that owns the agent. If you manage several departments, the Integrations page has a department picker at the top.
Set up an integration
You need to be able to manage the organization. Create an OAuth app at the service first, then add it to Blocks.
- In your OAuth app at the service, add the Redirect URI that Blocks shows on the Add integration page as the app's redirect (callback) URL.
- In Blocks, open Settings → Integrations and select Add integration.
- Pick a service. Google, Salesforce and Microsoft pre-fill the OAuth settings, so you only add your app's client ID and secret. Custom works with any OAuth 2.0 provider, and you enter every endpoint.
- Fill in the form:
| Field | What to enter |
|---|---|
| Name | The name agents use for this integration. Lowercase letters, digits, - and _, up to 63 characters, unique in your organization. You can't change it later. |
| Client ID and Client secret | From your OAuth app. |
| Scopes | The permissions agents may ask for. This is the ceiling: an agent card can request only scopes listed here. |
| Advanced | Authorization URL, Token URL and an optional Revoke URL. Templates pre-fill these. Also Require PKCE, Token auth method, Token revocation (revoke each token, or revoke the whole grant) and extra authorization parameters, one key=value per line, for example prompt=consent to make the service ask every time. |
For a Salesforce sandbox, change the endpoints to test.salesforce.com under Advanced. For a single-tenant Microsoft app, replace common in the endpoints with your tenant ID.
An integration's page shows which agents use it and how many people have connected, never who. From there you can:
- Edit it. Changing the endpoints or the client ID needs a new client secret.
- Rotate secret with a new client secret.
- Disable or Enable it. While it is disabled, tasks for agents that require it fail.
- Delete it. This disconnects everyone who connected and breaks the agents that declare it.
Declare the connection in your agent card
Add the integration to connections in agent-card.json:
"connections": [
{ "integration": "salesforce", "scopes": ["api", "refresh_token"], "required": true }
]integrationis the name an admin gave it. It must exist in your agent's organization and be enabled.scopesmust all be in the integration's list of scopes. If an agent asks for others, tasks fail withIntegrationUnavailable.requireddefaults totrue. Blocks then refuses the task until the person has connected and approved your agent, so callers get anAuthRequiredErrorwith a connect link instead of a running task. Withrequired: falsethe task starts anyway, andgetTokenthrowsConnectionRequiredErrorif the person hasn't connected.
You can list up to 10 connections. See the agent card reference.
Get a token in your handler
Call getToken when you need it.
Node.js
import type { HandlerResult, StartTaskMessage, TaskContext } from '@blocks-network/sdk';
const INTEGRATION = 'salesforce';
export default async function handler(task: StartTaskMessage, ctx?: TaskContext): Promise<HandlerResult> {
if (!ctx) throw new Error('TaskContext required for integration connections');
ctx.reportStatus('Fetching your recent Salesforce accounts');
let token = await ctx.connections.getToken(INTEGRATION);
const get = async (path: string): Promise<Response> => {
const instanceUrl = token.extra.instance_url as string; // Salesforce: the user's org API host
return fetch(`${instanceUrl}${path}`, { headers: { Authorization: `Bearer ${token.accessToken}` } });
};
const path = `/services/data/v62.0/query?q=${encodeURIComponent('SELECT Name FROM Account LIMIT 5')}`;
let res = await get(path);
if (res.status === 401) {
token = await ctx.connections.getToken(INTEGRATION, { forceRefresh: true }); // once
res = await get(path);
}
if (!res.ok) throw new Error(`Salesforce query failed: ${res.status}`);
return { artifacts: [{ data: JSON.stringify(await res.json()), mimeType: 'application/json' }] };
}Python
import json
import urllib.error
import urllib.parse
import urllib.request
INTEGRATION = "salesforce"
def handler(task, ctx=None):
if ctx is None:
raise RuntimeError("TaskContext required for integration connections")
ctx.report_status("Fetching your recent Salesforce accounts")
token = ctx.connections.get_token(INTEGRATION) # synchronous
query = urllib.parse.quote("SELECT Name FROM Account LIMIT 5")
path = f"/services/data/v62.0/query?q={query}"
def get(tok):
url = f"{tok.extra['instance_url']}{path}" # Salesforce: the user's org API host
req = urllib.request.Request(url, headers={"Authorization": f"Bearer {tok.access_token}"})
with urllib.request.urlopen(req, timeout=30) as resp:
return json.load(resp)
try:
data = get(token)
except urllib.error.HTTPError as err:
if err.code != 401:
raise
data = get(ctx.connections.get_token(INTEGRATION, force_refresh=True)) # once
return {"artifacts": [{"data": json.dumps(data), "mimeType": "application/json"}]}getToken returns { accessToken, tokenType, expiresAt, scopes, extra } (Python: access_token, token_type, expires_at, scopes, extra). extra holds provider fields, such as Salesforce's instance_url.
- The token belongs to this task. Blocks issues one only while the task is queued or running. Don't log it, store it or reuse it after the task.
- If the service answers
401, callgetTokenagain once withforceRefresh: true(Python:force_refresh=True) and retry.
What the person sees
When a person sends a task to an agent that needs a connection they haven't made, the task is refused and the caller gets an AuthRequiredError with the integration, a reason and a connectUrl. The reason is not_connected, not_approved, broken (the connection stopped working) or sign_in_required (the caller is signed out). A web app made with blocks init --mode webapp shows this as a Connect link. See Deploy agent web UIs.
The connect link opens a screen that says Allow @agent to use your Service account. It shows:
- the Blocks account the person is signed in with, and who publishes the agent
- the scopes the agent asks for
- that the agent will act as them in the service while their tasks run, and to only allow agents they trust
- that they will sign in at the service itself
The person selects Allow @agent, signs in at the service, and sends the task again. Blocks never sees their password.
Manage your connections
Each person manages their own connections from their profile menu: Profile → Connections. For each connected account it shows:
- the status: Active, or Needs reconnect when the connection stopped working
- the agents the person approved, with their scopes
The person can Revoke one agent, or Disconnect the whole account. The agents lose access straight away. If the service doesn't let Blocks revoke access, the person should also remove the app under their account's permissions at the service. The screen says so when that applies.
Errors
| Error | Where | Meaning |
|---|---|---|
AuthRequiredError (HTTP 403, AuthRequired) | Caller | The person hasn't connected or approved. Carries integration, reason and connectUrl. No task was created. |
ConnectionRequiredError | Handler, from getToken | The person must connect or approve at connectUrl. Carries integration, reason and connectUrl. |
ConnectionAccessError | Handler, from getToken | Any other failure, for example the task ended. Carries status and code. |
IntegrationUnavailable (HTTP 409) | Caller | The integration doesn't exist or is disabled, or the card asks for scopes it doesn't allow. |
ConnectionsUnavailable (HTTP 503) | Caller | This deployment hasn't turned integration connections on. |
Security
- The person signs in at the service. Blocks stores the grant encrypted and never sees a password.
- The agent only receives an access token, and only while the task runs.
- The person can revoke an agent or disconnect at any time. Admins see how many people connected to an integration, never who.