User connection

"Which Linear issues are assigned to me?" only works with that person's own Linear.

A user connection is an account one of your users connects. The agent uses it only in that user's conversations.

Let each user connect

If you don't have an agent named support yet, create one in Creating an agent. Add a connector without --connection, and each user signs in to their own account:

curl -fsSL https://getstream.io/cli.sh | bash # get the CLI
getstream agents connectors bind support linear

The command adds this to agents/support/agent.yaml and syncs the agent. See a full agent.yaml for the rest of the file.

# ...
connectors:
  - name: linear

The user signs in at Linear, and the agent never sees their password.

A test in the terminal has no signed-in user, so it leaves linear out and tells you so. Test it in the Stream Dashboard, where you are the signed-in user:

getstream agents test support --sync --dashboard

The CLI prints the address of the agent's test chat in the Dashboard. Open it and ask: "Which Linear issues are assigned to me?". A Connect Linear button shows under the reply while the conversation runs. Sign in at Linear, and the button turns into "Linear connected" as the agent goes on to list your issues.

To check which connection the agent uses:

getstream agents tools support
CONNECTOR  NAME    ACCOUNT          GRANT      REQUIRED  SANDBOX
linear     linear  Each user's own  All tools  no        no

To connect one user's account from the terminal, add --user with their user ID:

getstream agents connections create linear --user alice

Linear's sign-in opens in your browser. The Linear account you sign in with becomes alice's. Over SSH, add --no-browser: the command then prints a link to open on the same computer. To see that connection's tools, or to delete it:

getstream agents connections tools linear --user alice
getstream agents connections delete linear --user alice

Connect in your app's chat

In your own app, the reply asks the same way: the call's step waits for the user to sign in, and the AI components show the Connect Linear card on it. Give each session a returnUrl where the sign-in comes back, your page's origin on the web or your app's own scheme in a mobile app, and an approver that runs it:

React Native · ConnectedConversation.tsx
import type { Session } from "@stream-io/stream-agents";
import { useMemo } from "react";
import type { LocalMessage } from "stream-chat";
import {
  AIClientIdentity,
  createAuthSessionAuthorizer,
  fromStreamMessage,
  type AIToolApprover,
} from "stream-chat-expo/ai-components";
import { AIConversation } from "stream-chat-expo/ai-components/conversation";

// Where the sign-in comes back: your app's own scheme, in reverse domain form. Pass the same URL
// when the session opens: api.agent("support").sessions.create({ returnUrl: connectedUrl })
export const connectedUrl = "com.example.assistant:/connected";

// `messages` are the messages of the channel session.chat() opened, loaded with
// `channel.watch()`.
export const ConnectedConversation = ({
  session,
  userId,
  messages,
}: {
  session: Session;
  userId: string;
  messages: LocalMessage[];
}) => {
  const approver = useMemo<AIToolApprover>(
    () => ({
      userId,
      clientId: AIClientIdentity.installId(),
      // Answers the questions of the tools this app registered for the session.
      decide: async (call, allowed) => session.decide(call.id, { allowed }),
      // Opens the sign-in in the system's sign-in sheet.
      authorizer: createAuthSessionAuthorizer({
        callbackScheme: "com.example.assistant",
        decline: async (call) => session.declineLogin(call.id),
      }),
    }),
    [session, userId],
  );
  const conversation = useMemo(
    () => messages.map((message) => fromStreamMessage(message)),
    [messages],
  );

  return <AIConversation approver={approver} messages={conversation} />;
};
React · ConnectedConversation.tsx
"use client"; // Next.js App Router: these hooks run in the browser

import type { Session } from "@stream-io/stream-agents";
import { useMemo } from "react";
import type { LocalMessage } from "stream-chat";
import {
  AIClientIdentity,
  AIConversation,
  createPopupAuthorizer,
  fromStreamMessage,
  type AIToolApprover,
} from "stream-chat-react/ai-components";
import "stream-chat-react/dist/css/index.css";
import "stream-chat-react/dist/css/ai-components.css";

// Where the sign-in comes back. Pass the same URL to sessions.create, with `api` the
// Client the user signed in with: api.agent("support").sessions.create({ returnUrl })
// Empty while a page renders on the server, where there is no window.
export const connectedPage = () =>
  typeof window === "undefined"
    ? ""
    : `${window.location.origin}/connected.html`;

