Your customers' own accounts
Your customers can connect their own accounts, such as their Google Calendar and Drive, so their agent can work there too. Your user signs in on a page OpenLegion hosts in your brand, and the agent gets that app's tools: neither your server nor the agent ever holds the account's token.
The smallest version
1. List the app in your template
In openlegion/template.ts, apps lists what your customers may connect:
export const template = defineTemplate({
slug: "support",
name: "Support assistant",
tools: { get_account: getAccount },
spec: {
instructions: "Help the customer with their account. Use their calendar when they ask about meetings.",
apps: [{ app: "google" }],
},
});
ol.connectorCatalog.list() lists the apps there are. An entry's id is what app takes, and its tools say what each tool can do (effect: read, draft, write or egress).
2. Say where your users come back to
Once in test mode and once in live mode, with a console key that has the connectors scope:
await ol.connectSettings.update({
name: "Your App",
return_origins: ["https://your.app"],
});
The connect page shows your name, and your logo_url, accent_color and privacy_url if you set them. It never shows OpenLegion's. In test mode, http://localhost is allowed as well.
3. Send your user to connect
A route on your server opens a connect session in the signed-in user's workspace, and sends their browser to it:
// app/connect/google/route.ts: a button on your settings page posts here.
export async function POST(): Promise<Response> {
const session = await currentSession();
if (!session) return new Response(null, { status: 401 });
const ws = openlegion().workspace(await workspaceFor(session.customer), { subject: session.user });
const connect = await ws.connectSessions.create({
app: "google",
return_url: "https://your.app/settings/integrations",
});
// An app with no sign-in is connected at once: there is no page to visit.
return Response.redirect(connect.url ?? connect.return_url, 303);
}
Your user signs in to Google, then comes back to return_url with connect_session and status added: completed, cancelled (they pressed Cancel, or declined on Google's screen), failed or expired. Use status to choose what to say; what is connected is what GET /connections lists.
- The
urlworks once, for 30 minutes, in the first browser that opens it. Send the browser there as a page of its own (a redirect or a link), never in an iframe, and open a new session for each try. - The key needs the
connectionsscope. The keynpx openlegion initmade has it.
4. Show what is connected
On your settings page, list the workspace's connections, with a ws made the same way:
const { data } = await ws.connections.list();
const rows = data.map((c) => ({
app: c.app,
account: c.account.label, // the vendor's name for it, such as an email address; never a token
reconnect: c.status === "needs_reauth",
lastUsed: c.last_used_at, // when an agent last used it, or null
}));
- A workspace has one live connection per app. It belongs to the workspace;
connected_bysays who connected it. - Disconnecting is
ws.connections.delete(id). From then on no agent can use the account, and OpenLegion revokes the token at the vendor, or at the server's own sign-in, where it allows that. The connection stays readable as history, withstatus: "revoked". - Erasing one of your users (
DELETE /subjects/{subject}) disconnects the connections they made.
With the kit: from the chat and your pages
If your app uses the kit (createHandler and <AgentChat>), the kit does steps 3 and 4 for you. Steps 1 and 2 still apply.
In the chat
When an agent needs an app that isn't connected, it asks for it. <AgentChat> then shows a Connect card with the app's name and the agent's reason:
- Your user selects Connect. A new window opens on the connect page.
- When they finish, the window comes back to the kit's
{basePath}/connect_returnand closes. Where the browser won't let a page close itself, the page tells your user to close it. - The card reads the session from your server and shows that the app is connected. Then it sends one message as your user, "I connected Google.", so the agent carries on. The name in it is always the catalog's. For a server added by its address it is "I connected it." (
connectLabels.doneCustom), because that server's name is text someone typed and the message runs with your user's trust.
- The card sends that message only when your user started the connect from that card, and never when the page reloads. If your user finishes after closing the chat, nothing is sent, and the agent can use the app from its next run.
- If the agent read outside content (a web page, an email) before it asked, the card says so. Your user should connect only if they asked for this.
connectLabelschanges the card's words.connectLabels.doneis the message it sends.{origin}{basePath}/connect_returnmust be on your return origins. To use another page, setcreateHandler({ connectReturnUrl }).
On your pages
import { AppCatalog, ConnectButton, ConnectionsList } from "@openlegion/platform/react";
export default function Integrations() {
return (
<>
<ConnectionsList /> {/* the workspace's connections, with Reconnect where one needs it, and Disconnect */}
<AppCatalog /> {/* the apps your template lists, searchable, each with a Connect button */}
<ConnectButton app="google" appName="Google" />
</>
);
}
They call the kit's routes with your key, as the person your resolve() answers, so your app decides who may connect. On one page they agree at once: an app connected from the catalog shows in the list, and one disconnected in the list is offered again in the catalog. An app that connects with no sign-in opens no window.
When a new window won't do
Some in-app browsers and webviews can't open a second window. mode="redirect" sends the page itself to the connect page. Your user then comes back to the same URL, where the button reads the session:
<ConnectButton app="google" mode="redirect" />
The page comes back only to a path on its own origin: the kit refuses any other return_path with invalid_body. If a browser blocks the new window, the card shows a link to the connect page instead. The link takes the focus, and the card says why.
The kit's own codes are invalid_app, invalid_server, invalid_connection and invalid_connect_session (400). Everything the API refuses (below) passes on with the API's code.
What the agent can do with it
The app's tools that only read run as soon as the account is connected. A tool that writes or sends (effect write or egress, such as creating a calendar event, which can email its guests) waits for a person's approval, like one of your own tools with requiresApproval, unless your template's spec lets it run:
apps: [{ app: "google", tools: { "connectors.google.calendar.create_event": { allowed: true } } }],
The consent screen names OpenLegion
Until you add your own OAuth app, Google's consent screen names OpenLegion, because OpenLegion's OAuth client signs your user in (the catalog entry reads auth.managed_app: true). To have it name you, make an OAuth client in Google's console and give OpenLegion its id and secret, with a console key that has the connectors scope:
const app = await ol.oauthApps.create({
app: "google",
client_id: process.env.GOOGLE_CLIENT_ID!,
client_secret: process.env.GOOGLE_CLIENT_SECRET!,
});
// Add app.redirect_uri to the client's authorized redirect URIs in Google's console.
- Register
redirect_uriwith Google first. Google refuses the sign-in until you do. - Test mode and live mode each need their own. Sending it again for the same app replaces it, and keeps its id.
- A new secret with the same client id keeps every connection. A different client id, or deleting the app, leaves existing connections working until their next token refresh. Then each one needs reconnecting (below), and the reconnect uses your current app.
- You can add your own OAuth app only for an app whose
sourceisnative, such asgoogle. An app served by its vendor's own server (vendor_mcp) can't take yours: if it signs in with OAuth, the vendor's screen names OpenLegion. One that admits only an app registered with the vendor readsstatus: "needs_oauth_app"and opens no connect session (app_needs_oauth_app).
A server your user adds by its address
Some of your users run tools the catalog doesn't have: an MCP server of their own, or one a vendor gave them a URL for. They can add it by its address. It's off until your template turns it on:
apps: [{ app: "google" }, { app: "custom" }],
Then a connect session names the server instead of an app:
const connect = await ws.connectSessions.create({
server: { url: "https://mcp.example.com/mcp", name: "Order tools" },
return_url: "https://your.app/settings/integrations",
});
- The page says, in your brand, that nobody has checked the server, and asks your user to connect it only if they trust whoever runs it. A server with no sign-in shows its tools first, in the server's own words. If the server asks for a key, your user types it into the page. If it has its own sign-in, they sign in there.
- Every tool the server offers asks your user before it runs, whatever the server says about it. Your template can't change that:
apps[].toolsis refused forcustom. - Your agents are told which of these servers are connected for them, by the
nameyour user gave it (or its host). The name is passed as quoted text, never as an instruction. The agents are also told that every one of the server's tools asks your user first. A server whose tools changed, or one that was disconnected, isn't named. - The connection's
appiscustom-<slug>, itssourceiscustom, andserversays which host it calls. To reconnect it, open a session with thatapp. - The address must be a public
httpsURL with a host name: no IP address, no user or password. OpenLegion never reaches a private or internal address, even through a redirect. - A workspace may have 10 such servers at a time (
custom_server_limit_reached,409). Disconnecting one frees its place.GET /connections/appssays how many it has (custom_servers: {count, max}), ornullwhen your template hasn't turned this on, so your page can hide the form or say it's full before anyone types. - A server that admits only an OAuth app registered with it ends the session
failedwithfailure_code: "needs_oauth_app".
On your pages
Where your template turns this on, <AppCatalog /> shows "Add your own server" below its apps: an address, a name your user may leave empty, and one button. Your user finishes on the hosted page, in a new window, as for an app.
- Off, there's no form. The kit reads
custom_serversand draws nothing when it'snull.<AppCatalog addServer={false} />hides the form even where it's on, but nothing can show it where your template has it off. - At the most, a sentence takes the form's place ("You've added 10 of 10 servers. Disconnect one to add another."). Reconnect still works on the servers your user already has.
- Every outcome is said in plain words, among them an address OpenLegion won't reach (the address field is marked) and a server that doesn't let new apps sign in (
needs_oauth_app). The kit never shows the server's own error text. - In
<ConnectionsList />, such a server goes by the name your user gave it, its host beside it, nevercustom-<slug>. <AddServerForm />is the form on its own, for a page with no catalog.labelsreplaces any of its words;onAdded(connection, name)is called once a server is added.
<AppCatalog onServerAdded={(connection, name) => toast(`${name} was added.`)} />
A connection that needs reconnecting
When an account's token stops working (say your user removed the access in their Google account, or you changed your OAuth app's client id), or a server's tools changed since your user connected it, the connection reads status: "needs_reauth" and its tools stop working for your agents. connection.needs_reauth fires once:
webhooks: {
"connection.needs_reauth": async (event) => {
const connection = event.data.truncated ? null : event.data.object;
// external_ref is your id for the customer: ask them, in your product, to connect again.
await askToReconnect(event.external_ref, connection?.app ?? "an app");
},
},
Reconnecting is a new connect session for the same app (step 3).
- The same account comes back as the same connection,
activeagain, andconnection.updatedfires. - A different account replaces it: the old connection is revoked (
connection.revoked) and a new one is made (connection.created). - If your user reconnects before the event is written, no event fires.
GET /connections?status=needs_reauthis the truth either way. - To walk this before production, call
POST /connections/{id}/expirewith a test key on a connection your user signed in to: it expires as a real one does, the event fires and the Reconnect card shows. A connection that uses a key, or no sign-in, has nothing to expire (connection_cannot_expire,409).
When your user can't connect
app_not_enabled(400): the workspace's template version doesn't list the app inapps. The message names the apps it does list. A workspace on a version that lists none can connect nothing until a version that lists apps is applied.parameter_invalid(400) onreturn_url: it isn't on your return origins, exactly.insufficient_scope(403): your key doesn't have theconnectionsscope.insufficient_role(403): the person is a member, whether they came with a session token (POST /sessions) or as your key'sOpenLegion-Subject. Any member may list and read the workspace's connections, connect an app, and disconnect one they connected. Replacing or disconnecting an account someone else connected, and changing which agents use one, need an owner or admin. Your key with no subject may.rate_limited(429): the workspace opened too many connect sessions in the last hour.
When an agent can't use the account
A connection lets an agent use the account while the connection is live, your template version's apps entry allows the agent, and the connection's own agents is null or names it.
- In the template,
apps[].agentsnames the template agents that may use the app, by key. Left out, every agent may. - In a workspace,
ws.connections.update(id, { agents: ["agt_…"] })narrows one connection to some of its agents.nullgives it back to every agent the template allows.[]is refused: disconnect instead.
Anything else doesn't run. The action reads outcome: "refused" with connection_not_granted, or with connection_revoked when the account was disconnected. For the second, your user connects the account again through a connect session.