# TypeScript SDK

A small client for TypeScript and JavaScript with no dependencies.

The TypeScript SDK is a thin client for the [REST API](https://millionshort.com/docs/search/parameters), for TypeScript and JavaScript. It has no dependencies and uses the platform's own `fetch`, so it needs Node.js 18 or later.

Call it from your server. Do not put your API key in code that runs in a browser.

## Install

```bash
npm install millionshort
```

**Not published yet.** The package is not on the public registry yet, so this command finds nothing today; it works once the package is published. Until then, call the REST API directly: every method below is one request, and the reference pages show each one with `curl`.

## Create a client

The package has a named export, `MillionShort`. There is no default export.

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });
```

| Option | Default | Meaning |
|---|---|---|
| `apiKey` | none | Your key. Read it from the environment yourself; the client does not. |
| `baseUrl` | `https://api.millionshort.com` | The API address. |
| `timeoutMs` | `60000` | Milliseconds to wait for one request. |
| `maxRetries` | `2` | How many times a request that is safe to repeat is retried. |

## Search

Options are written in camelCase and sent as the snake_case fields of the [Search reference](https://millionshort.com/docs/search/parameters): `removeTopSites` is `remove_top_sites`.

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const r = await client.search('sourdough starter hydration', {
  sources: ['web', 'smallweb'],
  removeTopSites: 10000,
  numResults: 20,
  excludeDomains: ['example.com'],
  explain: true,
});

for (const hit of r.results) {
  console.log(hit.position, hit.site, hit.popularity.bucket);
  console.log('   ', hit.title);
  console.log('   ', hit.url);
  for (const reason of hit.why ?? []) console.log('    why:', reason);
}

console.log(r.summary.returned, 'returned;', r.summary.removed.popularity, 'removed by popularity');
console.log(r.usage?.credits, 'credits; request', r.requestId);
for (const warning of r.warnings) console.log('warning:', warning.code, warning.message);
```

The options are `sources`, `numResults`, `removeTopSites`, `onlyTopSites`, `includeDomains`, `excludeDomains`, `boostDomains`, `buryDomains`, `pageTypes`, `topics`, `safeSearch`, `maxCharsPerResult` and `explain`. The filters, highlights and page content are options too, under the names of the reference in camelCase: for example `startDate`, `language`, `country`, `excludePageTypes`, `boostTopics`, `trafficTrend`, `popularIn`, `siteTech`, `excludeRisky`, `maxHighlights` and `includeContent`. An option you leave out uses the API's default.

## What comes back

The API wraps its answer as `data`, `usage`, `warnings` and `request_id`. The SDK unwraps it:

- the fields of `data` sit directly on the result: `r.results`, `r.summary`;
- `r.usage` has `credits`, `cost_usd` and `breakdown`;
- `r.warnings` is an array;
- `r.requestId` is a string.

The fields inside a result keep the API's names, so a result has `published_date` and `page_type`.

## Sources and domain info

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const catalog = await client.listSources();
console.log(catalog.sources.map((source) => source.slug));
console.log(catalog.page_types.map((pageType) => pageType.slug));

const info = await client.getDomainInfo(['example.com', 'blog.example.org']);
for (const entry of info.domains) {
  console.log(entry.domain, entry.popularity.bucket, entry.risk);
}
```

## Map and Crawl

`map` lists the URLs of a site. `crawl` starts a job that returns the site's pages as clean text:

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const found = await client.map('https://example.org/', { search: 'pricing', limit: 20 });
for (const u of found.urls) console.log(u.url, u.title);

let job = await client.crawl('https://example.org/docs', { maxPages: 50, include: ['^/docs/'] });
while (job.status === 'queued' || job.status === 'running') {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  job = await client.getCrawl(job.id);
}

for (const page of job.results ?? []) {
  if (page.status === 'ok') console.log(page.depth, page.url, page.page_type);
  else console.log(page.url, 'failed:', page.error?.code);
}
console.log(job.completed, 'pages,', job.credits_used, 'credits');
```

| Method | Does |
|---|---|
| `map(url, options?)` | Lists a site's URLs. The options are the other fields of a [Map request](https://millionshort.com/docs/map/parameters#request) in camelCase: `search`, `limit`, `includeSubdomains`, `include`, `exclude`, `sources` |
| `crawl(url, options?)` | Starts a crawl and returns the job. The options are the other fields of a [crawl request](https://millionshort.com/docs/crawl/parameters#request) in camelCase: `maxPages`, `maxDepth`, `include`, `exclude`, `mode` and the rest |
| `getCrawl(id, { cursor })` | The crawl, with a page of its results. Pass `next` as `cursor` for the following page. Free |
| `listCrawls({ limit })` | Your team's crawls, newest first, without results. Free |
| `cancelCrawl(id)` | Stops a crawl. The pages that came back are kept and stay charged |
| `waitCrawl(id, options?)` | Polls until the crawl ends, then returns it with every page of results. It polls every 5 seconds unless `pollIntervalMs` says otherwise, and gives up after `timeoutMs` (10 minutes by default; the crawl keeps running). A large crawl takes hours: give it a timeout to match, or poll `getCrawl` yourself |

A map costs 1 credit per 10 URLs returned, and a crawled page 1 credit in `live`: see [Map pricing](https://millionshort.com/docs/map/pricing) and [Crawl pricing](https://millionshort.com/docs/crawl/pricing). A page that fails is free.

## Spaces

A [Space](https://millionshort.com/docs/search/spaces) is a saved scope for search. Create one, then pass its slug or id as `space` on `search`:

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const baking = await client.createSpace('Baking', {
  sites: ['example.org', 'example.com/blog'],
  removeTopSites: 1000,
});

const r = await client.search('sourdough hydration', { space: baking.slug });
console.log(r.results.length, 'results from', r.space?.sites_applied, 'sites');

const listing = await client.listSpaces({ scope: 'all' });
for (const entry of listing.spaces) console.log(entry.slug, entry.curated);

await client.updateSpace(baking.id, { removeTopSites: 10000 });
await client.deleteSpace(baking.id);
```

| Method | Does |
|---|---|
| `createSpace(name, options)` | Creates a Space. The options are the fields of the [Space object](https://millionshort.com/docs/spaces#the-space-object) in camelCase: `sites`, `mode`, `removeTopSites`, `lens` and the rest |
| `listSpaces(options)` | Lists Spaces: `scope` is `'own'` (the default), `'curated'` or `'all'` |
| `getSpace(id)` | Reads one, by id, by your slug, or as `'curated:<slug>'` |
| `updateSpace(id, patch)` | Changes the fields given; the others stay. `lens` is one field: a `lens` given replaces all three of its lists |
| `deleteSpace(id)` | Deletes it |
| `importSpaces(spaces)` | Loads Spaces exported from the MillionShort search site: the export file as an object, or an array of entries |
| `search(query, { space })` | Searches with a Space. An option you pass beside it replaces the Space's value for that setting |

All of them are free; a search with a Space costs what the search costs. A Space that does not exist rejects with `NotFoundError`, with the code `SPACE_NOT_FOUND`. A curated Space cannot be changed: `MillionShortError`, with the code `SPACE_READ_ONLY`.

## Places

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const r = await client.places({ query: 'coffee', near: 'Leslieville, Toronto', limit: 5 });
for (const place of r.results) {
  console.log(place.name, place.address.formatted, place.phone);
}
console.log(r.attribution.text);
```

The options are the fields of a [Places request](https://millionshort.com/docs/places/parameters#request), in camelCase: `query`, `category`, `excludeCategory`, `brand`, `near`, `lat`, `lng`, `bbox`, `ip`, `nearMe`, `neighbourhood`, `city`, `region`, `country`, `radiusM`, `hasPhone`, `hasWebsite`, `hasHours`, `openNow`, `sort`, `fields` and `limit`. If you show the places to people, show `attribution` with them.

```ts
const nearby = await client.places({
  category: 'Coffee shop',
  neighbourhood: 'Leslieville',
  city: 'Toronto',
  hasWebsite: true,
  sort: 'distance',
  fields: ['name', 'distance_m', 'website'],
});
```

`nearMe: true` searches around the city of the machine that runs this code. On a server, send the person's own address as `ip`, or a position they shared as `lat` and `lng`.

`listPlaceCategories()` returns the categories `category` takes, free: `client.listPlaceCategories({ q: 'sushi' })`, or `{ parent: 'italian_restaurant' }` for what is directly under a category.

## Agent

The methods of [Agent](https://millionshort.com/docs/agent).

A question in, an answer with a checked quote for every statement out. A run is a job: start it, then wait for it.

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const run = await client.startAgent(
  'What does a monthly adult pass cost on Northbridge Transit in 2026, and when did the price last change?',
  { processor: 'lite', maxCredits: 40, idempotencyKey: 'fares-2026-11-20' },
);

const done = await client.waitAgent(run.id, { pollIntervalMs: 2000, timeoutMs: 600_000 });
console.log(done.status, done.stop_reason);
console.log(done.answer);
for (const cite of done.citations ?? []) console.log(cite.n, cite.url, cite.quote);
console.log(done.usage?.credits, done.usage?.steps);
```

| Method | Does |
|---|---|
| `startAgent(prompt, options)` | Starts a run and resolves to it, with its `id`. The options are the fields of an [Agent request](https://millionshort.com/docs/agent/parameters#request), in camelCase: `urls`, `schema`, `sources`, `space`, `removeTopSites`, `includeDomains`, `excludeDomains`, `startDate`, `processor`, `model`, `maxCredits` and `webhookId`. `idempotencyKey` is sent as the `Idempotency-Key` header, and lets the client retry the call |
| `getAgent(id)` | The run: status, progress and steps, and the result once it has ended. Free |
| `getAgentResults(id)` | The result alone. `ready` is `false` while the run is going, which is not an error. Free |
| `waitAgent(id, { pollIntervalMs, timeoutMs })` | Polls until the run is `completed`, `incomplete`, `failed` or `cancelled`, and resolves to it. Past `timeoutMs` it rejects with `PollTimeoutError`; the run goes on |
| `streamAgentEvents(id, { after })` | An async iterator of the steps as they happen: `agent.step` for each, then one `agent.done`. Free |
| `cancelAgent(id)` | Cancels the run. The work already done is charged |

`citations[n-1]` is the page behind the `[n]` marker of `answer`: `n`, `url`, `title`, `source` and `quote`. With `schema`, read `output`, `field_citations` and `uncited_fields` in place of `answer`. The fields of a run keep the API's names. An `incomplete` run does not reject: `stop_reason` says why it ended early.

```ts
import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const run = await client.startAgent('What changed in Northbridge Transit fares in 2026?', { processor: 'lite' });
let last = 0;
for await (const { event, data } of client.streamAgentEvents(run.id)) {
  if (event === 'agent.step') {
    last = data.seq;
    console.log(last, data.type);
  } else {
    console.log('ended:', data.status, data.stop_reason);
  }
}
```

A stream is closed after 5 minutes at most. If it ends with no `agent.done`, call again with `{ after: last }`.

A run is metered, and never costs more than `maxCredits`. [Agent pricing and limits](https://millionshort.com/docs/agent/pricing) has the prices, and [Agent errors](https://millionshort.com/docs/agent/errors) what a start can be refused for.

## Errors

Every failure rejects with a subclass of `MillionShortError`:

| Class | Raised for |
|---|---|
| `ValidationError` | `INVALID_PARAM` |
| `UnsupportedOptionError` | `UNSUPPORTED_OPTION` |
| `AuthenticationError` | `AUTH_INVALID_KEY`, `AUTH_MISSING_KEY` |
| `MillionShortError` | `QUOTA_EXCEEDED`, `ACCOUNT_NOT_ELIGIBLE`, `ACCOUNT_SUSPENDED` |
| `NotFoundError` | `NOT_FOUND` |
| `RateLimitError` | `RATE_LIMITED` |
| `CapacityError` | `CAPACITY` |
| `InsufficientCreditsError` | `INSUFFICIENT_CREDITS` |
| `ServerError` | `INTERNAL` |
| `SearchUnavailableError` | `SEARCH_UNAVAILABLE` |
| `APIConnectionError` | The request never reached the API (network failure or timeout). |

Each error has `code`, `message`, `requestId`, `details`, `retryAfterSeconds` and `statusCode`.

```ts
import {
  CapacityError,
  InsufficientCreditsError,
  MillionShort,
  MillionShortError,
  RateLimitError,
  SearchUnavailableError,
} from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

let r;
for (let attempt = 0; attempt < 4 && !r; attempt += 1) {
  try {
    r = await client.search('tide tables', { numResults: 5 });
  } catch (error) {
    if (
      error instanceof RateLimitError ||
      error instanceof CapacityError ||
      error instanceof SearchUnavailableError
    ) {
      const seconds = error.retryAfterSeconds ?? 2 ** attempt;
      await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
    } else if (error instanceof InsufficientCreditsError) {
      throw new Error('Out of credits.');
    } else if (error instanceof MillionShortError) {
      throw new Error(`${error.code}: ${error.message} (request ${error.requestId})`);
    } else {
      throw error;
    }
  }
}
if (!r) throw new Error('Still failing after four attempts.');

console.log(r.results.length, 'results');
```

## Retries

The client retries a `GET`, such as `listSources`, on `429` and on a server error, waiting as long as the API asks. It does not repeat a `POST` on its own, so a failed `search` rejects at once: retry it yourself, as in the example above. The [Errors](https://millionshort.com/docs/errors) page says which codes are worth a retry.

## A trial key

An agent with no key can get a short-lived one:

```ts
import { MillionShort } from 'millionshort';

const { api_key } = await new MillionShort().createAgentKey('my-agent');
const client = new MillionShort({ apiKey: api_key });
```

See [Authentication](https://millionshort.com/docs/authentication#trial-key-for-agents).