// `messages` are the messages of the channel session.chat() opened, loaded with
// `channel.watch()`.
export const ConnectedConversation = ({
  session,
  userId,
  messages,
}: {
  session: Session;
  userId: string;
  messages: LocalMessage[];
}) => {
  const approver = useMemo<AIToolApprover>(
    () => ({
      userId,
      clientId: AIClientIdentity.installId(),
      // Answers the questions of the tools this page registered for the session.
      decide: async (call, allowed) => session.decide(call.id, { allowed }),
      authorizer: createPopupAuthorizer({
        returnUrl: connectedPage(),
        decline: async (call) => session.declineLogin(call.id),
      }),
    }),
    [session, userId],
  );
  const conversation = useMemo(
    () => messages.map((message) => fromStreamMessage(message)),
    [messages],
  );

  return <AIConversation approver={approver} messages={conversation} />;
};
Kotlin
// Where the sign-in comes back: your app's own scheme. Pass the same URL when the session opens:
// agents.agent("support").sessions.create(SessionOptions(returnUrl = "com.example.assistant:/connected"))
val approver = AIToolApprover(
    userId = agents.backend.user?.id.orEmpty(),
    clientId = AIClientIdentity.installId(context),
    scope = viewModelScope,
    authorizer = AIToolAuthorizer(
        connect = { _, url -> SignIns.open(context, url) },
        decline = { call -> session.declineLogin(call.id) },
    ),
) { call, allowed ->
    // Answers the questions of the tools this app gave the session.
    session.decide(call.id, allowed)
}
Swift · ConnectedConversation.swift
import Foundation
import StreamAgents
import StreamChatAI
import SwiftUI

// Where the sign-in comes back: your app's own URL scheme, in reverse domain form.
@MainActor
func openConnectedConversation() async throws -> AgentTransport {
    var options = SessionOptions()
    options.returnURL = URL(string: "com.example.assistant:/connected")
    return try await AgentTransport(agents.agent("support").sessions.create(options))
}

// `AgentTransport` and `AgentMessage` are the quickstart's.
struct ConnectedConversation: View {
    @StateObject private var conversation: AIConversation<AgentMessage>

    init(transport: AgentTransport) {
        var approver = transport.approver
        // Opens the sign-in in the system's sign-in sheet, and declines it on Not now.
        approver.authorizer = AIToolAuthorizer(callbackScheme: "com.example.assistant") { call in
            try await transport.session.declineLogin(call.id)
        }
        _conversation = StateObject(
            wrappedValue: AIConversation(transport: transport, approver: approver, actions: [.rate])
        )
    }

    var body: some View {
        AIConversationView(conversation: conversation)
            .safeAreaInset(edge: .bottom) {
                AIComposerView(conversation: conversation)
            }
    }
}
Dart
import 'package:flutter/services.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
import 'package:stream_chat_flutter_ai/stream_chat_flutter_ai.dart';
import 'package:stream_agents/stream_agents.dart';

// Where the sign-in comes back: your app's own scheme. Pass the same URL when the session opens:
// agents.agent('support').sessions.create(const SessionOptions(returnUrl: 'com.example.assistant:/connected'))
AIToolApprover connectingApprover(AgentSession session) => AIToolApprover(
  identity: AIClientIdentity(userId: session.backend.userId),
  // Answers the questions of the tools this app gave the session.
  decide: (call, decision) async {
    // The session ignores an answer to a call it isn't waiting on, such as one asked before
    // the app was relaunched, so say so rather than show the answer as sent.
    if (!session.approvals.value.any((request) => request.id == call.id)) {
      throw StateError('This question is no longer waiting for an answer.');
    }
    session.decide(call.id, allowed: decision == AIToolApprovalDecision.allowed);
  },
  authorizer: AIToolAuthorizer(
    connect: (call, url) => signIn(url),
    decline: (call) async => session.declineLogin(call.id),
  ),
);

/// Opens the sign-in in the system's sign-in sheet, and completes with whether the user connected.
Future<bool> signIn(Uri url) async {
  try {
    final back = await FlutterWebAuth2.authenticate(
      url: '$url',
      callbackUrlScheme: 'com.example.assistant',
      options: const FlutterWebAuth2Options(preferEphemeral: true),
    );
    // The router sends the browser back with `status=connected` once it holds the grant.
    return Uri.parse(back).queryParameters['status'] == 'connected';
  } on PlatformException catch (error) {
    if (error.code == 'CANCELED') return false; // closed without connecting
    rethrow; // the card says the sign-in couldn't be opened
  }
}
Kotlin only

SignIns opens the page in a Custom Tab and resumes once the browser comes back, as in the Android SDK's Tool sign-ins, which has its activity code and manifest entry. Give the approver to the conversation's AIConversationState, as the quickstart's chat UI does.

Swift only

AIToolAuthorizer comes with StreamChatAI from version 5.15.0 of the Stream Chat Swift SDK. Tool sign-ins in the iOS guide covers the card, what happens when the user taps Connect, and a card in your own design.

