Skip to content

feat(docs): add elastic docs api commands - #825

Open
akira28 wants to merge 17 commits into
elastic:mainfrom
akira28:feature/text-inside-external-tags
Open

akira28 wants to merge 17 commits into
elastic:mainfrom
akira28:feature/text-inside-external-tags

Conversation

@akira28

@akira28 akira28 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Adds elastic docs api search, elastic docs api get and elastic docs api list. They let agents and users look up operations in the Elastic REST API reference by route, operation id or field, without going through general docs search.

Closes elastic/docs-eng-team#1204.

The docs API endpoints are live on www.elastic.co: elastic/docs-builder#4887, #4896, #4942 and #4943 are deployed to production.

Commands

The commands sit under elastic docs, as the issue preferred. A bare elastic api would read as calling the Elastic APIs.

Command Docs API request MCP tool equivalent
elastic docs api search <query> --api <api> [--api-version] [--include-deprecated] [--page] [--size] GET /docs/_api/v1/apis/{api}/operations?q= search_api_operations with an API
elastic docs api get <operation-id> --api <api> [--api-version] [--include-body] GET /docs/_api/v1/apis/{api}/operations/{operationId} get_api_operation by id
elastic docs api get <endpoint> --api <api> [--api-version] [--include-body] GET /docs/_api/v1/apis/{api}/operations?endpoint=&view=full get_api_operation by endpoint
elastic docs api list GET /docs/_api/v1/apis list_api_operations
elastic docs api list <api> [--api-version] GET /docs/_api/v1/apis/{api}/groups list_api_operations with an API (group counts)
elastic docs api list <api> --group <group> [--page] [--size] GET /docs/_api/v1/apis/{api}/operations?group= list_api_operations with a group
  • Every command makes one request.
  • search and get require --api. Most operation ids and many routes exist in several APIs, for example elasticsearch and elasticsearch-serverless, so a lookup across APIs could only guess. The docs API has none, and neither does the CLI. The MCP tools still search across APIs.
  • get treats an argument containing / as an endpoint, such as GET /_cluster/health, and anything else as an operation id. --endpoint and --operation-id are also available.
  • For an endpoint, get asks the API's operations for the full view: a route made only of parameters, such as /{index}, can serve several operations. The best route becomes the result, and the rest go to otherMatches. --json output has the same shape as a lookup by id.
  • The API key and operation id are URL-encoded into one path segment with the shared encodePathParam.
  • --json passes the server reply through unchanged, except for get by endpoint, which reshapes the results as described above. Text output lists method, path, operation id, URL and fields.
  • Input is checked against a JSON Schema before any request, and under --dry-run too. The schema keys are the query parameter names, so flags map straight onto the request. The schema rejects:
    • unknown keys and out-of-range --size or --page values
    • a missing or blank query for search, and a missing or blank --api for search and get
    • anything but exactly one non-blank --endpoint or --operation-id for get (oneOf)
    • for list, --api-version or --group without an API, and --page or --size without --group (dependencies)
    • a blank API key, --group or --api-version, for every command that takes one
    • . or .. as an API key or operation id: URL parsing would resolve them out of the path and reach another route. The paths are also built with encodePathParam, which refuses them under --no-validate with input_error
  • The API version flag is --api-version, not --version, because elastic --version prints the CLI's own version. It is sent as the docs API's version query parameter.
  • Errors use the existing docs_error code, like the other docs commands. The docs API answers errors as RFC 9457 problems (Publish an OpenAPI document for the docs API and answer errors as RFC 9457 problems docs-builder#4896). The message is the problem's detail, such as "No API operation matches nope in elasticsearch.", or its title when there is no detail. An HTML error page from the CDN is reduced to its status name, such as Not Found: www.elastic.co's CDN answers an API 404 with the site's HTML page, so a missing API or operation reads docs api error (404): Not Found. elastic/docs-eng-team#1231 tracks letting the API's 404 problems through. A 2xx reply that isn't JSON, such as a maintenance page, fails with the reply is not JSON.
  • Requests accept application/json and application/problem+json, use redirect: 'error', and URL-encode parameters. They send no cookie: elastic/docs-infra#523 dropped the production gate, and fix(docs): stop sending the docs API cookie #829 removed the cookie from docs search and docs ask.

Shared factory changes

  • positionalArg in CommandConfig gains an optional toInput, which maps the positional value onto input fields before schema validation. Before, a positional value reached the handler only as parsed.arg, after validation, so a schema couldn't require it, and --dry-run reported success for invocations a real run would reject. Flags and JSON input win over the fields toInput sets. main's inputKey fills one fixed field and errors when its flag is also given; toInput is for get, whose positional fills endpoint or operation_id depending on its value. Both live on positionalArg.

  • toInput applies only when the JSON input is absent or an object. Any other root (42, [], a string) stays as given, so the schema rejects it instead of a request going out for input the user never wrote.

  • A JSON null root now fails command input validation with must be object. validateWithJsonSchema reads null as no input, so echo null | elastic docs api list elasticsearch passed (every list field is optional) and dropped the positional. This applies to every command that takes JSON input. Before, a piped null ran as empty input. The shared validator is unchanged, because the config loader relies on it for an empty YAML file.

  • Flags merge into an absent or object JSON root only. Before, any root was spread into a new object when a flag was given, so echo 42 | elastic docs api get cluster-health --api elasticsearch passed and sent a request. This applies to every command with JSON input. ES body-root commands already rejected an array root with flags; only their message changes, to must be object.

Commands that set neither toInput nor inputKey behave as before, apart from the null and flag-merge changes. test/factory.test.ts covers all of this.

Verify

npm run test:unit -- test/docs/api.test.ts
elastic docs api list
elastic docs api list --api elasticsearch --group "Cluster - Health"
elastic docs api search "retriever." --api elasticsearch --size 3
elastic docs api get --api elasticsearch --operation-id cluster-health
elastic docs api get --api elasticsearch --endpoint "GET /my-index/_search"
elastic docs api get --api elasticsearch --operation-id nope --json   # {"error":{"code":"docs_error",...}}, exit 1

The full unit suite, tsc --noEmit and eslint pass. docs/cli/schema.json is up to date.

All of the above ran against production with the built CLI and returned the expected results. That run found two bugs, fixed in this PR:

  • docs api list padded keys to 24 columns, so elasticsearch-serverless ran into its title. The column now fits the longest key.
  • A 404 read request failed. HTTP/2 has no status text, and the CDN replaces the API's 404 problem with an HTML page. It now reads Not Found.

🤖 Generated with Claude Code

Add `elastic docs api search`, `get` and `list` to look up operations in
the Elastic REST API reference. They call the docs API's
/_api/v1/api-reference endpoints, which serve the same lookups as the
docs MCP server's API tools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 17, 2026 11:30
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🔍 Preview links for changed docs

No direct page links are available.
Browse the full preview

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Command validation allows missing search queries and missing or conflicting operation selectors, causing backend rejections in normal runs and false success with --dry-run.

1 open issue
What changed in this PR

Adds elastic docs api commands for looking up Elastic REST API reference material directly, complementing the existing general documentation commands. Live use remains dependent on deployment of the linked docs-builder backend changes.

Changes:

  • Adds search, get, and list commands with schema-based inputs and text or JSON output.
  • Adds an API-reference client with encoded query parameters, redirect protection, and server error handling.
  • Adds unit tests and updates the generated CLI schema.
File Description
test/​docs/​api.test.ts Tests requests, validation, formatting, and error handling.
src/​docs/​register.ts Registers the new docs api command group.
src/​docs/​client.ts Adds API-reference HTTP requests and error parsing.
src/​docs/​api.ts Defines the commands, input schemas, and text formatters.
docs/​cli/​schema.json Documents the new commands and parameters in the generated schema.

Review effort: Balanced

Comment thread src/docs/api.ts Resolved
akira28 and others added 2 commits November 17, 2026 12:58
Patching process.stdout.write directly also swallowed the Node 22 test
runner's serialized events, so the --json test parsed binary data.
captureDuring forwards non-string chunks to the real stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The command reference turns 'Default:' in a description into a default value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The docs API now serves the lookups as one resource: the collection
filters by q or endpoint, one operation reads by id, and groups and apis
are their own routes. `get` with an endpoint lists the matching
operations, then reads the best one by id in its own API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each command is now one request. `get` reads /api-operations/{api}:{id}
with --api, and otherwise asks the collection for the full view of every
match. `list <api>` counts its groups, and `list <api> --group` pages
through the group's operations with --page and --size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The docs API answers every error as application/problem+json. The error
message is now the problem's detail, or its title when there is none, and
requests accept application/problem+json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A positional argument reached the handler only after schema validation, so
the schema could not require it: `search` without a query and `get` with
neither or both selectors passed validation, failed on the server, and
reported success under --dry-run. positionalArg.toInput now maps the value
into the input before validation, and the docs api schemas require a
non-blank query, exactly one of endpoint or operation_id, and api for
version, group, page and size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The docs API dropped lookups across APIs: most operation ids and many routes
exist in several APIs, so such a lookup could only guess. `search` and `get`
now require --api and call /apis/{api}/operations, and `get <id>` reads
/apis/{api}/operations/{operationId}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@akira28
akira28 marked this pull request as ready for review November 18, 2026 10:21
@akira28 akira28 changed the title feat(docs): add elastic docs api commands [WAIT-FOR-API-IN-PROD] feat(docs): add elastic docs api commands Nov 18, 2026
elastic/docs-infra#523 removed the CDN's cookie gate. elastic#829 drops it from search and ask on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@akira28 akira28 changed the title [WAIT-FOR-API-IN-PROD] feat(docs): add elastic docs api commands feat(docs): add elastic docs api commands Nov 20, 2026
akira28 and others added 2 commits November 20, 2026 16:18
…rror

elastic docs api list padded keys to 24 columns, so elasticsearch-serverless ran into its title. Over HTTP/2 a reply has no status text, and www.elastic.co's CDN answers an API 404 with its HTML page, so the error read "request failed"; it now names the status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread src/docs/api.ts Resolved
Comment thread src/docs/api.ts Resolved
Comment thread src/docs/client.ts Resolved
Comment thread src/docs/client.ts Resolved
- `elastic --version` prints the CLI version, so `docs api` names the API version `--api-version` and still sends it as the `version` query parameter.
- `docs api list` rejects a blank API key instead of requesting `/apis//groups`.
- A 2xx reply that is not JSON, such as a CDN maintenance page, reports `the reply is not JSON` instead of a SyntaxError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Positional-field merging converts invalid JSON root values into valid object inputs, bypassing schema rejection and allowing requests or successful dry runs.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread src/factory.ts Resolved
Comment thread src/docs/api.ts Resolved
Comment thread src/factory.ts Resolved
akira28 and others added 2 commits December 1, 2026 10:53
Conflicts in src/factory-core.ts and test/factory.test.ts: main added
positionalArg.inputKey, which fills one fixed input field. toInput stays
for elastic docs api get, whose positional fills endpoint or operation_id
depending on its value, so positionalArg now has both and the tests for
both are kept.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
- A positional is merged into the JSON input only when that input is
  absent or an object. Any other root (null, 42, [], a string) stays as
  given so the schema rejects it, instead of becoming valid input that
  sends a request and passes --dry-run.
- A JSON null root now fails command input validation. The validator
  reads null as no input, which passed schemas whose fields are all
  optional, such as elastic docs api list, and dropped the positional.
- group and api_version reject a blank value like the other string
  parameters, so --group '' no longer sends group=.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Flag merging converts non-object JSON roots into objects before validation, allowing invalid inputs combined with --api to pass the guard and send requests.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread src/factory.ts Resolved
mergeFlagsIntoInput spread any root into a new object when a schema flag
was given, so echo 42 | elastic docs api get cluster-health --api
elasticsearch passed validation and sent a request. null, true and []
did the same, also under --dry-run. Flags now merge into an absent or
object root only; any other root stays as given and validation rejects
it. This applies to every command with JSON input. ES body-root commands
already rejected an array root with flags; only their message changes,
to must be object.

The toInput guard now checks isPlainObject alone, since
mergeFlagsIntoInput already turns no input into {}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because dot-only API keys or operation IDs can be normalized into unintended request routes.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

encodeURIComponent keeps . and .., and URL parsing resolves them out of
the path, so elastic docs api list .. requested /docs/_api/v1/groups and
get .. --api elasticsearch requested the API itself. api and
operation_id, the values sent as path segments, now use one pattern
that is non-blank and not . or .., so --dry-run fails as a real run
would and the rule shows in the CLI schema. The paths are built with
the existing encodePathParam, which covers --no-validate; its
input_error code is kept instead of becoming docs_error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@akira28

akira28 commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Re the Copilot review summary, "dot-only API keys or operation IDs can be normalized into unintended request routes": confirmed and fixed in b178091.

encodeURIComponent keeps . and .., and URL parsing resolves them out of the path (encoding them as %2e doesn't help, the parser treats that as a dot too):

Input Path requested before
elastic docs api list .. /docs/_api/v1/groups
elastic docs api list . /docs/_api/v1/apis/groups
elastic docs api get .. --api elasticsearch /docs/_api/v1/apis/elasticsearch/

What changed:

  • api and operation_id, the two values sent as path segments, use one pattern that is non-blank and not . or .., so --dry-run fails as a real run would. It is a single regex rather than a not keyword because the CLI schema generator only carries regex and range validations, and this way the rule shows in docs/cli/schema.json.
  • The paths are built with the existing encodePathParam from src/lib/path-encoding.ts, which the kb, cloud and es request builders already use. It refuses empty, . and .., which covers --no-validate, where the schema is skipped. Its input_error code is kept instead of becoming docs_error.
  • Tests: . and .. as a positional or flag for each command, normal and --dry-run, and --no-validate failing with input_error and no request.

Comment thread src/factory.ts
Comment on lines +556 to +559
// Flags merge into an absent or object root only. Any other root (null, 42, [], ...) stays as given so
// validation rejects it; merging would turn it into an object that passes and sends a request.
if (Object.keys(cliInput).length > 0 && (inputValue === undefined || isPlainObject(inputValue))) {
inputValue = { ...inputValue, ...cliInput }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This flag-merge change and the null rejection in validateAgainstSchema (below, line 616) apply to every command with JSON input, not only docs api. A piped null used to run as empty input and now exits 1. With a non-object root, flags are now dropped and left to the schema to reject. Not sure if it's an issue for any real commands now, but probably best to maintain consistency just in case.

Comment thread src/factory.ts
Comment on lines +893 to +899
const toInput = config.positionalArg?.toInput
// Only an object input takes the positional's fields (mergeFlagsIntoInput turns no input into {}); any other
// root (null, 42, [], ...) stays as given so the schema rejects it rather than a request going out for
// something the user never wrote.
if (merged !== undefined && positionalValue !== undefined && toInput != null && isPlainObject(merged.input)) {
merged.input = { ...toInput(positionalValue), ...merged.input }
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With toInput, a flag or JSON value silently overrides the positional (docs api search foo --query bar searches bar).

The pattern used by inputKey might be better: error with pass X either as an argument or as --flag, not both. That would avoid silent precedence, which is easy to miss.

Comment thread src/docs/api.ts
Comment on lines +135 to +136
// Operation ids never contain '/', endpoints always do.
fromArg: (arg) => (arg.includes('/') ? { endpoint: arg } : { operation_id: arg }),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This arg.includes logic means an operation ID should never contains a / character, which I assume is fine. Just wanted to call it out in case it's a potential concern.

Comment thread src/docs/client.ts
for (const [key, value] of Object.entries(params)) {
if (value != null) qs.set(key, String(value))
}
const resp = await fetch(`${DOCS_BASE_URL}/_api/v1${path}?${qs.toString()}`, {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const resp = await fetch(`${DOCS_BASE_URL}/_api/v1${path}?${qs.toString()}`, {
const apiURL = new URL(`${DOCS_BASE_URL}/_api/v1${path}`)
apiURL.search = qs
const resp = await fetch(apiURL.href, {

nit: using new URL ensures proper construction and doesn't append an unnecessary ? when qs is empty.

This branch was successfully deployed

1 active deployment
docs-preview — b1780918 Deployed Dec 1, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants