# SDK quickstart

Create a user, open their session and stream the agent's reply from a script on your server.
It takes about fifteen minutes and needs no wallet or funds.

## Before you begin

- **A runtime with `fetch`**: Node 20 or later, Bun or Deno.
- **An API URL and an API key** from your deployment operator. The key never leaves your server.
- **TypeScript 5.4 or later**, if you type-check. The SDK ships its own types.

> [!NOTE]
> The packages are not on npm yet. They publish with their first release.

## 1. Install

```sh
npm install @nearai/financial-agents-sdk
```

## 2. Create the client

Create one client and share it across your server.

```ts title="fin.ts"
import { createFinClient } from "@nearai/financial-agents-sdk";

export const fin = createFinClient({
  baseUrl: process.env.FIN_BASE_URL ?? "https://api.example.test",
  apiKey: process.env.FIN_API_KEY ?? "",
});
```

## 3. Create the user

`userId` is your own id for the user: letters, digits, `.`, `_`, `:` and `-`, never an email
address. Creating a user again returns the same user.

```ts
const created = await fin.users.create({ userId: "customer-123", name: "Example user" });
console.log(created.agentId); // the user's agent
```

## 4. Open a session

After your own login succeeds, vouch for the user by naming the wallet they signed in with. They
sign nothing here.

```ts
const { token } = await fin.users.createSession("customer-123", {
  controller: { kind: "evm", chainId: 1, address: "0x0000000000000000000000000000000000000001" },
});
```

- The first session registers this wallet for good. It signs anything that moves money.
- A session lasts one hour. When a call rejects with `credential_expired`, open a new one.
- NEAR, Solana, Stellar, TON and Tron wallets and passkeys work too: see
  [Authentication](/authentication). Without a login of your own, use
  [wallet sign-in](/sdk-recipes#sign-users-in).

> [!WARNING]
> Keep `token` on your server. Never put it in a page, a URL or browser storage.

## 5. Send a message

Every user has a main conversation. Send the message there:

```ts
const user = fin.user({ userId: "customer-123", token });
const conversation = await user.conversations.main();
const run = await user.runs.start(
  {
    conversationId: conversation.id,
    text: "Say hello in one sentence.",
    profile: { tools: [] },
    context: { timeZone: "America/New_York" },
  },
  { idempotencyKey: crypto.randomUUID() },
);
```

| Field | Purpose |
| --- | --- |
| `idempotencyKey` | Made once per message. A retry with the same key returns the same run. |
| `profile.tools` | `[]` turns tools off for this run. Leave `profile` out to allow every enabled tool. |
| `context.timeZone` | The user's time zone, so "9am" means their 9am. Send it with every message. |
| `context.country` | The user's uppercase two-letter country code from your server's edge geolocation, never the browser. Send it with every message; omit it when unavailable. |

Tokenized-stock purchases require a country outside the United States and Canada and an
operator-enabled `tokenized_stocks` flag. Once held, these assets can only be sold, never withdrawn or sent;
see [Tokenized stocks](/concepts#tokenized-stocks) for the country rule when selling.

## 6. Stream the reply

`events.stream` replays the conversation, then follows it live. Skip to your run, print its text
as it is written, and stop when it ends:

```ts
const stop = new AbortController();
let ours = false;
for await (const event of user.events.stream(conversation.id, { signal: stop.signal })) {
  if (event.type === "run.started") ours = event.payload.runId === run.id;
  if (!ours) continue;
  if (event.type === "agent.text_delta") process.stdout.write(event.payload.text);
  if (event.type === "run.ended") stop.abort();
}
```

`agent.text_delta` is live text and is never replayed; the saved `agent.entry` replaces it. The
stream reconnects by itself and resumes after the last saved event.

## The complete script

```ts title="quickstart.ts"
import { createFinClient, FinApiError } from "@nearai/financial-agents-sdk";

const fin = createFinClient({
  baseUrl: process.env.FIN_BASE_URL ?? "https://api.example.test",
  apiKey: process.env.FIN_API_KEY ?? "",
});

try {
  await fin.users.create({ userId: "customer-123", name: "Example user" });
  const { token } = await fin.users.createSession("customer-123", {
    controller: { kind: "evm", chainId: 1, address: "0x0000000000000000000000000000000000000001" },
  });
  const user = fin.user({ userId: "customer-123", token });
  const conversation = await user.conversations.main();
  const run = await user.runs.start(
    { conversationId: conversation.id, text: "Say hello in one sentence.", profile: { tools: [] } },
    { idempotencyKey: crypto.randomUUID() },
  );
  const stop = new AbortController();
  let ours = false;
  for await (const event of user.events.stream(conversation.id, { signal: stop.signal })) {
    if (event.type === "run.started") ours = event.payload.runId === run.id;
    if (!ours) continue;
    if (event.type === "agent.text_delta") process.stdout.write(event.payload.text);
    if (event.type === "run.ended") stop.abort();
  }
} catch (error) {
  // Every refusal is a FinApiError: quote its requestId when you report it.
  if (error instanceof FinApiError) console.error(error.status, error.reason, error.requestId);
  else throw error;
}
```

## Next steps

- [**SDK recipes**](/sdk-recipes) — Relay to the browser, approve money actions, fund and withdraw.
- [**React quickstart**](/react-quickstart) — Draw the conversation with Fin's blocks.
- [**SDK reference**](/sdk-reference) — Every method, option, error and type.
