Node SDK and CLI
Three calls from a file on disk to a passage with its page number.
Upload documents from Node.js or a terminal, wait for them to index, then search them and get each passage with the document and page it came from. Pass those passages to your app, your search UI or the model you already call.
FY2027 Growth Plangrowth-plan-2027.pdf
4.3 FY2027 projection
Net revenue retention held at 128% through Q3.
Revenue reaches $48.2M, 12% ahead of plan, up 31% year over year.
Margin lands at 24%.
12
quickstart.mjsNode.js
await client.upload(file) await client.waitForRun(run.id) client.search({ q: 'FY2027 revenue forecast' })
Run completed12 of 12 pages indexed
hit 10.87
Revenue reaches $48.2M, 12% ahead of plan, up 31% year over year.
growth-plan-2027.pdfp. 12On this page
Quickstart
You need Node.js 20+, a document, and a server API key with ingest, search:deep and chat scopes. Use ESM: save JavaScript as .mjs, or set "type": "module". The SDK includes TypeScript declarations and has no runtime npm dependencies.
npm install @docslurp/sdk@^0.4.0
export DOCSLURP_API_KEY='your-server-api-key'
# Save the example below as quickstart.mjs, then:
node quickstart.mjs ./growth-plan-2027.pdf "Are we on track to beat our FY2027 earnings?"import { createReadStream } from "node:fs";
import { createDocSlurpClient } from "@docslurp/sdk";
// Usage: node quickstart.mjs ./growth-plan-2027.pdf "Are we on track to beat our FY2027 earnings?"
const [filename, q = "What are the key points in this document?"] = process.argv.slice(2);
if (!filename) throw new Error("Pass a document path: node quickstart.mjs ./growth-plan-2027.pdf");
if (!process.env.DOCSLURP_API_KEY) throw new Error("Set DOCSLURP_API_KEY first.");
// Without DOCSLURP_PROJECT, upload and search use your organization's default project.
const client = createDocSlurpClient();
const { project, run, warnings } = await client.upload(createReadStream(filename));
// Save these IDs before waiting: processing can outlive this process.
console.error(JSON.stringify({ projectId: project.id, projectSlug: project.slug, runId: run.id }));
for (const warning of warnings ?? []) console.error(warning);
await client.waitForRun(run.id, { timeoutMs: 600_000 });
const evidence = await client.search({ q, limit: 5 });
if (evidence.availability?.status !== "complete") {
console.error("Check corpus availability:", evidence.availability);
}
// Keep the complete response: citations, availability, and search session ID.
console.log(JSON.stringify(evidence, null, 2));- Line 10: Reads
DOCSLURP_API_KEY, andDOCSLURP_URLorDOCSLURP_PROJECTif set, from the environment. - Line 11: Accepted is not indexed. Upload returns IDs before processing finishes. Save them, then wait.
- Line 15: Parsing, OCR, chunking and embedding run on DocSlurp’s workers. If this wait times out, the run keeps going; wait again with the saved run ID.
- Line 17: Ranked passages with a citation each. No answer is generated here.
Outputnode quickstart.mjs ./growth-plan-2027.pdf "Are we on track to beat our FY2027 earnings?"
FY2027 Growth PlanSection 4
4.3 FY2027 projection
Net revenue retention is 128%. Revenue reaches $48.2M, 12% ahead of plan.
12
growth-plan-2027.pdfp. 12 the cited page
With no project configured, uploads, search and chat use your organization's default project. To keep documents in a separate project, pass project: 'legal-contracts' or set DOCSLURP_PROJECT. project takes an ID, slug or name (names match by slug, so 'Legal Contracts' is the same project), and an upload into a name that matches nothing creates that project. Without project, newProject: true uploads into a fresh self-titled project and templateKey creates a templated one. Former slugs are also accepted. How projects are addressed
When an upload is complete
upload() sends files directly to storage and waits for an accepted ingestion run. Small files use one PUT; large files use multipart. The server verifies the stored bytes and starts ingestion automatically. For streams without a known size, the SDK sends the final byte count and part list after EOF and successful part uploads.
You do not call a completion method after upload(). Its returned run.id means ingestion was accepted; use waitForRun() or streamProgress() to follow processing. A timeout does not prove that no run exists. Direct sessions ignore idempotencyKey; use the low-level session methods when you need to save a session ID and control retries.
Completion states, HTTP endpoints and recovery · SDK session example
Upload and search from a terminal
npm install --global @docslurp/cli
export DOCSLURP_API_KEY='your-server-api-key'
docslurp upload ./growth-plan-2027.pdf --watch
# No project setup: upload and search use your organization's default project.
docslurp search 'Are we on track to beat our FY2027 earnings?'
docslurp search 'Are we on track to beat our FY2027 earnings?' --context > evidence.txt
docslurp search 'Are we on track to beat our FY2027 earnings?' --json > evidence.jsonIn an interactive terminal, --watch updates document and page progress in place. Redirected output gets a new snapshot for each update. The wait stops after five minutes, but the run keeps processing: resume with docslurp status RUN_ID --watch --timeout 600.
| Output | Use it for |
|---|---|
| Default search | Readable results with 200-character previews and page citations. |
search --context | Full numbered source passages to pass into an LLM. |
search --json | Structured results, availability, usage, and the search session ID. |
chat --json | Answer, citations, session ID, usage, and runtime. |
Upload and status print readable output; search, chat and the read commands such as whoami and jobs get accept --json. Full command reference and shell recipes
Send passages to your own model
Search returns ranked passages with citations and doesn't generate an answer. Format the passages as context for the model you already call, or use the citations to build a source viewer. Retrieval can still incur embedding costs.
Iterate hits with for await (const hit of client.search(input)), or await the whole response to read availability and session metadata. Both forms share one request when you reuse the returned search. Hits are read from the finished JSON response; the server doesn't stream them.
import { createDocSlurpClient, formatSearchContext } from '@docslurp/sdk';
// Set DOCSLURP_API_KEY first. Searches the default project unless DOCSLURP_PROJECT is set.
const client = createDocSlurpClient();
const evidence = await client.search({ q: 'What is our FY2027 revenue forecast?', limit: 5 });
if (evidence.availability?.status !== 'complete') {
throw new Error('Wait for the project to finish indexing.');
}
if (!evidence.results.length) throw new Error('No supporting evidence.');
const context = formatSearchContext(evidence);
console.log(context);
console.log(evidence.usage); // Tokens + recorded AI cost.
// Pass context to your LLM as untrusted source evidence.
// Keep evidence.results to map citations back to their documents.- Line 6: Indexing can still be running. Don’t present partial evidence as complete.
- Line 11: Numbered passages with file and pages, ready for your model’s prompt.
console.log(context)
Ask your model to cite numbered passages and acknowledge missing evidence. Treat document text as untrusted source data. Keep evidence.sessionId for diagnostics and evidence.results to resolve the citations.
evidence.usage includes inputTokens, outputTokens, totalTokens, and costCents in USD. costSource distinguishes provider-reported, estimated, mixed, unknown, or no recorded AI usage. This covers retrieval only, not ingestion, storage, your own model, or an invoice. Fractional cents are preserved. Native chat returns its answer-generation usage in usage.
These examples require SDK 0.4.0 or newer, including batch search, URL uploads, project discovery and the single project option.
For independent questions, search({ queries }) accepts 1–20 queries with up to four concurrent searches. Ordered outcomes retain per-query errors. Batch retrieval example
Ask questions with cited answers
Using the client from above, ask a question and get an answer with citations. Pass the returned session ID to ask a follow-up in the same chat, and check availability before you present an answer as complete.
const first = await client.chat({ q: 'Summarize the FY2027 earnings outlook with sources.' });
console.log(first.answer, first.citations, first.availability);
console.log(first.usage, first.runtime);
const next = await client.chat({
q: 'How far above our margin target are we?',
sessionId: first.sessionId,
});
console.log(next.answer);Wait for each answer before you send the next follow-up in the same chat. SDK chat returns a promise. chatStream() yields a retrieval status and then the whole answer. To stream the answer as it's written, use the OpenAI-compatible chat API.
Run it in production
| Behavior | Contract |
|---|---|
| Deadlines | SDK requests default to 30 seconds. Run waits and streams default to five minutes. Override with timeoutMs (plus idleTimeoutMs on streamProgress); CLI uses seconds. |
| Cancellation | Pass an AbortSignal to stop the local request. This does not cancel server processing. |
| Live updates | streamProgress yields typed counts, usage, and runtime snapshots; automatic transport falls back to polling within the same deadline, every pollIntervalMs; heartbeatMs re-yields the latest snapshot when nothing has changed. Runnable fallback. |
| Retries | SDK run, document, project-state, and organization reads retry selected transient HTTP errors, as do replayable uploads with an idempotency key. Other writes and raw streams are not retried. |
| Project state | getProjectState returns indexed/remaining pages, source MB, recent search latency and throughput. Response and metric definitions. |
| Ingest report | getIngestReport explains how files processed and why a page cannot be found: text and images per page, pages read with vision, searchable pages with a reason, the settings behind them and recommendations with estimated cost. No AI call. |
| Organizations | Read details and access, update metadata, manage members, and revoke keys with explicit organization scopes. Inputs, outputs, and permissions. |
| Project readiness | availability distinguishes empty, pending, partial, and complete. A completed run can coexist with other pending uploads. |
| Keys | Keep server keys on your backend. Allowed websites restrict browser keys only; nothing makes a server key safe to publish. |
Configure another deployment with DOCSLURP_URL (the service origin, without /v1). Explicit options override environment values. Per-call projects override the client's (DOCSLURP_PROJECT, else default).
Reference
- SDK method reference, errors, retries, and upload recipes
- CLI commands, JSON output, CI, and migration tools
- The complete HTTP upload, poll and search script
- Search inputs, response contracts, and retrieval controls
- Connect agent tools with MCP
Pre-release: pin the package version you validate. SDKs are MIT licensed. The CLI is under the Business Source License 1.1 and becomes Apache-2.0 three years after each release. License details