@cyanheads/openalex-mcp-server 0.7.14 → 0.7.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/AGENTS.md +8 -4
  2. package/CLAUDE.md +8 -4
  3. package/README.md +12 -9
  4. package/changelog/0.7.x/0.7.15.md +33 -0
  5. package/changelog/0.7.x/0.7.16.md +32 -0
  6. package/dist/mcp-server/prompts/definitions/literature-review.prompt.js +1 -1
  7. package/dist/mcp-server/prompts/definitions/literature-review.prompt.js.map +1 -1
  8. package/dist/mcp-server/tools/definitions/analyze-trends.tool.d.ts +22 -2
  9. package/dist/mcp-server/tools/definitions/analyze-trends.tool.d.ts.map +1 -1
  10. package/dist/mcp-server/tools/definitions/analyze-trends.tool.js +71 -17
  11. package/dist/mcp-server/tools/definitions/analyze-trends.tool.js.map +1 -1
  12. package/dist/mcp-server/tools/definitions/citation-graph.tool.d.ts +12 -1
  13. package/dist/mcp-server/tools/definitions/citation-graph.tool.d.ts.map +1 -1
  14. package/dist/mcp-server/tools/definitions/citation-graph.tool.js +56 -39
  15. package/dist/mcp-server/tools/definitions/citation-graph.tool.js.map +1 -1
  16. package/dist/mcp-server/tools/definitions/describe-fields.tool.d.ts.map +1 -1
  17. package/dist/mcp-server/tools/definitions/describe-fields.tool.js +82 -15
  18. package/dist/mcp-server/tools/definitions/describe-fields.tool.js.map +1 -1
  19. package/dist/mcp-server/tools/definitions/resolve-name.tool.d.ts +18 -0
  20. package/dist/mcp-server/tools/definitions/resolve-name.tool.d.ts.map +1 -1
  21. package/dist/mcp-server/tools/definitions/resolve-name.tool.js +29 -7
  22. package/dist/mcp-server/tools/definitions/resolve-name.tool.js.map +1 -1
  23. package/dist/mcp-server/tools/definitions/search-entities.tool.d.ts +50 -0
  24. package/dist/mcp-server/tools/definitions/search-entities.tool.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/search-entities.tool.js +176 -41
  26. package/dist/mcp-server/tools/definitions/search-entities.tool.js.map +1 -1
  27. package/dist/mcp-server/tools/escape-markdown.d.ts +32 -0
  28. package/dist/mcp-server/tools/escape-markdown.d.ts.map +1 -0
  29. package/dist/mcp-server/tools/escape-markdown.js +389 -0
  30. package/dist/mcp-server/tools/escape-markdown.js.map +1 -0
  31. package/dist/mcp-server/tools/render-entity-record.d.ts +2 -1
  32. package/dist/mcp-server/tools/render-entity-record.d.ts.map +1 -1
  33. package/dist/mcp-server/tools/render-entity-record.js +24 -8
  34. package/dist/mcp-server/tools/render-entity-record.js.map +1 -1
  35. package/dist/services/openalex/html-entities.json +2237 -0
  36. package/dist/services/openalex/openalex-service.d.ts +17 -1
  37. package/dist/services/openalex/openalex-service.d.ts.map +1 -1
  38. package/dist/services/openalex/openalex-service.js +211 -101
  39. package/dist/services/openalex/openalex-service.js.map +1 -1
  40. package/dist/services/openalex/provider-text.d.ts +20 -0
  41. package/dist/services/openalex/provider-text.d.ts.map +1 -0
  42. package/dist/services/openalex/provider-text.js +276 -0
  43. package/dist/services/openalex/provider-text.js.map +1 -0
  44. package/dist/services/openalex/types.d.ts +16 -0
  45. package/dist/services/openalex/types.d.ts.map +1 -1
  46. package/dist/services/openalex/types.js +7 -0
  47. package/dist/services/openalex/types.js.map +1 -1
  48. package/package.json +6 -3
  49. package/server.json +3 -3
package/AGENTS.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Developer Protocol
2
2
 
3
3
  **Server:** openalex-mcp-server
4
- **Version:** 0.7.14
5
- **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.5`
4
+ **Version:** 0.7.16
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.6`
6
6
  **Engines:** Bun ≥1.4.0, Node ≥24.0.0
7
7
  **MCP SDK:** `@modelcontextprotocol/server` ^2.0.0
8
8
  **Zod:** ^4.6.5
@@ -168,7 +168,7 @@ Handlers receive a unified `ctx` object. Key properties:
168
168
 
169
169
  Handlers throw — the framework catches, classifies, and formats.
170
170
 
171
- **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` to receive a typed `ctx.fail(reason, …)` keyed by the declared reason union — `ctx.fail('typo')` is a TS error, `data.reason` is auto-populated, and the linter enforces conformance against the handler. The `recovery` field is required (≥5 words). Spread `ctx.recoveryFor('reason')` into `data` to opt the contract recovery onto the wire.
171
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable?, thrownBy? }]` on `tool()` to receive a typed `ctx.fail(reason, …)` keyed by the declared reason union — `ctx.fail('typo')` is a TS error, `data.reason` is auto-populated, and the linter enforces conformance against the handler. The `recovery` field is required (≥5 words). Spread `ctx.recoveryFor('reason')` into `data` to opt the contract recovery onto the wire; `error-contract-recovery-unforwarded` warns per `ctx.fail` site that forwards neither the resolver nor its own `recovery` key.
172
172
 
