> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getclean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> getclean's own MCP server is at https://mcp.getclean.ai/mcp. The /mcp path of this docs site is Mintlify's search over these pages, not getclean.
> Every answer of the API opens with outcome. A page that could not be read is a record whose outcome says why, never an HTTP error; read outcome before anything else.
> The API's contract is the OpenAPI 3.1 file at https://docs.getclean.ai/openapi.yaml; the SDKs are generated from it.
> The product's name is written getclean, in lower case.

# getclean for TypeScript

> The getclean package for TypeScript and JavaScript, for a research agent and for the person who builds one: create the client, make the first fetch and read the record, run the research loop, read a record again for free, upload documents, handle errors, retry safely, and keep every request inside a budget.

The `getclean` package calls the getclean API from TypeScript and JavaScript, in Node and in the other runtimes that have `fetch`. It's generated from the API's OpenAPI contract, so each of the 22 operations is a method of the client named in camelCase, such as `fetchContents`, taking one request object whose members keep the API's own names, such as `max_characters`. The answer is typed with the record's members, and a member that only sometimes applies is optional, so the compiler makes you check before you read it. Every method's JSDoc is the operation's description from the contract. On top of the generated code, a small hand-written layer does the things a research agent would otherwise write itself: it follows an upload's job to the record, pages a long section, drops repeated items from a list, and retries a request whose first attempt is still running.

```bash theme={"theme":"css-variables"}
npm install getclean
```

## Create the client

```typescript theme={"theme":"css-variables"}
import { GetClean } from "getclean";

const client = new GetClean({}); // reads GETCLEAN_API_KEY
```

With no `apiKey`, the client reads your API key from `GETCLEAN_API_KEY`. If there's no key there and you pass none, the constructor throws right away, with the message "apiKey is required: pass it to the client or set the environment variable GETCLEAN\_API\_KEY." A missing key never looks like a network problem.

You can pass the key, or a function that returns an access token:

```typescript theme={"theme":"css-variables"}
const withKey = new GetClean({ apiKey: "your-api-key" });

const withToken = new GetClean({ apiKey: async () => readAccessToken() });
```

The SDK calls your function when it needs a credential and never refreshes a token itself, so the function returns a token that's still valid. [Authenticate a request](https://docs.getclean.ai/start/authentication.md) covers both kinds of credential.

The client talks to `https://api.getclean.ai`. To point it elsewhere, pass `baseUrl` or set `GETCLEAN_BASE_URL`.

## The first fetch, and how to read it

```typescript theme={"theme":"css-variables"}
const record = await client.fetchContents({
  url: "https://example.com/q3",
  highlights: ["Revenue rose 12%", "what drove the margin"],
  summary: true,
});

record.outcome.kind;             // "delivered"
record.outcome.reason;           // "whole"
record.highlights?.[1].basis;    // "judged"
record.highlights?.[1].block_id; // "b9"
record.cost?.actual.amount;      // "0.0090"
record.id;                       // "cnt_3Fk9abaUhNX7t2eKkgfd3e"
```

Read `outcome` first, every time. A page that couldn't be read is still a record, returned normally, and its outcome says why. Nothing is thrown for a failed page:

```typescript theme={"theme":"css-variables"}
const offer = await client.fetchContents({ url: "https://shop.example/offer" });

if (offer.outcome.kind === "failed" || offer.outcome.kind === "refused" || offer.outcome.kind === "needs_person") {
  console.log(offer.outcome.reason);  // "challenge_served"
  console.log(offer.outcome.message); // what may work next
}
```

A record that failed, was refused or needs a person has no content, and `offer.cost?.actual.amount` is `"0.0000"`. Notices come right after the outcome and are worth a look before you use the result:

```typescript theme={"theme":"css-variables"}
for (const notice of record.notices) {
  console.log(notice.code, notice.message);
}
```

