Programmatic API
AFDocs exports its check runner and utilities as a TypeScript API, so you can integrate agent-friendliness checks into your own tools and workflows.
Run all checks
import { runChecks } from 'afdocs';
const report = await runChecks('https://docs.example.com');
console.log(report.summary);
// { total: 28, pass: 19, warn: 4, fail: 3, skip: 2, error: 0 }
for (const result of report.results) {
console.log(`${result.id}: ${result.status} — ${result.message}`);
}runChecks throws an Error if the options are invalid (see Validate options below). On success, it returns a ReportResult containing:
url— the URL that was checkedtimestamp— when the check ranafdocsVersion— the version of AFDocs that produced the report (e.g.0.23.0)specVersion— the version of the Agent-Friendly Documentation Spec the checks implement (e.g.v0.6.0)results— array ofCheckResultobjects (one per check)summary— counts by status (pass, warn, fail, skip, error)checkDefinitions— what each check inresultslooks for, keyed by check ID: a one-sentencedescriptionand thespecUrlof the check's section in the spec. See Label checks and categoriescategories— the displaynameand sortorderof each category that appears inresults, keyed by category IDtestedPages— number of pages tested by page-level checks (present when page discovery ran)samplingStrategy— the sampling strategy used (random,deterministic,curated, ornone)requestSummary— aggregate of every HTTP request the run made:requests,stalledBodies,challengePages,fetchErrors,failed, andfailureRate(0–100). Feeds the bot protection scan-reliability diagnosticnetworkContext— where the scan ran from:developer-machine,ci, orcloud, withsourceset toenvironment(classified from environment variables, with theindicatorvariable that matched) oroption(thenetworkContextrunner option). Never includes an IP address
Label checks and categories
Each entry in results identifies its check and category by ID (markdown-url-support, markdown-availability). The report carries the human-readable text for those IDs in two maps, so a dashboard or custom report doesn't need its own hardcoded list:
{
"results": [
{
"id": "markdown-url-support",
"category": "markdown-availability",
"status": "pass",
"message": "..."
}
],
"checkDefinitions": {
"markdown-url-support": {
"description": "Whether appending .md to page URLs returns valid markdown",
"specUrl": "https://agentdocsspec.com/spec/web/markdown-availability/#markdown-url-support"
}
},
"categories": {
"markdown-availability": { "name": "Markdown Availability", "order": 2 }
}
}Look up each result's id in checkDefinitions and its category in categories:
const rows = report.results.map((result) => ({
...result,
description: report.checkDefinitions?.[result.id]?.description,
specUrl: report.checkDefinitions?.[result.id]?.specUrl,
categoryName: report.categories?.[result.category]?.name,
}));Both maps describe exactly the checks and categories in results. A run limited with checkIds gets a correspondingly smaller map, and checks that were skipped are included because they still appear in results. The same maps appear in the CLI's --format json output.
These fields, along with afdocsVersion and specVersion, are optional in the ReportResult type. Reports saved by AFDocs versions before these fields were added don't have them, so code that reads stored reports should handle their absence.
Run with options
Pass a second argument to configure sampling, concurrency, and thresholds:
import { runChecks } from 'afdocs';
// Run specific checks (include-list)
const report = await runChecks('https://docs.example.com', {
checkIds: ['llms-txt-exists', 'llms-txt-valid', 'llms-txt-size'],
samplingStrategy: 'deterministic',
maxLinksToTest: 20,
maxConcurrency: 5,
requestDelay: 100,
// How long one request may go without a response or new data, in milliseconds
requestTimeout: 15000,
thresholds: {
pass: 50000,
fail: 100000,
},
// page-size-transfer: served (decoded) HTML bytes
transferThresholds: {
pass: 1_000_000,
fail: 10_000_000,
},
// embedded-data-serialization: what counts as bulk, and when it is blamed
bulkTableRows: 20,
bulkBlobChars: 2000,
bulkDominantShare: 50,
// bot-protection-interference: where the scan runs from, if detection is wrong
networkContext: 'ci',
});
// Or run all checks except a few (exclude-list)
const skipReport = await runChecks('https://docs.example.com', {
skipCheckIds: ['markdown-content-parity'],
});
// Or test specific pages with curated sampling
const curatedReport = await runChecks('https://docs.example.com', {
samplingStrategy: 'curated',
curatedPages: [
'https://docs.example.com/quickstart',
{ url: 'https://docs.example.com/api/auth', tag: 'api-reference' },
],
});All options are optional. The defaults match the CLI defaults.
Progress events
Pass an onProgress callback to observe each check as it starts and completes. The runner calls it with a start event before a check runs and a complete event after, carrying the check's 1-based position and the total number of selected checks. The complete event also includes the CheckResult and the wall-clock duration in milliseconds. The CLI's stderr progress output is built on this callback.
import { runChecks } from 'afdocs';
import type { CheckProgressEvent } from 'afdocs';
const report = await runChecks('https://docs.example.com', {
onProgress: (event: CheckProgressEvent) => {
if (event.phase === 'start') {
console.error(`[${event.index}/${event.total}] ${event.checkId}...`);
} else {
console.error(` ${event.result.status} in ${event.durationMs}ms`);
}
},
});Skipped checks (excluded via skipCheckIds or gated by an unmet dependency) still emit both events, with a skip result on completion.
Run a single check
For more control, create a context and run individual checks:
import { createContext, getCheck } from 'afdocs';
const ctx = createContext('https://docs.example.com');
const check = getCheck('llms-txt-exists')!;
const result = await check.run(ctx);
console.log(result.status); // 'pass', 'warn', 'fail', or 'skip'
console.log(result.message);createContext validates the options and throws an Error if any are invalid, then sets up the shared state (HTTP client, page cache, previous results) that checks use. If you run multiple checks against the same context, later checks can access the results of earlier ones through ctx.previousResults, which is how check dependencies work.
List available checks
import { getAllChecks, getChecksSorted } from 'afdocs';
// All checks as a Map<string, CheckDefinition>
const all = getAllChecks();
// Checks in dependency-safe execution order
const sorted = getChecksSorted();
for (const check of sorted) {
console.log(`${check.id} (${check.category}): ${check.description}`);
}List categories
CATEGORIES lists every check category in display order. Each entry has the category id that check results and definitions refer to, a human-readable name, and a 1-based order:
import { CATEGORIES } from 'afdocs';
for (const category of CATEGORIES) {
console.log(`${category.order}. ${category.name} (${category.id})`);
}
// 1. Content Discoverability (content-discoverability)
// 2. Markdown Availability (markdown-availability)
// 3. Page Size and Truncation Risk (page-size)
// 4. Content Structure (content-structure)
// 5. URL Stability and Redirects (url-stability)
// 6. Observability and Content Health (observability)
// 7. Authentication and Access (authentication)Use getAllChecks and CATEGORIES when you need the full catalog. To label the results of one run, the maps on the report are simpler.
Validate options
Both runChecks and createContext validate options and throw on invalid input. If you want to check options before calling either function (for example, to show validation errors in a UI or dry-run mode), use validateRunnerOptions:
import { validateRunnerOptions } from 'afdocs';
const validation = validateRunnerOptions({
maxConcurrency: -1,
samplingStrategy: 'curated',
});
if (!validation.valid) {
for (const error of validation.errors) {
console.error(`${error.field}: ${error.message}`);
// maxConcurrency: maxConcurrency must be between 1 and 100, got -1
// samplingStrategy: Curated sampling requires curatedPages to be non-empty
}
}validateRunnerOptions returns a ValidationResult with errors and warnings arrays. Each entry has a field (the option name) and a message (human-readable description). The valid boolean is true when there are no errors.
Validations performed include numeric range checking, threshold ordering (e.g. size pass threshold must be less than or equal to fail threshold), sampling strategy enum validation, and check ID existence.
Sampling strategies
The valid sampling strategies are available as a constant:
import { VALID_SAMPLING_STRATEGIES } from 'afdocs';
console.log(VALID_SAMPLING_STRATEGIES);
// ['random', 'deterministic', 'curated', 'none']Versions
Three constants identify what produced a result, for code that stores reports or compares them over time:
import { AFDOCS_VERSION, SPEC_VERSION, SCORING_VERSION } from 'afdocs';
console.log(AFDOCS_VERSION); // the installed AFDocs package version
console.log(SPEC_VERSION); // 'v0.6.0'
console.log(SCORING_VERSION); // '0.2.0'AFDOCS_VERSIONis the version of the AFDocs package. Every report records it asafdocsVersion.SPEC_VERSIONis the version of the Agent-Friendly Documentation Spec the checks implement. Every report records it asspecVersion.SCORING_VERSIONis the version of the scoring method. Every score records it asscoringVersion. Scores from different scoring versions are not comparable.
Types
The main types you'll work with:
import type {
CheckResult,
CheckStatus, // 'pass' | 'warn' | 'fail' | 'skip' | 'error'
ReportResult,
CheckDefinitionInfo, // entry in report.checkDefinitions
CategoryInfo, // entry in report.categories
RunnerOptions,
CheckOptions,
CheckProgressEvent, // CheckProgressStartEvent | CheckProgressCompleteEvent
CheckProgressStartEvent,
CheckProgressCompleteEvent,
SamplingStrategy, // 'random' | 'deterministic' | 'curated' | 'none'
AgentDocsConfig,
CuratedPageEntry,
PageConfigEntry,
ValidationResult,
ValidationIssue,
} from 'afdocs';See the Scoring API for scoring-related types.