173
173
  ```ts
174
174
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
@@ -177,6 +177,10 @@ errors: [
177
177
  { reason: 'semantic_per_page_cap', code: JsonRpcErrorCode.ValidationError,
178
178
  when: 'per_page exceeds the semantic-search cap',
179
179
  recovery: 'Reduce per_page to 50 or less, or switch search_mode to keyword.' },
180
+ { reason: 'upstream_timeout', code: JsonRpcErrorCode.Timeout,
181
+ when: 'OpenAlex did not respond within the request deadline',
182
+ recovery: 'Retry after a short delay, or narrow the request with tighter filters.',
183
+ thrownBy: 'service' },
180
184
  ],
181
185
  async handler(input, ctx) {
182
186
  if (overCap) throw ctx.fail('semantic_per_page_cap', message, { ...ctx.recoveryFor('semantic_per_page_cap') });
@@ -185,7 +189,7 @@ async handler(input, ctx) {
185
189
 
186
190
  **Declare contracts inline on each tool, even when similar across tools.** The contract is part of the tool's documented public surface — reading one tool definition file should give the full picture. Don't extract a shared `errors[]` constant; per-tool repetition is the intended cost of locality.
187
191
 
188
- The OpenAlex service throws factory errors (`notFound`, `rateLimited`, etc.) based on upstream status codes, carrying the contract `reason` on `data.reason` and the recovery via `ctx.recoveryFor(reason)`; those bubble through and are auto-classified. Because most declared reasons are produced in the service, handler-local precondition throws (`semantic_per_page_cap`, `reserved_filter_key`, …) live in module-level helpers (`assertListQueryConstraints`, `assertNoReservedFilterKey`, `resolveSeedToWorkId`) rather than inline: `error-contract-unthrown` only scans handlers holding a literal `ctx.fail(`, and an inline one would flag every service-produced reason as dead. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely without needing to be declared on a contract.
192
+ The OpenAlex service throws factory errors (`notFound`, `rateLimited`, etc.) based on upstream status codes, carrying the contract `reason` on `data.reason` and the recovery via `ctx.recoveryFor(reason)`; those bubble through and are auto-classified. Every such entry carries `thrownBy: 'service'` — lint-only metadata that tells `error-contract-unthrown`, whose scan reads the handler body alone, to skip a reason produced a layer below it. Handler-local precondition throws stay inline and unmarked so the rule keeps checking them: `semantic_without_query`, `semantic_per_page_cap`, `semantic_with_cursor`, `page_without_semantic`, `sample_with_cursor`, `sample_with_page`, `sample_with_semantic`, `sample_with_sort`, and `seed_without_sample` on `openalex_search_entities`; `reserved_filter_key` and the seed-lookup `entity_not_found` on `openalex_get_citation_graph`. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely without needing to be declared on a contract.
189
193
 
190
194
  **Fallback for ad-hoc throws:** error factories or plain `Error`.
191
195
 
package/CLAUDE.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Developer Protocol
2
2
 
3
3
  **Server:** openalex-mcp-server
4
- **Version:** 0.7.14
5
- **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.5`
4
+ **Version:** 0.7.16
5
+ **Framework:** [@cyanheads/mcp-ts-core](https://www.npmjs.com/package/@cyanheads/mcp-ts-core) `^0.13.6`
6
6
  **Engines:** Bun ≥1.4.0, Node ≥24.0.0
7
7
  **MCP SDK:** `@modelcontextprotocol/server` ^2.0.0
8
8
  **Zod:** ^4.6.5
@@ -168,7 +168,7 @@ Handlers receive a unified `ctx` object. Key properties:
168
168
 
169
169
  Handlers throw — the framework catches, classifies, and formats.
170
170
 
171
- **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable? }]` on `tool()` to receive a typed `ctx.fail(reason, …)` keyed by the declared reason union — `ctx.fail('typo')` is a TS error, `data.reason` is auto-populated, and the linter enforces conformance against the handler. The `recovery` field is required (≥5 words). Spread `ctx.recoveryFor('reason')` into `data` to opt the contract recovery onto the wire.
171
+ **Recommended: typed error contract.** Declare `errors: [{ reason, code, when, recovery, retryable?, thrownBy? }]` on `tool()` to receive a typed `ctx.fail(reason, …)` keyed by the declared reason union — `ctx.fail('typo')` is a TS error, `data.reason` is auto-populated, and the linter enforces conformance against the handler. The `recovery` field is required (≥5 words). Spread `ctx.recoveryFor('reason')` into `data` to opt the contract recovery onto the wire; `error-contract-recovery-unforwarded` warns per `ctx.fail` site that forwards neither the resolver nor its own `recovery` key.
172
172
 
173
173
  ```ts
174
174
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
@@ -177,6 +177,10 @@ errors: [
177
177
  { reason: 'semantic_per_page_cap', code: JsonRpcErrorCode.ValidationError,
178
178
  when: 'per_page exceeds the semantic-search cap',
179
179
  recovery: 'Reduce per_page to 50 or less, or switch search_mode to keyword.' },
180
+ { reason: 'upstream_timeout', code: JsonRpcErrorCode.Timeout,
181
+ when: 'OpenAlex did not respond within the request deadline',
182
+ recovery: 'Retry after a short delay, or narrow the request with tighter filters.',
183
+ thrownBy: 'service' },
180
184
  ],