[Records](https://docs.getclean.ai/understand/records.md) says what a record has, and [Outcomes and notices](https://docs.getclean.ai/understand/outcomes-and-notices.md) lists every reason and code.

## Requests and types

Every request is one object, including the ids from the path: `client.getContents({ contents_id: record.id, max_characters: 0 })`, `client.getSection({ contents_id: record.id, section_id: "s2" })`. A field whose value is an object takes an object literal with the API's names:

```typescript theme={"theme":"css-variables"}
const result = await client.search({
  query: "EU AI Act article 50 marking obligations",
  published_within_days: 365,
  max_candidates: 3,
  contents: { top: 1, max_characters: 8000 },
  max_cost: { amount: "0.1000", currency: "USD" },
});

result.candidates[0].contents?.id; // "cnt_8Lq5XFriyaJ0jEc2oPNx6E"
```

Amounts are strings, as the API sends them, so there's no floating point in your money. The API's types are under the `GetClean` namespace, and a closed set is both a type and a set of values, so `GetClean.Candidate.DroppedReason.FoldedCopy` is a value you can compare against. An open set such as `outcome.reason` is typed as a string, so a value added in a later version arrives without breaking anything.

The optional members follow the API's own rule. A record always has `id`, `outcome`, `notices`, `fetched_at`, `truncated`, `source`, `execution`, `retention`, `run_id`, `expires_at` and `request_id`. Everything else is there only while its condition holds, and the SDK types it with `?`, so with strict null checks on you check before you read. A member the API sends as `null` is typed `| null`, which is a different thing from absent: a candidate's `relevance_score` is `number | null`, and it's `null` under `deterministic_only`.

```typescript theme={"theme":"css-variables"}
const fetched = await client.fetchContents({ url: "https://example.com/q3" });
fetched.cost?.actual.amount; // the fetch's bill

const again = await client.getContents({ contents_id: fetched.id });
again.cost;                  // undefined: reading a record you already have is free
```

## The research loop

This is the loop a research agent runs, in TypeScript: search, fetch the best result, find where it says the thing, read the rest for free, and keep a pointer that survives.

```typescript theme={"theme":"css-variables"}
import { GetClean } from "getclean";

const client = new GetClean({});

// 1. Search, with a spending limit, and let the search fetch the top result in the same call.
const found = await client.search({
  query: "EU AI Act article 50 marking obligations",
  published_within_days: 365,
  max_candidates: 5,
  contents: { top: 1, max_characters: 8000 },
  max_cost: { amount: "0.1000", currency: "USD" },
});

const lead = found.candidates[0];
const recordId = lead.contents!.id; // the fetched record, already yours

// 2. Find where the record says what you need. Strings found word for word are free.
const places = await client.highlightContents({
  contents_id: recordId,
  highlights: ["machine-readable format", "which obligations apply to deployers"],
  max_characters: 0,
});
for (const h of places.highlights) {
  console.log(h.query_index, h.basis, h.section_id, h.block_id);
}

// 3. Read the section that holds the answer, for free.
const section = await client.getSection({ contents_id: recordId, section_id: places.highlights[0].section_id });
console.log(section.markdown);

// 4. Keep a pointer for the citation pass: the record, its fingerprint, and the place.
const citation = {
  record: recordId,
  fingerprint: section.fingerprint,
  section: places.highlights[0].section_id,
  block: places.highlights[0].block_id,
};
```

Every read of a record you already have is free and keeps the record alive for another 48 hours. The pointer in step 4 is what makes a claim checkable later: the same fingerprint means the same text. [Records](https://docs.getclean.ai/understand/records.md) explains how long a record is kept, and the guides under Contents and Search show each call with its full response.

## Reading a record again

`getContents` returns the same record in any format, at any size, under either view, with the highlights, summary and schema values the fetch produced. It's free, so the record it returns has no `cost`:

```typescript theme={"theme":"css-variables"}
const whole = await client.getContents({ contents_id: recordId, max_characters: 200000 });
const outline = await client.getContents({ contents_id: recordId, max_characters: 0 });
const tables = await client.getContents({ contents_id: recordId, formats: ["json"], block_kinds: ["table"] });
```

A long section comes in pieces. `iterSection` walks them for you, one page of the section at a time, until there's no more:

```typescript theme={"theme":"css-variables"}
for await (const page of client.iterSection({ contents_id: recordId, section_id: "s4", max_characters: 8000 })) {
  console.log(page.markdown);
}
```

Each page is a `SectionContents`, the same object `getSection` returns, so you can break out whenever you have enough.

## Pagers

The seven list operations return a page that you can iterate with `for await`, and it reads the next page when it needs to:

```typescript theme={"theme":"css-variables"}
for await (const item of await client.listContents({ url: "https://example.com/*" })) {
  console.log(item.id, item.source.title, item.expires_at);
}

for await (const block of await client.listBlocks({ contents_id: recordId, block_kinds: ["table"] })) {
  console.log(block.page_number, block.table?.rows);
}
```

The page's own members live on `response`. A page of blocks, for example, repeats the record's fingerprint and version:

```typescript theme={"theme":"css-variables"}
const page = await client.listBlocks({ contents_id: recordId, block_ids: ["b7"] });
page.response.fingerprint;
page.response.version;
```

`listLinks`, `listDatasources`, `getSearch` and `compareContents` page the same way. On `listContents` and `listJobs`, a record or a job created while you page can make an item appear twice, and the SDK drops the repeat for you, by `id`.

## Uploading a document

`document` takes a path, a Buffer, a Blob or File, or a stream. A long document runs as a job, and with `wait: true` the SDK follows the job to the record:

```typescript theme={"theme":"css-variables"}
import { GetClean, JobCanceled } from "getclean";

const answer = await client.uploadContents({
  document: { path: "records.pdf" },
  max_cost: { amount: "1.0000", currency: "USD" },
  wait: true,
});

const record = answer.contents; // the record, whether the parse finished at once or ran as a job
const job = answer.job;         // the final job, when there was one
```

When the parse finishes within `wait_seconds`, the API answers `201` and `answer.contents` is the record straight away. When it runs on as a job, the API answers `202`, and with `wait: true` the SDK reads the job with `getJob`, which waits on the server for up to a minute per request, until the job is final, then reads the record under the upload's own `max_characters`, `formats` and `block_kinds`. A job that fails before any record exists throws the error class of its problem's status, the same class the API would have thrown had it refused the upload directly. A job canceled before any page was done throws `JobCanceled`, which carries the job. A job still running after the API's own limit of 30 minutes comes back as it stands, so you're never stuck.

Without `wait`, you get the `202` as it is, with `answer.job` set, and you follow it yourself. The call's raw response says which status you got:

```typescript theme={"theme":"css-variables"}
const { data: answer, rawResponse } = await client
  .uploadContents({ document: { path: "records.pdf" }, max_cost: { amount: "1.0000", currency: "USD" } })
  .withRawResponse();

if (rawResponse.status === 202) {
  let job = answer.job!;
  while (!job.finished) {
    job = await client.getJob({ job_id: job.id, wait_seconds: 60 });
  }
}
```

Set `max_cost` on every upload: a long scan is the most expensive request there is. An upload requires an idempotency key, and the SDK generates one when you give none. The file is read into memory before it's sent, so that a retry can send the same bytes. [Turn PDFs, Office files, and scans into evidence you can cite by page](https://docs.getclean.ai/read/pdfs-scans-and-documents.md) covers what a document gives you.

## Errors

A problem, the API's own refusal, makes the call throw. Each HTTP status has its own error class under the `GetClean` namespace, and the error carries the problem as `body`:

```typescript theme={"theme":"css-variables"}
import { GetClean, GetCleanError } from "getclean";

try {
  await client.deleteContents({ contents_id: "cnt_3Fk9abaUhNX7t2eKkgfd3e" });
} catch (error) {
  if (error instanceof GetClean.NotFoundError) {
    console.log(error.body.type);         // "https://api.getclean.ai/problems/not-found"
    console.log(error.body.who_must_act); // "caller"
  } else if (error instanceof GetCleanError) {
    console.log(error.statusCode, error.message);
  } else {
    throw error;
  }
}
```

Several problem types share one status, so compare on `body.type` and not on the class alone: the eleven `422` types all throw `GetClean.UnprocessableEntityError`. The error's message starts with the problem's title and detail, so a log line says what happened without unpacking anything. `body.retryable` says whether asking again can help, and `body.change` carries the fix when it's data. A status the contract doesn't declare throws the plain `GetCleanError`. `JobCanceled` is exported from the package and under the namespace as `GetClean.JobCanceled`. [Errors](https://docs.getclean.ai/understand/errors.md) lists every type.

## Retries and the idempotency key

The SDK retries on its own when the API answers `429`, `502`, `503` or `504`: up to five attempts in all, with a backoff that starts at one second and doubles to a ceiling of 30 seconds, plus jitter. When the response has `Retry-After` within that ceiling, the SDK waits exactly that long. A `Retry-After` beyond it ends the retries, and the error reaches your code as it arrived, with `retry_after_seconds` in its body.

On the eight operations that take an idempotency key, the SDK generates one per request when you give none and sends the same key on every attempt, so a retry is never charged twice. That covers one more case: `409 idempotency-key-in-flight`, which means the first attempt with this key is still running on the server. The SDK waits the `retry_after_seconds` the API asks for and sends the same request with the same key again, up to five attempts under the same ceiling, and once the first attempt has answered, the same key returns its response. Any other `409` is thrown at once.

Give your own key when your program may repeat a request after a crash or a restart, so the second run finds the first response. It's a member of the request, named like the header:

```typescript theme={"theme":"css-variables"}
const record = await client.fetchContents({
  url: "https://example.com/q3",
  "Idempotency-Key": "fetch-q3-2026-11-04",
});
record.cost?.replayed; // true when this is the original response again
```

[Errors](https://docs.getclean.ai/understand/errors.md) has every rule of the key.

## Budgets and time

Two members keep a research agent inside its budget. `max_cost` is the most one request may cost, and the API drops optional work from the end of a published order rather than refuse the request; `cost.ceiling` on the response shows the limit that applied. `wait_seconds` is how long one request may work on the server. [Set a spending limit that no call can pass](https://docs.getclean.ai/understand/costs-and-budgets.md) explains how the money is reserved and cut.

The client's own timeout is a separate thing: it bounds one attempt on your side. It starts at 120 seconds. Before the first request that can be charged, the client reads your limits once and sets the timeout for each family to the API's own `call_seconds` bound plus ten seconds, so a request gets the time the API itself allows and no more. A `timeoutInSeconds` you pass for one request in its options stands.

## Per-request options

Every operation accepts a W3C `traceparent` header, which getclean logs with the request and never forwards to a site or a source. It goes in the options after the request, together with a per-request timeout when one request needs more than the client's default:

```typescript theme={"theme":"css-variables"}
const record = await client.fetchContents(
  { url: "https://example.com/q3" },
  { headers: { traceparent }, timeoutInSeconds: 200 },
);
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.