Flutter only

signIn opens the page with flutter_web_auth_2, which needs its callback activity for your scheme in AndroidManifest.xml, as in the Flutter SDK's Tool sign-ins. Without preferEphemeral: true, the sign-in page shares the cookies of the device's browser, so a connection takes the account already signed in there, even when it's someone else's. Give the approver to the conversation's AIConversation, as the quickstart's AgentConversation does with the transport's approver(), and dispose it with the conversation.

React only

AIConversation, createPopupAuthorizer and AIClientIdentity come from stream-chat-react/ai-components.

session.decide answers only a question this session was asked on its own connection. A tool approval shown from the channel's history, after sessions.resume or after the page reloads, isn't answered: decide does nothing and doesn't throw, so the card keeps waiting. With an AgentChat, as in the quickstart, chat.decide(call.id, { allowed }) answers that one too, from what the reply shows.

React (v14) only

The same code runs on stream-chat-react 14.15.0 or later, which brought tool approvals and sign-ins. Render ConnectedConversation inside <Chat> or a TranslationProvider, as the quickstart's src/main.tsx does: stream-chat-react 14 translates only inside one, and without it the AI components show their keys. Tool sign-ins in the React v14 guide covers the card and what happens when the user taps Connect.

React Native only

createAuthSessionAuthorizer opens the page in the platform's sign-in session (ASWebAuthenticationSession on iOS, and on Android the browser's Auth Tab, or a Custom Tab where the browser has none), which comes back on your app's scheme, so declare that scheme, such as scheme in Expo's app.json. Tool sign-ins in the Chat SDK's guide covers the card and what happens when the user taps Connect.

With Expo Router, a sign-in opened in a Custom Tab also comes back as a link to a page your app doesn't have. Return null for it from redirectSystemPath in app/+native-intent.tsx, so the app stays on the screen that opened the sign-in, as the React Native assistant sample does.

session.decide answers only a question this session was asked on its own connection. A tool approval shown from the channel's history, after sessions.resume or after the app restarts, isn't answered: decide does nothing and doesn't throw, so the card keeps waiting. With an AgentChat, as in the quickstart, chat.decide(call.id, { allowed }) answers that one too, from what the reply shows.

React Native (v9) only

The same code runs on stream-chat-expo 9.14.0 or later. See Tool sign-ins in the v9 guide.

session.decide answers only the tools your page registered. A connector call held for the user's approval by require_approval is answered by that user or your backend over the session's socket, which the JavaScript SDK has no call for yet.

React only

The return page reports how the sign-in went and closes the popup. It imports a package, so build it with your app's bundler as a second page, such as connected.html in Vite's build.rolldownOptions.input (build.rollupOptions.input before Vite 8):

connected.html
<script type="module">
  import { completeConnectorSignIn } from "stream-chat-react/ai-components";
  completeConnectorSignIn();
</script>

Connect opens the sign-in in a popup, and the same reply goes on once the user is in. Not now calls session.declineLogin, so the call runs nothing and the agent says the user didn't connect. On iOS and Android, React Native included, name your app's own scheme in reverse domain form, such as com.example.assistant:/connected, as the session's returnURL or returnUrl, and the sign-in card opens the page in the system's sign-in sheet. The React, React Native, Swift, Android and Flutter assistant samples do this.

A sign-in comes back only to the returnUrl the session was created with, so a conversation started on a phone finishes its sign-ins on that phone.

Connect from your app

Your app can also show its own Connect button. Your server starts the sign-in, your app opens it in a popup, and the popup comes back to your page:

sequenceDiagram
  participant B as Your backend
  participant F as Your frontend
  participant R as Stream router
  actor U as User
  participant P as Provider
  B->>R: connections.create
  R-->>B: id, status pending
  B->>R: connections.authorize
  R-->>B: launch_url, handoff_token
  B-->>F: launch_url, handoff_token
  F->>R: open launch_url in a popup
  R-->>F: va.connector.oauth.ready
  F->>R: va.connector.oauth.handoff with handoff_token
  R->>P: the popup goes to the provider
  U->>P: signs in and approves
  P->>R: the popup comes back to the router
  R-->>F: the popup goes to returnUrl?connection_id=...&status=connected

Your server: create the connection

Your server creates the connection with Stream's server SDK. The userId option (UserID in Go) names the user it's for:

Not documented for Python yet. Showing Node.js.

Not documented for Ruby yet. Showing Node.js.

Not documented for PHP yet. Showing Node.js.

Not documented for .NET yet. Showing Node.js.

Not documented for Rust yet. Showing Node.js.

Node.js
// STREAM_API_KEY and STREAM_API_SECRET are in the environment.
import { Client } from "@stream-io/stream-agents";

const stream = new Client();

const connection = await stream.connections.create("linear", {
  userId: "alice",
});
Go
// STREAM_API_KEY and STREAM_API_SECRET are in the environment.
api, err := client.New(stream.Backend{})
if err != nil {
	log.Fatal(err)
}

connection, err := api.Connections().Create(ctx, client.ConnectionRequest{
	Connector: "linear",
	UserID:    "alice",
})
if err != nil {
	log.Fatal(err)
}

It returns the connection, pending, with its id. Keep the id with your user: you need it to check the status and to reconnect.

Your server: start the sign-in

Start the sign-in on that connection:

Not documented for Python yet. Showing Node.js.

Not documented for Ruby yet. Showing Node.js.

Not documented for PHP yet. Showing Node.js.

Not documented for .NET yet. Showing Node.js.

Not documented for Rust yet. Showing Node.js.

Node.js
const { launch_url, handoff_token } = await stream.connections.authorize(
  connection.id,
  {
    returnUrl: "https://app.example.com/settings/integrations",
    userId: "alice",
  },
);
Go
authorization, err := api.Connections().Authorize(ctx, *connection.Id, client.AuthorizeOptions{
	ReturnURL: "https://app.example.com/settings/integrations",
	UserID:    "alice",
})
if err != nil {
	log.Fatal(err)
}
// authorization.LaunchUrl and authorization.HandoffToken

It returns a launch_url and a handoff_token for your app. The sign-in expires 10 minutes later, and both calls are server-side only.

returnUrl must be https, or http on localhost. Without returnUrl, the sign-in goes back to the dashboard.

In your app: open the popup

Open the popup from a page on the returnUrl's origin: the popup takes the handoff token from that origin only. Wait for the popup's ready message, then post it the token:

Not documented for React Native yet. Showing React.

Not documented for React Native (v9) yet. Showing React.

Not documented for Kotlin yet. Showing React.

Not documented for Swift yet. Showing React.

Not documented for Flutter yet. Showing React.

ReactReact Native
const popup = window.open(
  "about:blank",
  "connect",
  "popup,width=520,height=720",
);
const { launchUrl, handoffToken } = await startConnect(); // your backend makes both calls
const routerOrigin = new URL(launchUrl).origin;
popup.location = launchUrl;
window.addEventListener("message", (event) => {
  if (event.source !== popup || event.origin !== routerOrigin) return;
  if (event.data?.type !== "va.connector.oauth.ready") return;
  popup.postMessage(
    { type: "va.connector.oauth.handoff", handoff_token: handoffToken },
    routerOrigin,
  );
});

The handoff token works once.

Your return page: tell the opening page

When the sign-in ends, the popup lands on your returnUrl:

https://app.example.com/settings/integrations?connection_id=...&status=connected

status is one of:

  • connected: the user signed in, and the account is stored.
  • denied: the user cancelled or refused at the provider.
  • failed: the sign-in didn't complete.
  • account_mismatch: the user signed in to a different provider account than the connection holds, or than their email allows. Nothing is stored, and a reconnect keeps the old grant.

Pass status on to the opening page, for instance with a same-origin BroadcastChannel, then close the popup.

Your server: check the status

Not documented for Python yet. Showing Node.js.

Not documented for Ruby yet. Showing Node.js.

Not documented for PHP yet. Showing Node.js.

Not documented for .NET yet. Showing Node.js.

Not documented for Rust yet. Showing Node.js.

Node.js
const { status } = await stream.connections.get(connection.id, {
  userId: "alice",
});
Go
current, err := api.Connections().Get(ctx, *connection.Id, client.ConnectionOptions{
	UserID: "alice",
})
if err != nil {
	log.Fatal(err)
}
// current.Status
status What it means What to do
pending Nobody has signed in yet. It stays pending after a failed sign-in Start a sign-in again
connected The user signed in, and the agent can use the account Nothing
needs_reauthorization The provider no longer accepts the credential Reconnect
disconnected The connection was deleted Create a new one

Reconnect

Start a new sign-in on the same connection, and open its launch_url the same way. Until the user finishes, the connection stays as it was.

Disconnect a user

getstream agents connections delete linear --user alice

The CLI finds alice's connection to linear and deletes it. Deleting a connection drops its credentials at once, so no agent can use the account any more, and its status turns disconnected. The provider isn't asked to revoke the grant: the user does that in the provider's own settings. To connect the account again, create a new connection.

OAuth clients

To put your app's name on the consent screen, set your own OAuth client. See Sign-in and OAuth clients.

Going further