Repository navigation
Conversation
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>
🔍 Preview links for changed docsNo direct page links are available. |
There was a problem hiding this comment.
🟡 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, andlistcommands 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
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>
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>
…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>
- `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>
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>
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>
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>
|
Re the Copilot review summary, "dot-only API keys or operation IDs can be normalized into unintended request routes": confirmed and fixed in b178091.
What changed:
|
| // 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 } |
There was a problem hiding this comment.
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.
| 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 } | ||
| } |
There was a problem hiding this comment.
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.
| // Operation ids never contain '/', endpoints always do. | ||
| fromArg: (arg) => (arg.includes('/') ? { endpoint: arg } : { operation_id: arg }), |
There was a problem hiding this comment.
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.
| 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()}`, { |
There was a problem hiding this comment.
| 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.


Adds
elastic docs api search,elastic docs api getandelastic 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 bareelastic apiwould read as calling the Elastic APIs.elastic docs api search <query> --api <api> [--api-version] [--include-deprecated] [--page] [--size]GET /docs/_api/v1/apis/{api}/operations?q=search_api_operationswith an APIelastic docs api get <operation-id> --api <api> [--api-version] [--include-body]GET /docs/_api/v1/apis/{api}/operations/{operationId}get_api_operationby idelastic docs api get <endpoint> --api <api> [--api-version] [--include-body]GET /docs/_api/v1/apis/{api}/operations?endpoint=&view=fullget_api_operationby endpointelastic docs api listGET /docs/_api/v1/apislist_api_operationselastic docs api list <api> [--api-version]GET /docs/_api/v1/apis/{api}/groupslist_api_operationswith an API (group counts)elastic docs api list <api> --group <group> [--page] [--size]GET /docs/_api/v1/apis/{api}/operations?group=list_api_operationswith a groupsearchandgetrequire--api. Most operation ids and many routes exist in several APIs, for exampleelasticsearchandelasticsearch-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.gettreats an argument containing/as an endpoint, such asGET /_cluster/health, and anything else as an operation id.--endpointand--operation-idare also available.getasks 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 tootherMatches.--jsonoutput has the same shape as a lookup by id.encodePathParam.--jsonpasses the server reply through unchanged, except forgetby endpoint, which reshapes the results as described above. Text output lists method, path, operation id, URL and fields.--dry-runtoo. The schema keys are the query parameter names, so flags map straight onto the request. The schema rejects:--sizeor--pagevaluessearch, and a missing or blank--apiforsearchandget--endpointor--operation-idforget(oneOf)list,--api-versionor--groupwithout an API, and--pageor--sizewithout--group(dependencies)--groupor--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 withencodePathParam, which refuses them under--no-validatewithinput_error--api-version, not--version, becauseelastic --versionprints the CLI's own version. It is sent as the docs API'sversionquery parameter.docs_errorcode, like the otherdocscommands. 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'sdetail, such as "No API operation matches nope in elasticsearch.", or itstitlewhen there is no detail. An HTML error page from the CDN is reduced to its status name, such asNot Found: www.elastic.co's CDN answers an API 404 with the site's HTML page, so a missing API or operation readsdocs 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 withthe reply is not JSON.application/jsonandapplication/problem+json, useredirect: '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 fromdocs searchanddocs ask.Shared factory changes
positionalArginCommandConfiggains an optionaltoInput, which maps the positional value onto input fields before schema validation. Before, a positional value reached the handler only asparsed.arg, after validation, so a schema couldn't require it, and--dry-runreported success for invocations a real run would reject. Flags and JSON input win over the fieldstoInputsets.main'sinputKeyfills one fixed field and errors when its flag is also given;toInputis forget, whose positional fillsendpointoroperation_iddepending on its value. Both live onpositionalArg.toInputapplies 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
nullroot now fails command input validation withmust be object.validateWithJsonSchemareadsnullas no input, soecho null | elastic docs api list elasticsearchpassed (everylistfield is optional) and dropped the positional. This applies to every command that takes JSON input. Before, a pipednullran 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 elasticsearchpassed 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, tomust be object.Commands that set neither
toInputnorinputKeybehave as before, apart from thenulland flag-merge changes.test/factory.test.tscovers all of this.Verify
The full unit suite,
tsc --noEmitand eslint pass.docs/cli/schema.jsonis 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 listpadded keys to 24 columns, soelasticsearch-serverlessran into its title. The column now fits the longest key.request failed. HTTP/2 has no status text, and the CDN replaces the API's 404 problem with an HTML page. It now readsNot Found.🤖 Generated with Claude Code