181
185
  async handler(input, ctx) {
182
186
  if (overCap) throw ctx.fail('semantic_per_page_cap', message, { ...ctx.recoveryFor('semantic_per_page_cap') });
@@ -185,7 +189,7 @@ async handler(input, ctx) {
185
189
 
186
190
  **Declare contracts inline on each tool, even when similar across tools.** The contract is part of the tool's documented public surface — reading one tool definition file should give the full picture. Don't extract a shared `errors[]` constant; per-tool repetition is the intended cost of locality.
187
191
 
188
- The OpenAlex service throws factory errors (`notFound`, `rateLimited`, etc.) based on upstream status codes, carrying the contract `reason` on `data.reason` and the recovery via `ctx.recoveryFor(reason)`; those bubble through and are auto-classified. Because most declared reasons are produced in the service, handler-local precondition throws (`semantic_per_page_cap`, `reserved_filter_key`, …) live in module-level helpers (`assertListQueryConstraints`, `assertNoReservedFilterKey`, `resolveSeedToWorkId`) rather than inline: `error-contract-unthrown` only scans handlers holding a literal `ctx.fail(`, and an inline one would flag every service-produced reason as dead. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely without needing to be declared on a contract.
192
+ The OpenAlex service throws factory errors (`notFound`, `rateLimited`, etc.) based on upstream status codes, carrying the contract `reason` on `data.reason` and the recovery via `ctx.recoveryFor(reason)`; those bubble through and are auto-classified. Every such entry carries `thrownBy: 'service'` — lint-only metadata that tells `error-contract-unthrown`, whose scan reads the handler body alone, to skip a reason produced a layer below it. Handler-local precondition throws stay inline and unmarked so the rule keeps checking them: `semantic_without_query`, `semantic_per_page_cap`, `semantic_with_cursor`, `page_without_semantic`, `sample_with_cursor`, `sample_with_page`, `sample_with_semantic`, `sample_with_sort`, and `seed_without_sample` on `openalex_search_entities`; `reserved_filter_key` and the seed-lookup `entity_not_found` on `openalex_get_citation_graph`. Baseline codes (`InternalError`, `ServiceUnavailable`, `Timeout`, `ValidationError`, `SerializationError`, `RequestCancelled`) bubble freely without needing to be declared on a contract.
189
193
 
190
194
  **Fallback for ad-hoc throws:** error factories or plain `Error`.
191
195
 
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  <div align="center">
9
9
 
10
- [![Version](https://img.shields.io/badge/Version-0.7.14-blue.svg?style=flat-square)](./CHANGELOG.md) [![License](https://img.shields.io/badge/License-Apache%202.0-orange.svg?style=flat-square)](./LICENSE) [![Docker](https://img.shields.io/badge/Docker-ghcr.io-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/users/cyanheads/packages/container/package/openalex-mcp-server) [![MCP SDK](https://img.shields.io/badge/MCP%20SDK-^2.0.0-green.svg?style=flat-square)](https://modelcontextprotocol.io/) [![npm](https://img.shields.io/npm/v/@cyanheads/openalex-mcp-server?style=flat-square&logo=npm&logoColor=white)](https://www.npmjs.com/package/@cyanheads/openalex-mcp-server) [![TypeScript](https://img.shields.io/badge/TypeScript-^7.0.2-3178C6.svg?style=flat-square)](https://www.typescriptlang.org/) [![Bun](https://img.shields.io/badge/Bun-v1.4.0-blueviolet.svg?style=flat-square)](https://bun.sh/)
10
+ [![Version](https://img.shields.io/badge/Version-0.7.16-blue.svg?style=flat-square)](./CHANGELOG.md) [![License](https://img.shields.io/badge/License-Apache%202.0-orange.svg?style=flat-square)](./LICENSE) [![Docker](https://img.shields.io/badge/Docker-ghcr.io-2496ED?style=flat-square&logo=docker&logoColor=white)](https://github.com/users/cyanheads/packages/container/package/openalex-mcp-server) [![MCP SDK](https://img.shields.io/badge/MCP%20SDK-^2.0.0-green.svg?style=flat-square)](https://modelcontextprotocol.io/) [![npm](https://img.shields.io/npm/v/@cyanheads/openalex-mcp-server?style=flat-square&logo=npm&logoColor=white)](https://www.npmjs.com/package/@cyanheads/openalex-mcp-server) [![TypeScript](https://img.shields.io/badge/TypeScript-^7.0.2-3178C6.svg?style=flat-square)](https://www.typescriptlang.org/) [![Bun](https://img.shields.io/badge/Bun-v1.4.0-blueviolet.svg?style=flat-square)](https://bun.sh/)
11
11
 
12
12
  </div>
13
13
 
@@ -52,11 +52,12 @@ Scholarly catalog data from [OpenAlex](https://openalex.org) — 270M+ works, 90
52
52
 
53
53
  ### `openalex_search_entities` <sub>tool</sub>
54
54
 
55
- - Retrieve a single entity by ID — OpenAlex ID, DOI, ORCID, ROR, PMID, ISSN, or PMCID (bare or URL form). `id` takes precedence: search parameters passed alongside it are dropped, and the response names which ones. A PMCID resolves nothing (OpenAlex indexes none) — use the work's PMID or DOI instead
56
- - Keyword search (boolean operators, quoted phrases, wildcards, fuzzy match) plus `exact` and `semantic` search modes — semantic caps at 50 results per page and ~1 req/sec
55
+ - Retrieve a single entity by ID — OpenAlex ID, DOI, ORCID, ROR, PMID, ISSN, or PMCID (bare or URL form), or a keyword by its slug or keyword URL. `id` takes precedence: search parameters passed alongside it are dropped, and the response names which ones. A PMCID resolves nothing (OpenAlex indexes none) — use the work's PMID or DOI instead
56
+ - Keyword search (boolean operators, quoted phrases, wildcards, fuzzy match) plus `exact` and `semantic` search modes — semantic ranks a query-dependent candidate set at ~1 req/sec (up to 50 per page), and its `meta.count` reports the candidate count rather than a match total
57
57
  - Rich filter syntax: AND across fields, OR within a field (`|`), NOT (`!`), ranges, comparisons; a comma inside a filter value is rejected (use `|`, or a `.search` filter for free text)
58
58
  - `select` returns a curated per-entity-type default unless overridden, or `["*"]` for the full record; invalid field names error with the valid set
59
- - Cursor pagination, up to 100 results per page (default 25); `sample` (up to 100, single page only, no `cursor`) plus a deterministic `seed` for reproducible random sampling
59
+ - Cursor pagination for keyword and exact search, up to 100 results per page (default 25); semantic search walks its candidates with `page` (1-based) instead, and mixing either knob with the wrong `search_mode` is rejected before the upstream call
60
+ - `sample` (up to 100, single page only — neither `cursor` nor `page` applies) plus a deterministic `seed` for reproducible random sampling; keyword and exact modes only, and never alongside `sort` — OpenAlex does not sample a semantic search and refuses a sorted sample, so both combinations are rejected before the upstream call
60
61
  - `display_name` is nullable for untitled records; every call reports OpenAlex daily-budget cost and remaining balance
61
62
 
62
63
  ---
@@ -65,8 +66,8 @@ Scholarly catalog data from [OpenAlex](https://openalex.org) — 270M+ works, 90
65
66
 
66
67
  - Group any supported field for trend, distribution, or comparative analysis; combine with `filters` to scope the population before aggregation
67
68
  - Up to 200 groups per page (default). `order: "count"` (default) returns the top-N by count with no further pages; `order: "key"` enumerates all distinct values key-ascending with cursor pagination
68
- - `include_unknown` (default `false`) adds a group for entities with no value for the grouped field
69
- - Not every field is groupable — raw date fields, `.search` operators, and `from_*`/`to_*` range modifiers are rejected; check with `openalex_describe_fields(entity_type, "group_by")`
69
+ - `include_unknown` (default `false`) adds a group for entities with no value for the grouped field, flagged `is_unknown: true` and labeled as unknown in the text output. OpenAlex keys it `-111`/`-111.0` (numeric fields), `unknown` (text fields and `order: "key"`), or an ID ending in `/unknown`; the key is a sentinel, not a filter value. Boolean fields have no such group — a missing value counts as `false`
70
+ - Not every field is groupable — raw date fields, `.search` operators, `from_*`/`to_*` range modifiers, decimal scores such as `fwci`, `display_name`, and external-ID fields such as `doi` are rejected; `openalex_describe_fields(entity_type, "group_by")` lists the fields that group
70
71
  - Reports OpenAlex daily-budget cost and remaining balance — aggregation is priced far below paging the same entities
71
72
 
72
73
  ---
@@ -74,8 +75,9 @@ Scholarly catalog data from [OpenAlex](https://openalex.org) — 270M+ works, 90
74
75
  ### `openalex_resolve_name` <sub>tool</sub>
75
76
 
76
77
  - A name or partial name runs an autocomplete search: up to 10 matches with disambiguation hints (last institution, host organization, place, etc.)
77
- - An identifier — OpenAlex ID, DOI, ORCID, ROR, PMID, or ISSN, bare or in URL form — resolves directly to the one record it addresses; no `entity_type` needed, since the identifier determines its own. A PMCID is recognized but resolves nothing — OpenAlex indexes none
78
+ - An identifier — OpenAlex ID, DOI, ORCID, ROR, PMID, ISSN, or keyword URL, bare or in URL form — resolves directly to the one record it addresses; no `entity_type` needed, since the identifier determines its own. A PMCID is recognized but resolves nothing — OpenAlex indexes none
78
79
  - `filters` narrows autocomplete only; on an identifier lookup they're ignored and named in a notice
80
+ - With `entity_type` set, OpenAlex autocomplete fails on a name over 1,000 characters; that failure is reported once as `query_too_long` with advice to shorten the name, not retried as an outage
79
81
  - Reports OpenAlex daily-budget cost and remaining balance
80
82
 
81
83
  ---
@@ -84,7 +86,7 @@ Scholarly catalog data from [OpenAlex](https://openalex.org) — 270M+ works, 90
84
86
 
85
87
  - `direction` sets the edge: `cites` (works citing the seed), `cited_by` (the seed's own reference list), `related_to` (OpenAlex's algorithmic related works, ~8-30 typical, may be empty)
86
88
  - `seed_id` accepts an OpenAlex ID, DOI, or PMID (PMCID recognized but resolves nothing); validated against a live lookup first, so a non-existent seed fails as `NotFound` rather than returning an empty graph
87
- - Stacks with `filters`/`sort`/`select` to narrow the graph; `filters` cannot set `cites`/`cited_by`/`related_to` directly — those are reserved for `direction`
89
+ - Stacks with `filters`/`sort`/`select` to narrow the graph; `filters` cannot set `cites`/`cited_by`/`related_to`, nor an alias of one such as `cited_works` — those keys are reserved for `direction`
88
90
  - Cursor pagination, up to 100 results per page (default 25)
89
91
  - Reports OpenAlex daily-budget cost, covering both the seed-validation lookup and the graph page, plus remaining balance
90
92
 
@@ -93,7 +95,7 @@ Scholarly catalog data from [OpenAlex](https://openalex.org) — 270M+ works, 90
93
95
  ### `openalex_describe_fields` <sub>tool</sub>
94
96
 
95
97
  - Lists every valid field name for an entity type + context (`filter`, `group_by`, `select`) — the complete pool, never truncated
96
- - `group_by` is the filter set minus raw date fields, `.search`/`.search.exact` operators, and `from_*`/`to_*` range modifiers, which OpenAlex rejects as aggregation keys
98
+ - `group_by` is the filter set minus what OpenAlex rejects as an aggregation key: raw date fields, `.search`/`.search.exact` operators, `from_*`/`to_*` range modifiers, and a per-entity-type set found by grouping every listed field against the live API — decimal scores such as `fwci`, several source year fields, `display_name`, and external-ID fields among them
97
99
  - Optional `query` reorders results by name similarity without dropping any field — a nested value's parent object stays reachable further down the list
98
100
  - Backed by a generated field catalog — no live API calls
99
101
 
@@ -130,6 +132,7 @@ Agent-friendly output:
130
132
  - Effective-query echo — search, trends, and citation-graph responses echo the criteria that actually ran, so an empty result is diagnosable without re-reading the request
131
133
  - Discriminated output contracts — typed error reasons (`entity_not_found`, `upstream_budget_exhausted`, `semantic_per_page_cap`, `reserved_filter_key`, and more) each carrying an explicit recovery hint
132
134
  - Response shaping — abstracts are reconstructed from OpenAlex's inverted-index encoding into plaintext, and `display_name` stays `null` for untitled or paratext records instead of being backfilled
135
+ - Clean provider text — OpenAlex passes titles, abstracts, and names through unsanitized; HTML entities are decoded against the full WHATWG table, comments and HTML/JATS/MathML formatting tags are removed, and literal text such as `A < B` is kept. The text output escapes that text for Markdown, so a stray `*`, `<tag>`, or `[x](y)` renders as written; IDs, and URLs that render as links, stay byte-identical
133
136
 
134
137
  ## Getting started
135
138
 
@@ -0,0 +1,33 @@
1
+ ---
2
+ summary: "Keyword identifiers, semantic-mode `page` pagination, AND'd filter aliases, and honest pagination/notice handling across the paginating tools."
3
+ breaking: false
4
+ security: false
5
+ ---
6
+
7
+ # 0.7.15 — 2026-09-22
8
+
9
+ ## Added
10
+
11
+ - **Keyword identifiers** resolve via their OpenAlex URL or bare slug (`https://openalex.org/keywords/groundwater` or `groundwater`) — keywords never had a native alphanumeric ID, so the removed `K`-prefixed routing arm 404'd. ([#68](https://github.com/cyanheads/openalex-mcp-server/issues/68))
12
+ - **`page`** input on `openalex_search_entities` paginates semantic search (1-based), the one mode OpenAlex rejects `cursor` on. Combining `page`/`cursor`/`sample` with the wrong mode now throws `semantic_with_cursor`, `page_without_semantic`, or `sample_with_page`. ([#71](https://github.com/cyanheads/openalex-mcp-server/issues/71))
13
+ - **`best_oa_location`** joins the default `works` projection, naming a green-OA work's readable copy (`pdf_url`, `license`, `version`, hosting source) instead of leaving only the closed publisher location. ([#79](https://github.com/cyanheads/openalex-mcp-server/issues/79))
14
+ - **`query_too_long`** error reason on `openalex_search_entities` — an over-length `query` (HTTP 400) now maps to its own contract entry instead of the generic invalid-params one. ([#71](https://github.com/cyanheads/openalex-mcp-server/issues/71))
15
+
16
+ ## Changed
17
+
18
+ - **Filter aliases** resolving to the same upstream key are now AND'd instead of silently overwriting — `{year: "2020", publication_year: "2024"}` now matches works in both years, matching OpenAlex's own repeated-key behavior. ([#70](https://github.com/cyanheads/openalex-mcp-server/issues/70))
19
+ - **`openalex_get_citation_graph`'s reserved-key guard** now checks the *translated* filter key, so an alias of `cites`/`cited_by`/`related_to` (e.g. `cited_works`) is caught instead of colliding silently with `direction`. ([#70](https://github.com/cyanheads/openalex-mcp-server/issues/70))
20
+ - **Pagination-exhausted notices** — `openalex_search_entities`, `openalex_analyze_trends`, and `openalex_get_citation_graph` now report the traversal as finished on an empty page reached via `cursor`, instead of advising a broader query. ([#74](https://github.com/cyanheads/openalex-mcp-server/issues/74))
21
+ - **`meta.per_page`** on `openalex_search_entities` and `openalex_get_citation_graph` now documents itself as the requested page size, not the record count returned. ([#74](https://github.com/cyanheads/openalex-mcp-server/issues/74))
22
+ - **`meta.count`** under `search_mode: "semantic"` is disclosed as the capped candidate ceiling (≤50), not an exhaustive match total. ([#71](https://github.com/cyanheads/openalex-mcp-server/issues/71))
23
+
24
+ ## Fixed
25
+
26
+ - **Blank `id`/`query`/`cursor`/`group_by` inputs** on the paginating tools are now rejected at the schema, instead of running as an unfiltered listing or an accepted "exhausted" page. ([#69](https://github.com/cyanheads/openalex-mcp-server/issues/69), [#80](https://github.com/cyanheads/openalex-mcp-server/issues/80))
27
+ - **`openalex_analyze_trends`** no longer reports a successful empty aggregation when OpenAlex answers with its plain list shape (no `group_by` key) — it now throws `upstream_missing_group_by`. ([#69](https://github.com/cyanheads/openalex-mcp-server/issues/69))
28
+ - **`openalex_literature_review`** prompt's step 3 now re-runs the step-2 filtered search sorted by `-cited_by_count` instead of an unfiltered search, and names the fields to `select` on the detail lookup. ([#77](https://github.com/cyanheads/openalex-mcp-server/issues/77))
29
+
30
+ ## Dependencies
31
+
32
+ - `@cyanheads/mcp-ts-core` ^0.13.5 → ^0.13.6
33
+ - `@types/node` ^26.6.1 → ^26.6.2
@@ -0,0 +1,32 @@
1
+ ---
2
+ summary: "Provider text arrives clean on both surfaces (entities decoded, markup removed, Markdown escaped in content[]), plus a flagged unknown group_by bucket, local rejection of sample with semantic search or sort, and corrected group_by field lists and error reasons."
3
+ breaking: false
4
+ security: false
5
+ ---
6
+
7
+ # 0.7.16 — 2026-09-24
8
+
9
+ ## Added
10
+
11
+ - **`is_unknown`** on `openalex_analyze_trends` groups — set on the missing-value bucket `include_unknown` adds (keyed `-111`, `-111.0`, `unknown`, or an ID ending in `/unknown`). The text output labels it `unknown (no value; key …)` and renders it after the last year of a time series. ([#75](https://github.com/cyanheads/openalex-mcp-server/issues/75))
12
+ - **`sample_with_semantic`** and **`sample_with_sort`** error reasons on `openalex_search_entities` — `sample` with `search_mode: "semantic"` (which OpenAlex does not sample) or with any `sort` (which OpenAlex refuses) is rejected before the upstream call. `id` lookups still drop both with a notice. ([#83](https://github.com/cyanheads/openalex-mcp-server/issues/83), [#85](https://github.com/cyanheads/openalex-mcp-server/issues/85))
13
+
14
+ ## Changed
15
+
16
+ - **Provider text in `structuredContent`** — string values now carry decoded HTML entities (full WHATWG table) with HTML comments removed and HTML/JATS/MathML formatting tags unwrapped; literal text such as `A < B` or `Fish <Actinopterygii>` is kept. Affected records return different values than before. ([#76](https://github.com/cyanheads/openalex-mcp-server/issues/76))
17
+ - **`content[]` escaping** — every `format()` backslash-escapes provider text for Markdown, so a stray `*`, `<tag>`, or `[x](y)` renders as written; IDs and URLs that render as links stay byte-identical. ([#76](https://github.com/cyanheads/openalex-mcp-server/issues/76))
18
+ - **`openalex_analyze_trends` group `key`** is passed through raw, exactly as OpenAlex returns it (it was entity-decoded before); `key_display_name` gets the provider-text normalization. ([#76](https://github.com/cyanheads/openalex-mcp-server/issues/76))
19
+
20
+ ## Fixed
21
+
22
+ - **Named-entity decoding** no longer resolves `Object.prototype` names — `&constructor;` stays literal instead of becoming `function Object() { [native code] }`. ([#76](https://github.com/cyanheads/openalex-mcp-server/issues/76))
23
+ - **`openalex_describe_fields` `group_by` view** drops the fields OpenAlex refuses to aggregate — decimal scores such as `fwci`, several source year fields, `display_name`, external-ID fields, and the concept keys on authors — and five works fields whose grouping fails with an HTTP 500 on every attempt (`cites`, `has_embeddings`, and the three `raw_type` location fields), per a live sweep of every listed field on all eight entity types; they stay valid filters. ([#86](https://github.com/cyanheads/openalex-mcp-server/issues/86))
24
+ - **`group_by` rejections** on authors' concept keys (reported upstream as an invalid ID) and on `referenced_works` now surface as `upstream_ungroupable_group_by`, whose recovery points at `openalex_describe_fields`; an invalid-ID 400 quoting a value from the request's `filter` keeps `upstream_invalid_id_value`. ([#87](https://github.com/cyanheads/openalex-mcp-server/issues/87))
25
+ - **`openalex_resolve_name`** reports the HTTP 500 that typed autocomplete returns for a `query` over 1,000 code points as `query_too_long` after one attempt, instead of a retried `upstream_unavailable` outage. ([#81](https://github.com/cyanheads/openalex-mcp-server/issues/81))
26
+ - **Semantic `meta.count`** — descriptions and the runtime notice no longer claim a 50-candidate ceiling; the candidate count is query-dependent and can exceed 50 (the 50-per-page cap stands). ([#84](https://github.com/cyanheads/openalex-mcp-server/issues/84))
27
+
28
+ ## Dependencies
29
+
30
+ - `mdast-util-from-markdown` ^2.0.3 (new devDependency)
31
+ - `mdast-util-gfm` ^3.1.0 (new devDependency)
32
+ - `micromark-extension-gfm` ^3.0.0 (new devDependency)
@@ -41,7 +41,7 @@ Follow this workflow using the OpenAlex tools:
41
41
  - Search with multiple related topic IDs to capture adjacent areas`}
42
42
  Use select to keep payloads manageable.
43
43
 
44
- 3. **Identify key papers** — Sort by cited_by_count to find landmark works. Use openalex_search_entities with id to get full details on the most important ones.
44
+ 3. **Identify key papers** — Re-run the step 2 search with sort: "-cited_by_count" to surface landmark works, keeping the topical filters in place: an explicit sort replaces relevance ranking, so without them you get the most-cited works in the catalog rather than in "${args.topic}". Then call openalex_search_entities with id and a select naming the fields you need (e.g. ["abstract", "authorships", "primary_location"]) for the most important ones — an id lookup on its own returns the curated default projection.
45
45
 
46
46
  4. **Trace citations** — For each key paper, use openalex_get_citation_graph with direction "cites" to find subsequent work that cites it, and direction "cited_by" to find foundational work it references.
47
47
 
@@ -1 +1 @@
1
- {"version":3,"file":"literature-review.prompt.js","sourceRoot":"","sources":["../../../../src/mcp-server/prompts/definitions/literature-review.prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAEnD,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC,4BAA4B,EAAE;IACzE,WAAW,EACT,wHAAwH;IAC1H,SAAS,EACP,2HAA2H;IAC7H,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QACb,KAAK,EAAE,CAAC;aACL,MAAM,EAAE;aACR,QAAQ,CACP,+FAA+F,CAChG;QACH,KAAK,EAAE,CAAC;aACL,IAAI,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;aACzB,QAAQ,EAAE;aACV,QAAQ,CACP,wGAAwG,CACzG;KACJ,CAAC;IACF,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE;QACjB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,QAAQ,CAAC;QACrC,OAAO;YACL;gBACE,IAAI,EAAE,MAAM;gBACZ,OAAO,EAAE;oBACP,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,+CAA+C,IAAI,CAAC,KAAK;;SAEhE,KAAK;;;;mHAIqG,IAAI,CAAC,KAAK;;iFAGjH,KAAK,KAAK,QAAQ;wBAChB,CAAC,CAAC;;;qCAGqB;wBACvB,CAAC,CAAC;;;sEAIN;;;;;;;;;;;;+IAYqI;iBACtI;aACF;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}
1
+ {"version":3,"file":"literature-review.prompt.js","sourceRoot":"","sources":["../../../../src/mcp-server/prompts/definitions/literature-review.prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,wBAAwB,CAAC;AAEnD,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC,4BAA4B,EAAE;IACzE,WAAW,EACT,wHAAwH;IAC1H,SAAS,EACP,2HAA2H;IAC7H,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QACb,KAAK,EAAE,CAAC;aACL,MAAM,EAAE;aACR,QAAQ,CACP,+FAA+F,CAChG;QACH,KAAK,EAAE,CAAC;aACL,IAAI,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;aACzB,QAAQ,EAAE;aACV,QAAQ,CACP,wGAAwG,CACzG;KACJ,CAAC;IACF,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE;QACjB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,QAAQ,CAAC;QACrC,OAAO;YACL;gBACE,IAAI,EAAE,MAAM;gBACZ,OAAO,EAAE;oBACP,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,+CAA+C,IAAI,CAAC,KAAK;;SAEhE,KAAK;;;;mHAIqG,IAAI,CAAC,KAAK;;iFAGjH,KAAK,KAAK,QAAQ;wBAChB,CAAC,CAAC;;;qCAGqB;wBACvB,CAAC,CAAC;;;sEAIN;;;+QAGqQ,IAAI,CAAC,KAAK;;;;;;;;;+IAS1I;iBACtI;aACF;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}
@@ -34,6 +34,7 @@ export declare const analyzeTrendsTool: import("@cyanheads/mcp-ts-core").ToolDef
34
34
  key: z.ZodString;
35
35
  key_display_name: z.ZodString;
36
36
  count: z.ZodNumber;
37
+ is_unknown: z.ZodOptional<z.ZodLiteral<true>>;
37
38
  }, z.core.$strip>>;
38
39
  }, z.core.$strip>, readonly [{
39
40
  readonly reason: "rate_limited";
@@ -41,64 +42,83 @@ export declare const analyzeTrendsTool: import("@cyanheads/mcp-ts-core").ToolDef
41
42
  readonly when: "OpenAlex throttled the request for exceeding its per-second ceiling (HTTP 429).";
42
43
  readonly retryable: true;
43
44
  readonly recovery: "Wait several seconds and retry; consider lowering request frequency for this caller.";
45
+ readonly thrownBy: "service";
44
46
  }, {
45
47
  readonly reason: "upstream_budget_exhausted";
46
48
  readonly code: JsonRpcErrorCode.RateLimited;
47
49
  readonly when: "The OpenAlex daily usage budget is spent (HTTP 429).";
48
50
  readonly retryable: false;
49
51
  readonly recovery: "The daily budget refills at midnight UTC — retrying sooner will not succeed. Set OPENALEX_API_KEY to a free key (https://openalex.org/settings/api) for a larger daily budget than anonymous access, or wait for the reset.";
52
+ readonly thrownBy: "service";
50
53
  }, {
51
54
  readonly reason: "upstream_timeout";
52
55
  readonly code: JsonRpcErrorCode.Timeout;
53
56
  readonly when: "OpenAlex did not respond within the request deadline.";
54
57
  readonly retryable: true;
55
58
  readonly recovery: "Retry after a short delay; if timeouts persist, narrow the request with tighter filters to reduce upstream load.";
59
+ readonly thrownBy: "service";
56
60
  }, {
57
61
  readonly reason: "upstream_unavailable";
58
62
  readonly code: JsonRpcErrorCode.ServiceUnavailable;
59
63
  readonly when: "OpenAlex was unreachable or unusable — HTTP 503, a connection failure, or a body that was empty, HTML, or unparseable JSON.";
60
64
  readonly retryable: true;
61
65
  readonly recovery: "Wait and retry; check https://openalex.org for service status if the outage persists.";
66
+ readonly thrownBy: "service";
62
67
  }, {
63
68
  readonly reason: "upstream_unauthorized";
64
69
  readonly code: JsonRpcErrorCode.Unauthorized;
65
70
  readonly when: "OpenAlex rejected the API key (HTTP 401).";
66
71
  readonly recovery: "Check that OPENALEX_API_KEY is set to a valid OpenAlex account API key (free from https://openalex.org/settings/api).";
72
+ readonly thrownBy: "service";
67
73
  }, {
68
74
  readonly reason: "upstream_forbidden";
69
75
  readonly code: JsonRpcErrorCode.Forbidden;
70
76
  readonly when: "OpenAlex denied access to the requested resource (HTTP 403).";
71
77
  readonly recovery: "Confirm the API key has access to this entity type or endpoint, then retry the request.";
78
+ readonly thrownBy: "service";
72
79
  }, {
73
80
  readonly reason: "comma_in_filter_value";
74
81
  readonly code: JsonRpcErrorCode.InvalidParams;
75
82
  readonly when: "A filter value contains a comma, which collides with the OpenAlex filter separator.";
76
83
  readonly recovery: "Use `|` for OR within a filter value (e.g. \"2020|2021\"), or use a `.search` filter or the `query` parameter for free-text phrases that contain commas.";
84
+ readonly thrownBy: "service";
77
85
  }, {
78
86
  readonly reason: "upstream_invalid_params";
79
87
  readonly code: JsonRpcErrorCode.InvalidParams;
80
88
  readonly when: "OpenAlex rejected an invalid group_by or filter field name (HTTP 400).";
81
89
  readonly recovery: "The upstream message names the rejected key and suggests close matches. Use openalex_describe_fields(entity_type, \"group_by\") to browse valid group_by fields, or openalex_describe_fields(entity_type, \"filter\") for filter fields.";
90
+ readonly thrownBy: "service";
82
91
  }, {
83
92
  readonly reason: "upstream_invalid_id_value";
84
93
  readonly code: JsonRpcErrorCode.InvalidParams;
85
94
  readonly when: "An entity-ID filter received a value that is not an OpenAlex ID — usually a name (HTTP 400).";
86
95
  readonly recovery: "Call openalex_resolve_name to turn the name into an OpenAlex ID, then filter by that ID. Entity filters such as authorships.author.id and primary_topic.id accept IDs only.";
96
+ readonly thrownBy: "service";
87
97
  }, {
88
98
  readonly reason: "upstream_ungroupable_group_by";
89
99
  readonly code: JsonRpcErrorCode.InvalidParams;
90
- readonly when: "group_by targets a raw date, float, or *.search field OpenAlex cannot aggregate (HTTP 400).";
91
- readonly recovery: "Group by a categorical or year field (e.g. publication_year, type, oa_status, or an integer count field) — raw date fields and *.search operators cannot be grouped. Call openalex_describe_fields(entity_type, \"group_by\") for the groupable set.";
100
+ readonly when: "group_by targets a field OpenAlex cannot aggregate — a raw date, a decimal score, a *.search operator, a field such as display_name, doi, or referenced_works, or a concept key on authors, which OpenAlex reports as an invalid OpenAlex ID (HTTP 400).";
101
+ readonly recovery: "Group by a field OpenAlex can aggregate, such as publication_year, type, or oa_status — call openalex_describe_fields(entity_type, \"group_by\") for the full groupable set of this entity type.";
102
+ readonly thrownBy: "service";
92
103
  }, {
93
104
  readonly reason: "upstream_invalid_params_other";
94
105
  readonly code: JsonRpcErrorCode.InvalidParams;
95
106
  readonly when: "OpenAlex rejected the request (HTTP 400) for a reason other than an invalid field name.";
96
107
  readonly recovery: "Read the upstream message in the error above and adjust the request — check filter operators, value formats, and the group_by field.";
108
+ readonly thrownBy: "service";
97
109
  }, {
98
110
  readonly reason: "upstream_validation_failed";
99
111
  readonly code: JsonRpcErrorCode.ValidationError;
100
112
  readonly when: "OpenAlex rejected the request as semantically invalid (HTTP 422).";
101
113
  readonly recovery: "Read the upstream message for the specific field, then adjust the request to satisfy validation.";
114
+ readonly thrownBy: "service";
115
+ }, {
116
+ readonly reason: "upstream_missing_group_by";
117
+ readonly code: JsonRpcErrorCode.ServiceUnavailable;
118
+ readonly when: "OpenAlex answered with its plain list shape, carrying no aggregation for the requested group_by.";
119
+ readonly retryable: true;
120
+ readonly recovery: "Retry the request; if it repeats, confirm group_by names a field OpenAlex can aggregate with openalex_describe_fields(entity_type, \"group_by\").";
121
+ readonly thrownBy: "service";
102
122
  }], {
103
123
  readonly echo: z.ZodString;
104
124
  readonly totalCount: z.ZodNumber;
@@ -1 +1 @@
1
- {"version":3,"file":"analyze-trends.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/analyze-trends.tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAKjE,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+S5B,CAAC"}
1
+ {"version":3,"file":"analyze-trends.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/analyze-trends.tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAMjE,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwV5B,CAAC"}
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { tool, z } from '@cyanheads/mcp-ts-core';
6
6
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
7
+ import { escapeMarkdown } from '../escape-markdown.js';
7
8
  import { renderBudgetTrailer } from '../render-budget.js';
8
9
  import { getOpenAlexService } from '../../../services/openalex/openalex-service.js';
9
10
  import { ENTITY_TYPES } from '../../../services/openalex/types.js';
@@ -18,6 +19,7 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
18
19
  when: 'OpenAlex throttled the request for exceeding its per-second ceiling (HTTP 429).',
19
20
  retryable: true,
20
21
  recovery: 'Wait several seconds and retry; consider lowering request frequency for this caller.',
22
+ thrownBy: 'service',
21
23
  },
22
24
  {
23
25
  reason: 'upstream_budget_exhausted',
@@ -25,6 +27,7 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
25
27
  when: 'The OpenAlex daily usage budget is spent (HTTP 429).',
26
28
  retryable: false,
27
29
  recovery: 'The daily budget refills at midnight UTC — retrying sooner will not succeed. Set OPENALEX_API_KEY to a free key (https://openalex.org/settings/api) for a larger daily budget than anonymous access, or wait for the reset.',
30
+ thrownBy: 'service',
28
31
  },
29
32
  {
30
33
  reason: 'upstream_timeout',
@@ -32,6 +35,7 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
32
35
  when: 'OpenAlex did not respond within the request deadline.',
33
36
  retryable: true,
34
37
  recovery: 'Retry after a short delay; if timeouts persist, narrow the request with tighter filters to reduce upstream load.',
38
+ thrownBy: 'service',
35
39
  },
36
40
  {
37
41
  reason: 'upstream_unavailable',
@@ -39,54 +43,71 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
39
43
  when: 'OpenAlex was unreachable or unusable — HTTP 503, a connection failure, or a body that was empty, HTML, or unparseable JSON.',
40
44
  retryable: true,
41
45
  recovery: 'Wait and retry; check https://openalex.org for service status if the outage persists.',
46
+ thrownBy: 'service',
42
47
  },
43
48
  {
44
49
  reason: 'upstream_unauthorized',
45
50
  code: JsonRpcErrorCode.Unauthorized,
46
51
  when: 'OpenAlex rejected the API key (HTTP 401).',
47
52
  recovery: 'Check that OPENALEX_API_KEY is set to a valid OpenAlex account API key (free from https://openalex.org/settings/api).',
53
+ thrownBy: 'service',
48
54
  },
49
55
  {
50
56
  reason: 'upstream_forbidden',
51
57
  code: JsonRpcErrorCode.Forbidden,
52
58
  when: 'OpenAlex denied access to the requested resource (HTTP 403).',
53
59
  recovery: 'Confirm the API key has access to this entity type or endpoint, then retry the request.',
60
+ thrownBy: 'service',
54
61
  },
55
62
  {
56
63
  reason: 'comma_in_filter_value',
57
64
  code: JsonRpcErrorCode.InvalidParams,
58
65
  when: 'A filter value contains a comma, which collides with the OpenAlex filter separator.',
59
66
  recovery: 'Use `|` for OR within a filter value (e.g. "2020|2021"), or use a `.search` filter or the `query` parameter for free-text phrases that contain commas.',
67
+ thrownBy: 'service',
60
68
  },
61
69
  {
62
70
  reason: 'upstream_invalid_params',
63
71
  code: JsonRpcErrorCode.InvalidParams,
64
72
  when: 'OpenAlex rejected an invalid group_by or filter field name (HTTP 400).',
65
73
  recovery: 'The upstream message names the rejected key and suggests close matches. Use openalex_describe_fields(entity_type, "group_by") to browse valid group_by fields, or openalex_describe_fields(entity_type, "filter") for filter fields.',
74
+ thrownBy: 'service',
66
75
  },
67
76
  {
68
77
  reason: 'upstream_invalid_id_value',
69
78
  code: JsonRpcErrorCode.InvalidParams,
70
79
  when: 'An entity-ID filter received a value that is not an OpenAlex ID — usually a name (HTTP 400).',
71
80
  recovery: 'Call openalex_resolve_name to turn the name into an OpenAlex ID, then filter by that ID. Entity filters such as authorships.author.id and primary_topic.id accept IDs only.',
81
+ thrownBy: 'service',
72
82
  },
73
83
  {
74
84
  reason: 'upstream_ungroupable_group_by',
75
85
  code: JsonRpcErrorCode.InvalidParams,
76
- when: 'group_by targets a raw date, float, or *.search field OpenAlex cannot aggregate (HTTP 400).',
77
- recovery: 'Group by a categorical or year field (e.g. publication_year, type, oa_status, or an integer count field) — raw date fields and *.search operators cannot be grouped. Call openalex_describe_fields(entity_type, "group_by") for the groupable set.',
86
+ when: 'group_by targets a field OpenAlex cannot aggregate — a raw date, a decimal score, a *.search operator, a field such as display_name, doi, or referenced_works, or a concept key on authors, which OpenAlex reports as an invalid OpenAlex ID (HTTP 400).',
87
+ recovery: 'Group by a field OpenAlex can aggregate, such as publication_year, type, or oa_status — call openalex_describe_fields(entity_type, "group_by") for the full groupable set of this entity type.',
88
+ thrownBy: 'service',
78
89
  },
79
90
  {
80
91
  reason: 'upstream_invalid_params_other',
81
92
  code: JsonRpcErrorCode.InvalidParams,
82
93
  when: 'OpenAlex rejected the request (HTTP 400) for a reason other than an invalid field name.',
83
94
  recovery: 'Read the upstream message in the error above and adjust the request — check filter operators, value formats, and the group_by field.',
95
+ thrownBy: 'service',
84
96
  },
85
97
  {
86
98
  reason: 'upstream_validation_failed',
87
99
  code: JsonRpcErrorCode.ValidationError,
88
100
  when: 'OpenAlex rejected the request as semantically invalid (HTTP 422).',
89
101
  recovery: 'Read the upstream message for the specific field, then adjust the request to satisfy validation.',
102
+ thrownBy: 'service',
103
+ },
104
+ {
105
+ reason: 'upstream_missing_group_by',
106
+ code: JsonRpcErrorCode.ServiceUnavailable,
107
+ when: 'OpenAlex answered with its plain list shape, carrying no aggregation for the requested group_by.',
108
+ retryable: true,
109
+ recovery: 'Retry the request; if it repeats, confirm group_by names a field OpenAlex can aggregate with openalex_describe_fields(entity_type, "group_by").',
110
+ thrownBy: 'service',
90
111
  },
91
112
  ],
92
113
  inputAliases: { filter: 'filters' },
@@ -94,7 +115,8 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
94
115
  entity_type: z.enum(ENTITY_TYPES).describe('Entity type to aggregate.'),
95
116
  group_by: z
96
117
  .string()
97
- .describe('Field to group by. Works examples: "publication_year", "type", "oa_status", "primary_topic.field.id", "authorships.institutions.country_code", "is_retracted". Authors: "last_known_institutions.country_code", "has_orcid". Sources: "type", "is_oa", "country_code". Not all fields support group_by — check entity docs if unsure.'),
118
+ .min(1)
119
+ .describe('Field to group by. Works examples: "publication_year", "type", "oa_status", "primary_topic.field.id", "authorships.institutions.country_code", "is_retracted". Authors: "last_known_institutions.country_code", "has_orcid". Sources: "type", "is_oa", "country_code". Not all fields support group_by — call openalex_describe_fields(entity_type, "group_by") for the groupable set.'),
98
120
  filters: z
99
121
  .record(z.string(), z.string())
100
122
  .optional()
@@ -102,7 +124,7 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
102
124
  include_unknown: z
103
125
  .boolean()
104
126
  .default(false)
105
- .describe('Include a group for entities with no value for the grouped field. Hidden by default.'),
127
+ .describe('Add a group for entities with no value for the grouped field. Hidden by default. That group carries `is_unknown: true`; OpenAlex keys it -111 or -111.0 on numeric fields, "unknown" on text fields and under order "key", and an ID ending in /unknown on ID fields — a sentinel, not a measured value. The key is not a filter value: passing -111 as a filter matches a numeric range, not the entities with no value. Boolean fields have no separate group — a missing value counts as false.'),
106
128
  per_page: z
107
129
  .number()
108
130
  .int()
@@ -116,8 +138,9 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
116
138
  .describe('Sort order for groups. Omit or pass "count" (default) to return the top-N groups by count descending — no further pages. Pass "key" to enumerate all distinct values in key-ascending order with cursor pagination. Use "key" only when you need a full traversal; most analysis calls want "count".'),
117
139
  cursor: z
118
140
  .string()
141
+ .min(1)
119
142
  .optional()
120
- .describe('Pagination cursor from a previous response. Only relevant when order is "key" — count-descending results have no next page. Pass the next_cursor from the previous response to advance.'),
143
+ .describe('Pagination cursor from a previous response. Only relevant when order is "key" — count-descending results have no next page. Pass the next_cursor from the previous response to advance. Omit it on the first call — an empty string is rejected, since a supplied-but-blank cursor is a caller mistake rather than a request for the first page.'),
121
144
  }),
122
145
  output: z.object({
123
146
  meta: z
@@ -133,9 +156,17 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
133
156
  groups: z
134
157
  .array(z
135
158
  .object({
136
- key: z.string().describe('Group key (OpenAlex ID or raw value).'),
137
- key_display_name: z.string().describe('Human-readable group label.'),
159
+ key: z
160
+ .string()
161
+ .describe('Group key (OpenAlex ID or raw value), exactly as OpenAlex returns it.'),
162
+ key_display_name: z
163
+ .string()
164
+ .describe('Human-readable group label as plain text, with HTML entities decoded and markup removed.'),
138
165
  count: z.number().describe('Number of entities in this group.'),
166
+ is_unknown: z
167
+ .literal(true)
168
+ .optional()
169
+ .describe('Present only on the group include_unknown adds for entities with no value; its key is an OpenAlex sentinel (-111, -111.0, unknown, or an ID ending in /unknown), not a measured value.'),
139
170
  })
140
171
  .describe('A single aggregation group with its key, display label, and entity count.'))
141
172
  .describe('Aggregation groups with counts.'),
@@ -153,7 +184,7 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
153
184
  notice: z
154
185
  .string()
155
186
  .optional()
156
- .describe('Guidance notice. Set when no groups are returned (recovery suggestions) or when the page is full and more groups likely exist (truncation signal with narrowing advice). Absent otherwise.'),
187
+ .describe('Guidance notice. Set when a first call returns no groups (recovery suggestions), when a `cursor` continuation returns none because the traversal is already finished, or when the page is full and more groups likely exist (truncation signal with narrowing advice). Absent otherwise.'),
157
188
  budget: z
158
189
  .object({
159
190
  costUsd: z
@@ -195,8 +226,14 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
195
226
  });
196
227
  const echo = buildAnalyzeEcho(input);
197
228
  ctx.enrich({ echo, totalCount: result.meta.count });
229
+ // An empty page on a `cursor` continuation means the key-ascending traversal already
230
+ // enumerated every group, so there is nothing left to remove or regroup. On a first call
231
+ // the same shape can still be an honest zero — including the all-values-unknown case,
232
+ // where `count` is nonzero but every matched entity is null for the grouped field.
198
233
  if (result.groups.length === 0) {
199
- ctx.enrich.notice(`No groups returned for ${echo}. Try removing filters or grouping by a different field.`);
234
+ ctx.enrich.notice(input.cursor === undefined
235
+ ? `No groups returned for ${echo}. Try removing filters or grouping by a different field.`
236
+ : `Pagination exhausted for ${echo} — the previous page held the last group, so this one came back empty. Stop paging rather than removing filters or regrouping.`);
200
237
  }
201
238
  else if (input.order === 'key') {
202
239
  // Key-ascending traversal: omitted groups sit beyond the cursor, not in a count tail, so
@@ -234,15 +271,16 @@ export const analyzeTrendsTool = tool('openalex_analyze_trends', {
234
271
  ];
235
272
  }
236
273
  // Time-series groupings are returned upstream in count-desc — useful for "top N years"
237
- // but jarring when reading a trend. Only the rendered text is reordered;
238
- // structuredContent stays in upstream order for callers that want it.
239
- const renderOrder = isTimeSeriesGrouping(result.groups)
240
- ? [...result.groups].sort((a, b) => a.key.localeCompare(b.key))
274
+ // but jarring when reading a trend. Only the rendered text is reordered, with the
275
+ // unknown bucket after the last period; structuredContent stays in upstream order.
276
+ const known = result.groups.filter((g) => !g.is_unknown);
277
+ const renderOrder = isTimeSeriesGrouping(known)
278
+ ? [
279
+ ...known.sort((a, b) => a.key.localeCompare(b.key)),
280
+ ...result.groups.filter((g) => g.is_unknown),
281
+ ]
241
282
  : result.groups;
242
- const lines = renderOrder.map((g) => {
243
- const label = g.key === g.key_display_name ? g.key_display_name : `${g.key_display_name} (${g.key})`;
244
- return `${label}: ${g.count}`;
245
- });
283
+ const lines = renderOrder.map((g) => `${renderGroupLabel(g)}: ${g.count}`);
246
284
  const footer = result.meta.next_cursor
247
285
  ? `\n\n*More groups available — next_cursor: \`${result.meta.next_cursor}\`*`
248
286
  : '';
@@ -258,6 +296,22 @@ const YEAR_OR_DATE_PATTERN = /^\d{4}(-\d{2}-\d{2})?$/;
258
296
  function isTimeSeriesGrouping(groups) {
259
297
  return groups.length > 1 && groups.every((g) => YEAR_OR_DATE_PATTERN.test(g.key));
260
298
  }
299
+ /**
300
+ * The label a group line opens with. The unknown bucket is named as such — its key is a
301
+ * sentinel, and `-111.0: 48777` reads as a measured value. A label that begins the line is
302
+ * escaped for that position; the key is upstream's own and stays byte-identical unless it
303
+ * carries Markdown syntax.
304
+ */
305
+ function renderGroupLabel(g) {
306
+ const key = escapeMarkdown(g.key);
307
+ if (g.is_unknown) {
308
+ const redundant = g.key_display_name === g.key || g.key_display_name.toLowerCase() === 'unknown';
309
+ const label = redundant ? '' : `, label ${escapeMarkdown(g.key_display_name)}`;
310
+ return `unknown (no value; key ${key}${label})`;
311
+ }
312
+ const display = escapeMarkdown(g.key_display_name, 'line-start');
313
+ return g.key === g.key_display_name ? display : `${display} (${key})`;
314
+ }
261
315
  function buildAnalyzeEcho(input) {
262
316
  const parts = [`entity_type=${input.entity_type}`, `group_by=${input.group_by}`];
263
317
  if (input.filters && Object.keys(input.filters).length > 0) {