@cyanheads/secedgar-mcp-server 0.20.1 → 0.21.1

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 (126) hide show
  1. package/AGENTS.md +33 -26
  2. package/CLAUDE.md +33 -26
  3. package/README.md +23 -12
  4. package/changelog/0.21.x/0.21.0.md +35 -0
  5. package/changelog/0.21.x/0.21.1.md +29 -0
  6. package/dist/mcp-server/prompts/definitions/company-analysis.prompt.js +3 -3
  7. package/dist/mcp-server/prompts/definitions/company-analysis.prompt.js.map +1 -1
  8. package/dist/mcp-server/tools/annual-report-reads.d.ts +53 -0
  9. package/dist/mcp-server/tools/annual-report-reads.d.ts.map +1 -0
  10. package/dist/mcp-server/tools/annual-report-reads.js +145 -0
  11. package/dist/mcp-server/tools/annual-report-reads.js.map +1 -0
  12. package/dist/mcp-server/tools/blockquote.d.ts +13 -0
  13. package/dist/mcp-server/tools/blockquote.d.ts.map +1 -0
  14. package/dist/mcp-server/tools/blockquote.js +18 -0
  15. package/dist/mcp-server/tools/blockquote.js.map +1 -0
  16. package/dist/mcp-server/tools/calendar-quarter.d.ts +22 -0
  17. package/dist/mcp-server/tools/calendar-quarter.d.ts.map +1 -0
  18. package/dist/mcp-server/tools/calendar-quarter.js +34 -0
  19. package/dist/mcp-server/tools/calendar-quarter.js.map +1 -0
  20. package/dist/mcp-server/tools/definitions/company-search.tool.d.ts.map +1 -1
  21. package/dist/mcp-server/tools/definitions/company-search.tool.js +10 -21
  22. package/dist/mcp-server/tools/definitions/company-search.tool.js.map +1 -1
  23. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts +12 -2
  24. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/compare-companies.tool.js +120 -29
  26. package/dist/mcp-server/tools/definitions/compare-companies.tool.js.map +1 -1
  27. package/dist/mcp-server/tools/definitions/find-holders.tool.d.ts.map +1 -1
  28. package/dist/mcp-server/tools/definitions/find-holders.tool.js +9 -16
  29. package/dist/mcp-server/tools/definitions/find-holders.tool.js.map +1 -1
  30. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.d.ts +31 -9
  31. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.d.ts.map +1 -1
  32. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js +268 -88
  33. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js.map +1 -1
  34. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts +10 -0
  35. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts.map +1 -1
  36. package/dist/mcp-server/tools/definitions/get-filing.tool.js +164 -10
  37. package/dist/mcp-server/tools/definitions/get-filing.tool.js.map +1 -1
  38. package/dist/mcp-server/tools/definitions/get-financials.tool.d.ts +1 -0
  39. package/dist/mcp-server/tools/definitions/get-financials.tool.d.ts.map +1 -1
  40. package/dist/mcp-server/tools/definitions/get-financials.tool.js +219 -128
  41. package/dist/mcp-server/tools/definitions/get-financials.tool.js.map +1 -1
  42. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.d.ts.map +1 -1
  43. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.js +2 -3
  44. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.js.map +1 -1
  45. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.d.ts +44 -0
  46. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.d.ts.map +1 -1
  47. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.js +336 -75
  48. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.js.map +1 -1
  49. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.d.ts +12 -0
  50. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.d.ts.map +1 -1
  51. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.js +16 -31
  52. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.js.map +1 -1
  53. package/dist/mcp-server/tools/definitions/get-material-events.tool.d.ts +15 -0
  54. package/dist/mcp-server/tools/definitions/get-material-events.tool.d.ts.map +1 -1
  55. package/dist/mcp-server/tools/definitions/get-material-events.tool.js +107 -54
  56. package/dist/mcp-server/tools/definitions/get-material-events.tool.js.map +1 -1
  57. package/dist/mcp-server/tools/definitions/get-snapshot.tool.d.ts +5 -0
  58. package/dist/mcp-server/tools/definitions/get-snapshot.tool.d.ts.map +1 -1
  59. package/dist/mcp-server/tools/definitions/get-snapshot.tool.js +48 -17
  60. package/dist/mcp-server/tools/definitions/get-snapshot.tool.js.map +1 -1
  61. package/dist/mcp-server/tools/definitions/index.d.ts +526 -464
  62. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  63. package/dist/mcp-server/tools/definitions/search-concepts.tool.js +1 -1
  64. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts +16 -0
  65. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts.map +1 -1
  66. package/dist/mcp-server/tools/definitions/search-filings.tool.js +194 -70
  67. package/dist/mcp-server/tools/definitions/search-filings.tool.js.map +1 -1
  68. package/dist/mcp-server/tools/filing-dates.d.ts +48 -0
  69. package/dist/mcp-server/tools/filing-dates.d.ts.map +1 -0
  70. package/dist/mcp-server/tools/filing-dates.js +99 -0
  71. package/dist/mcp-server/tools/filing-dates.js.map +1 -0
  72. package/dist/mcp-server/tools/limit-clamp.d.ts.map +1 -1
  73. package/dist/mcp-server/tools/limit-clamp.js +6 -2
  74. package/dist/mcp-server/tools/limit-clamp.js.map +1 -1
  75. package/dist/services/edgar/body-text-decoder.d.ts +33 -0
  76. package/dist/services/edgar/body-text-decoder.d.ts.map +1 -0
  77. package/dist/services/edgar/body-text-decoder.js +103 -0
  78. package/dist/services/edgar/body-text-decoder.js.map +1 -0
  79. package/dist/services/edgar/call-scope.d.ts +9 -0
  80. package/dist/services/edgar/call-scope.d.ts.map +1 -1
  81. package/dist/services/edgar/call-scope.js +3 -0
  82. package/dist/services/edgar/call-scope.js.map +1 -1
  83. package/dist/services/edgar/concept-map.d.ts.map +1 -1
  84. package/dist/services/edgar/concept-map.js +70 -12
  85. package/dist/services/edgar/concept-map.js.map +1 -1
  86. package/dist/services/edgar/concept-series.d.ts +126 -9
  87. package/dist/services/edgar/concept-series.d.ts.map +1 -1
  88. package/dist/services/edgar/concept-series.js +217 -21
  89. package/dist/services/edgar/concept-series.js.map +1 -1
  90. package/dist/services/edgar/edgar-api-service.d.ts +31 -15
  91. package/dist/services/edgar/edgar-api-service.d.ts.map +1 -1
  92. package/dist/services/edgar/edgar-api-service.js +182 -36
  93. package/dist/services/edgar/edgar-api-service.js.map +1 -1
  94. package/dist/services/edgar/eight-k-items.d.ts +19 -1
  95. package/dist/services/edgar/eight-k-items.d.ts.map +1 -1
  96. package/dist/services/edgar/eight-k-items.js +24 -1
  97. package/dist/services/edgar/eight-k-items.js.map +1 -1
  98. package/dist/services/edgar/filing-headers.d.ts +22 -10
  99. package/dist/services/edgar/filing-headers.d.ts.map +1 -1
  100. package/dist/services/edgar/filing-headers.js +98 -15
  101. package/dist/services/edgar/filing-headers.js.map +1 -1
  102. package/dist/services/edgar/filing-to-text.d.ts +13 -6
  103. package/dist/services/edgar/filing-to-text.d.ts.map +1 -1
  104. package/dist/services/edgar/filing-to-text.js +23 -3
  105. package/dist/services/edgar/filing-to-text.js.map +1 -1
  106. package/dist/services/edgar/fiscal-periods.d.ts +14 -1
  107. package/dist/services/edgar/fiscal-periods.d.ts.map +1 -1
  108. package/dist/services/edgar/fiscal-periods.js +47 -18
  109. package/dist/services/edgar/fiscal-periods.js.map +1 -1
  110. package/dist/services/edgar/form4-amendments.d.ts +63 -0
  111. package/dist/services/edgar/form4-amendments.d.ts.map +1 -0
  112. package/dist/services/edgar/form4-amendments.js +99 -0
  113. package/dist/services/edgar/form4-amendments.js.map +1 -0
  114. package/dist/services/edgar/mirror/companyfacts-sync.d.ts +6 -1
  115. package/dist/services/edgar/mirror/companyfacts-sync.d.ts.map +1 -1
  116. package/dist/services/edgar/mirror/companyfacts-sync.js +29 -6
  117. package/dist/services/edgar/mirror/companyfacts-sync.js.map +1 -1
  118. package/dist/services/edgar/ownership-parser.d.ts +24 -0
  119. package/dist/services/edgar/ownership-parser.d.ts.map +1 -1
  120. package/dist/services/edgar/ownership-parser.js +82 -0
  121. package/dist/services/edgar/ownership-parser.js.map +1 -1
  122. package/dist/services/edgar/types.d.ts +5 -1
  123. package/dist/services/edgar/types.d.ts.map +1 -1
  124. package/package.json +3 -3
  125. package/server.json +3 -3
  126. package/skills/secedgar-guide/SKILL.md +11 -7
@@ -7,6 +7,7 @@ import { tool, z } from '@cyanheads/mcp-ts-core';
7
7
  import { JsonRpcErrorCode } from '@cyanheads/mcp-ts-core/errors';
8
8
  import { escapeMarkdownInline } from '@cyanheads/mcp-ts-core/utils';
9
9
  import { ambiguousMatches } from '../ambiguous-matches.js';
10
+ import { AnnualReportReads } from '../annual-report-reads.js';
10
11
  import { datasetSchema } from '../dataset-schema.js';
11
12
  import { formatUsd, groupedDigits } from '../format-usd.js';
12
13
  import { resolvedAsField } from '../resolved-as.js';
@@ -14,37 +15,25 @@ import { SEC_UPSTREAM_ERRORS } from '../sec-upstream-errors.js';
14
15
  import { dataframeGuidance, getCanvasBridge, toDatasetField, } from '../../../services/canvas-bridge/canvas-bridge.js';
15
16
  import { CallScope } from '../../../services/edgar/call-scope.js';
16
17
  import { describeUnknownConcepts, findUnknownConcept, resolveConcept, resolveConceptTarget, } from '../../../services/edgar/concept-map.js';
17
- import { conceptLineCaveats, describingTag, filerFiscalYearEnds, filerFiscalYearEndsWithComparatives, isQuarterlyForm, matchesPeriodType, rankSeriesUnits, relatedTagReadings, relatedTagsFor, resolveFrameSeriesByUnit, seriesStalenessCaveats, } from '../../../services/edgar/concept-series.js';
18
+ import { annualReportGapCaveat, conceptLineCaveats, describingTag, filerFiscalYearEnds, filerFiscalYearEndsWithComparatives, isQuarterlyForm, matchesPeriodType, newestReportedPeriod, rankSeriesUnits, relatedTagReadings, relatedTagsFor, resolveFrameSeriesByUnit, resolveYtdSeriesByUnit, seriesStalenessCaveats, taxonomyRetry, } from '../../../services/edgar/concept-series.js';
18
19
  import { getEdgarApiService } from '../../../services/edgar/edgar-api-service.js';
19
- import { missingQuarterCaveats } from '../../../services/edgar/fiscal-periods.js';
20
+ import { missingQuarterCaveats, singleQuarterCaveats } from '../../../services/edgar/fiscal-periods.js';
20
21
  import { nonUsListingNote } from '../../../services/edgar/listing-codes.js';
21
22
  /** The taxonomies the `taxonomy` input accepts — the only ones a retry hint may name. */
22
23
  const TAXONOMIES = ['us-gaap', 'ifrs-full', 'dei'];
23
- /** Whether a companyfacts concept carries any frame-aligned value (#141: non-array units skipped). */
24
- function hasFramedValue(concept) {
25
- return Object.values(concept?.units ?? {}).some((values) => Array.isArray(values) && values.some((value) => value.frame));
26
- }
27
24
  /**
28
- * The retry that answers a concept missing under the taxonomy tried, read from
29
- * the filer's companyfacts (#164): the first other accepted taxonomy where a
30
- * friendly name resolves to a tag carrying framed values, or where a raw tag
31
- * itself does. `undefined` when none does.
25
+ * The `no_concept_data` hint's lead when another taxonomy answers the concept
26
+ * (#164). It names the namespace the concept resolves to, which this tool's
27
+ * `taxonomy` accepts as given (`dei` for `shares_outstanding`).
32
28
  */
33
- function taxonomyRetry(concept, tried, namespaces) {
29
+ function taxonomyRetryHint(concept, requested, namespaces) {
34
30
  const name = concept.trim();
35
- if (resolveConcept(name)) {
36
- for (const requested of TAXONOMIES) {
37
- const target = resolveConceptTarget(name, requested);
38
- if (target.taxonomy === tried)
39
- continue;
40
- const tag = target.tags.find((t) => hasFramedValue(namespaces[target.taxonomy]?.[t]));
41
- if (tag)
42
- return `Retry with taxonomy: "${target.taxonomy}" — ${name} resolves there to ${tag}.`;
43
- }
44
- return undefined;
45
- }
46
- const taxonomy = TAXONOMIES.find((t) => t !== tried && hasFramedValue(namespaces[t]?.[name]));
47
- return taxonomy && `${name} is reported under ${taxonomy} — retry with taxonomy: "${taxonomy}".`;
31
+ const retry = taxonomyRetry(name, requested, namespaces, TAXONOMIES);
32
+ if (!retry)
33
+ return;
34
+ return resolveConcept(name)
35
+ ? `Retry with taxonomy: "${retry.taxonomy}" — ${name} resolves there to ${retry.tag}.`
36
+ : `${name} is reported under ${retry.taxonomy} — retry with taxonomy: "${retry.taxonomy}".`;
48
37
  }
49
38
  /**
50
39
  * The reported unit key a `unit` input names: exact after `fetch_frames`' dashed
@@ -58,12 +47,15 @@ function matchUnitKey(requested, reported) {
58
47
  const folded = reported.filter((key) => key.toLowerCase() === wanted.toLowerCase());
59
48
  return folded.length === 1 ? folded[0] : undefined;
60
49
  }
61
- /** `USD (3 periods, CY2016–CY2018)` — a unit's frames, oldest to newest. */
62
- function describeUnitFrames(unitKey, frames) {
63
- const ordered = [...frames].sort((a, b) => a.end.localeCompare(b.end));
64
- const first = ordered[0]?.frame;
65
- const last = ordered.at(-1)?.frame;
66
- const span = first === last ? first : `${first}–${last}`;
50
+ /**
51
+ * `USD (3 periods, CY2016–CY2018)` — a unit's periods, oldest to newest, each named by
52
+ * its key: a frame, or a year-to-date interval, whose span `joiner` reads ` to `.
53
+ */
54
+ function describeUnitPeriods(unitKey, periods, joiner) {
55
+ const ordered = [...periods].sort(([, a], [, b]) => a.end.localeCompare(b.end));
56
+ const first = ordered[0]?.[0];
57
+ const last = ordered.at(-1)?.[0];
58
+ const span = first === last ? first : `${first}${joiner}${last}`;
67
59
  return `${unitKey} (${ordered.length} period${ordered.length === 1 ? '' : 's'}, ${span})`;
68
60
  }
69
61
  /** How long the related-tag reads may take, queue time included, before they are dropped. */
@@ -71,9 +63,10 @@ const RELATED_READ_DEADLINE_MS = 3_000;
71
63
  /**
72
64
  * The filer's related-tag facts (#258), one companyconcept read per tag gathered
73
65
  * under `facts['us-gaap']` as companyfacts holds them. Best-effort: each read gets
74
- * one attempt, under its own deadline beside the caller's signal, so a 404, a
75
- * failure, or a stall only leaves that tag out — a cancelled call still fails.
76
- * `undefined` when the concept has no related tags.
66
+ * one attempt as a side read, yielding its pacer slot to primary reads (#283), under
67
+ * its own deadline beside the caller's signal, so a 404, a failure, a stall, or a
68
+ * wait for a slot that outlasts the deadline only leaves that tag out — a cancelled
69
+ * call still fails. `undefined` when the concept has no related tags.
77
70
  */
78
71
  async function readRelatedFacts(cik, related, ctx) {
79
72
  if (related.length === 0)
@@ -82,6 +75,7 @@ async function readRelatedFacts(cik, related, ctx) {
82
75
  const timer = setTimeout(() => deadline.abort(new DOMException('Related-tag read deadline passed', 'TimeoutError')), RELATED_READ_DEADLINE_MS);
83
76
  const scope = new CallScope(AbortSignal.any([ctx.signal, deadline.signal]), {
84
77
  singleAttempt: true,
78
+ sideRead: true,
85
79
  });
86
80
  try {
87
81
  const reads = await Promise.allSettled(related.map(({ tag }) => getEdgarApiService().tryGetCompanyConcept(cik, 'us-gaap', tag, scope)));
@@ -188,9 +182,9 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
188
182
  .default('us-gaap')
189
183
  .describe('XBRL taxonomy. us-gaap for US companies, ifrs-full for foreign filers, dei for entity info (shares outstanding).'),
190
184
  period_type: z
191
- .enum(['annual', 'quarterly', 'all'])
185
+ .enum(['annual', 'quarterly', 'all', 'ytd'])
192
186
  .optional()
193
- .describe('Filter to annual (FY) or quarterly (Q1-Q4) data. "all" returns both. For an instant (balance-sheet) concept, "annual" returns the values dated on the filer\'s fiscal-year ends. When omitted, defaults to "annual", except that an instant concept returns its full series.'),
187
+ .describe('Annual (FY) or quarterly (Q1-Q4) periods; "all" returns both. "ytd" returns only year-to-date values: 10-Q/6-K durations longer than a quarter, keyed by start/end. An instant concept\'s "annual" is its fiscal-year-end values. Omitted: "annual", or an instant concept\'s full series.'),
194
188
  unit: z
195
189
  .string()
196
190
  .min(1)
@@ -221,7 +215,9 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
221
215
  data: z
222
216
  .array(z
223
217
  .object({
224
- period: z.string().describe('Calendar period label (e.g., "CY2023", "CY2023Q3").'),
218
+ period: z
219
+ .string()
220
+ .describe('Calendar period label (e.g., "CY2023", "CY2023Q3"), or under ytd the start/end interval.'),
225
221
  value: z.number().describe('Reported value.'),
226
222
  start: z
227
223
  .string()
@@ -246,7 +242,7 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
246
242
  .describe('XBRL tag this value was reported under; differs from concept when an older or successor tag answers this period.'),
247
243
  })
248
244
  .describe('One reported value with its period, source filing, and tag.'))
249
- .describe("Deduplicated series, newest first, one value per calendar period. A proxy-framed period takes the filer's own report; an annual frame held by a 10-Q trailing-twelve-month figure is left out. An instant's annual values are its fiscal-year-end values (CY2025Q2I for a June year end)."),
245
+ .describe("Deduplicated series, newest first, one value per period. A proxy-framed period takes the filer's own report; an annual frame held by a 10-Q trailing-twelve-month figure is left out. An instant's annual values are its fiscal-year-end values (CY2025Q2I for a June year end)."),
250
246
  tags_tried: z
251
247
  .array(z.string())
252
248
  .optional()
@@ -257,7 +253,7 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
257
253
  caveats: z
258
254
  .array(z.string())
259
255
  .optional()
260
- .describe('Completeness warnings, absent when none apply: other units reported, with counts and spans (pass unit to read one); quarters missing every recent year (fiscal Q4 is only in the 10-K); a series ending well before today (a retired or dropped tag) or a related tag the filer reports.'),
256
+ .describe("Warnings, absent when none: an annual report SEC's XBRL data lacks statements for; other units, with counts and spans (pass unit to read one); quarters missing every recent year (fiscal Q4 is 10-K only); a series 2+ years stale (a retired or dropped tag) or a related tag."),
261
257
  }),
262
258
  async handler(input, ctx) {
263
259
  /**
@@ -296,6 +292,8 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
296
292
  const { label, tagSelection, tags, taxonomy } = resolveConceptTarget(input.concept, input.taxonomy);
297
293
  // Default to "annual" for unset period_type; post-fetch fallback handles instant concepts (#48).
298
294
  const effectivePeriodType = input.period_type ?? 'annual';
295
+ /** Year-to-date values are a series of their own, never mixed with frames (#284). */
296
+ const ytd = effectivePeriodType === 'ytd';
299
297
  // Read every tag. `tryGetCompanyConcept` returns null for 404 (tag not reported
300
298
  // by this company); other errors fail the call.
301
299
  /** Taxonomy metadata of every tag that carried values, keyed by tag. */
@@ -328,18 +326,25 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
328
326
  * one after another could sum past the client's request timeout. They settle together,
329
327
  * and a failure fails the call as the first in tag order once none is left running.
330
328
  * Each related tag (#258) is read beside them, so a concept the filer reports only
331
- * under one already has its pointer when its own reads come back empty.
329
+ * under one already has its pointer when its own reads come back empty. Under
330
+ * `ifrs-full` the filer's newest XBRL annual report is read from its submissions feed
331
+ * behind them, best-effort (#269).
332
332
  */
333
333
  const related = relatedTagsFor(input.concept, input.taxonomy);
334
- const [settled, relatedFacts] = await Promise.all([
334
+ const ownReads = Promise.all([
335
335
  Promise.allSettled(tags.map((tag) => api.tryGetCompanyConcept(match.cik, taxonomy, tag, scope))),
336
336
  readRelatedFacts(match.cik, related, ctx),
337
- ]);
338
- const conceptReads = settled.map((read) => {
339
- if (read.status === 'rejected')
340
- throw read.reason;
341
- return read.value;
337
+ ]).then(([settled, relatedRead]) => {
338
+ const reads = settled.map((read) => {
339
+ if (read.status === 'rejected')
340
+ throw read.reason;
341
+ return read.value;
342
+ });
343
+ return [reads, relatedRead];
342
344
  });
345
+ const reportReads = new AnnualReportReads([match.cik], input.taxonomy, ctx);
346
+ const [[conceptReads, relatedFacts], reports] = await reportReads.settle(ownReads);
347
+ const report = reports.get(match.cik);
343
348
  for (const [tagIndex, tag] of tags.entries()) {
344
349
  tagsTried.push(tag);
345
350
  const resp = conceptReads[tagIndex];
@@ -421,13 +426,15 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
421
426
  * against the filer's fiscal-year ends, which only companyfacts carries
422
427
  * (#148). The first pass records whether any frame needs them; only then is
423
428
  * companyfacts read — reusing the payload a served-empty tag already read —
424
- * and the series resolved again, so no other series pays the request.
429
+ * and the series resolved again, so no other series pays the request. A
430
+ * year-to-date series shows no frame, so it skips that read; its caveats
431
+ * keep the first pass.
425
432
  */
426
433
  let needsYearEnds = false;
427
434
  let byUnit = resolveFrameSeriesByUnit(allUnits, tagSelection, () => {
428
435
  needsYearEnds = true;
429
436
  });
430
- if (needsYearEnds) {
437
+ if (needsYearEnds && !ytd) {
431
438
  // A failed read keeps those frames untested, and a caveat names them.
432
439
  await readFactsForYearEnds();
433
440
  if (!yearEndsUnread) {
@@ -435,15 +442,27 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
435
442
  byUnit = resolveFrameSeriesByUnit(allUnits, tagSelection, () => yearEnds);
436
443
  }
437
444
  }
438
- const rankedUnits = rankSeriesUnits(byUnit);
445
+ /**
446
+ * Year-to-date values (#284) — interim-report durations longer than a quarter,
447
+ * one per `start`/`end` interval within each unit key, by the frame series'
448
+ * tag rule. They are the rows under `ytd`; elsewhere they say whether the
449
+ * one-quarter-a-year caveat has anything to point at. Both maps hold the same
450
+ * unit keys, and the series shown ranks its own.
451
+ */
452
+ const ytdByUnit = resolveYtdSeriesByUnit(allUnits, tagSelection);
453
+ const shownByUnit = ytd
454
+ ? ytdByUnit
455
+ : byUnit;
456
+ const rankedUnits = rankSeriesUnits(shownByUnit);
439
457
  const unitKey = input.unit === undefined ? rankedUnits[0] : matchUnitKey(input.unit, [...byUnit.keys()]);
440
458
  const byFrameClean = (unitKey === undefined ? undefined : byUnit.get(unitKey)) ?? new Map();
459
+ const ytdClean = (unitKey === undefined ? undefined : ytdByUnit.get(unitKey)) ?? new Map();
441
460
  /**
442
461
  * The concept is described by the tag behind its newest value: a successor
443
462
  * behind an older leader answers the recent frames (#125), and under a
444
463
  * `coverage` selection only the winner contributes at all (#101).
445
464
  */
446
- const conceptTag = describingTag([...byFrameClean.values()], allUnits, tagSelection);
465
+ const conceptTag = describingTag([...(ytd ? ytdClean : byFrameClean).values()], allUnits, tagSelection);
447
466
  const conceptResponse = conceptTag !== undefined ? responses.get(conceptTag) : undefined;
448
467
  if (conceptTag === undefined || !conceptResponse) {
449
468
  // Probe companyfacts to discover what namespaces and tags this filer actually reports,
@@ -471,7 +490,7 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
471
490
  })
472
491
  .join('; ');
473
492
  summary = `This filer reports under: ${namespaceSummary}. Try a raw XBRL tag from one of these namespaces, or switch taxonomy to match.`;
474
- retry = taxonomyRetry(input.concept, taxonomy, namespaces);
493
+ retry = taxonomyRetryHint(input.concept, input.taxonomy, namespaces);
475
494
  }
476
495
  else {
477
496
  summary =
@@ -507,67 +526,104 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
507
526
  * value carried a frame.
508
527
  */
509
528
  const newestFramed = [...byFrameClean.values()].reduce((newest, unit) => (!newest || unit.end > newest.end ? unit : newest), undefined);
510
- if (!newestFramed) {
511
- const pointer = conceptLineCaveats(undefined, relatedReadings())[0];
512
- throw ctx.fail('no_frame_data', `'${conceptTag}' exists for this company but has no standard-period data.`, { ...(pointer ? { recovery: { hint: pointer } } : {}), tag: conceptTag });
513
- }
514
- // Filter by period type using frame pattern (fp reflects the filing, not the data point)
529
+ /** The rows shown, newest first, each named by its period: a frame, or a year-to-date interval. */
530
+ let shown;
531
+ /** The unit of every shown value. */
532
+ let shownUnit;
515
533
  // resolvedPeriodType tracks the actual period type after the instant fallback (#48).
516
534
  let resolvedPeriodType = effectivePeriodType;
517
- let filtered = Array.from(byFrameClean.values()).filter((u) => matchesPeriodType(u.frame, effectivePeriodType));
518
- // If period_type filter removed everything, check for instant-concept fallback (#48)
519
- if (filtered.length === 0 && byFrameClean.size > 0) {
520
- const sample = byFrameClean.values().next().value;
521
- const hasInstant = sample && /I$/.test(sample.frame);
522
- /**
523
- * Post-fetch instant fallback (#48): when `period_type` was NOT explicitly set
524
- * and the annual filter emptied a non-empty series whose frames are all instant
525
- * (CY####Q#I), return the full set. The caller asked for the concept's default
526
- * period — the right answer is the series that actually exists, not an error.
527
- */
528
- if (hasInstant && input.period_type === undefined) {
529
- filtered = Array.from(byFrameClean.values());
530
- resolvedPeriodType = 'all';
535
+ /** The 10-Q-held years shown that a failed companyfacts read may have left untested (#148). */
536
+ let untestedYears = [];
537
+ /** Under `ytd`, the newest row shown. */
538
+ let newestYtd;
539
+ if (ytd) {
540
+ const ytdRows = [...ytdClean.values()].sort((a, b) => b.end.localeCompare(a.end) || b.start.localeCompare(a.start));
541
+ const [newest] = ytdRows;
542
+ newestYtd = newest;
543
+ if (!newest) {
544
+ // Only an instant concept has no value with a start: it accumulates nothing.
545
+ const hint = allUnits.some((unit) => unit.start)
546
+ ? 'No 10-Q, 10-QT, or 6-K value of this concept spans more than a quarter and less than a year. Try period_type: "quarterly" or "annual".'
547
+ : `${conceptTag} is an instant (balance-sheet) concept: its values are dated, not accumulated over a period, so it has no year-to-date values. Try period_type: "quarterly" or "all" for every reported date.`;
548
+ throw ctx.fail('no_period_data', `No year-to-date data for '${conceptTag}'.`, {
549
+ recovery: { hint },
550
+ tag: conceptTag,
551
+ period_type: effectivePeriodType,
552
+ });
531
553
  }
532
- else {
533
- let hint;
534
- if (hasInstant) {
535
- /**
536
- * An explicit annual view of an instant concept is its values dated on
537
- * the filer's fiscal-year ends (#167) — each annual report's own year
538
- * and the comparative years it restates, the same set
539
- * `compare_companies` aligns on, read from companyfacts only here, where
540
- * the call otherwise fails, and reusing a payload already read. Keyed
541
- * on the framed value's `end`, never its holder's form or quarter: a
542
- * year end SEC framed on a later 10-Q keeps that holder's provenance,
543
- * and a June year end lands on `Q2I`.
544
- */
545
- await readFactsForYearEnds();
546
- const yearEnds = facts ? new Set(filerFiscalYearEndsWithComparatives(facts)) : undefined;
547
- filtered = yearEnds
548
- ? [...byFrameClean.values()].filter((u) => /I$/.test(u.frame) && yearEnds.has(u.end))
549
- : [];
550
- hint = yearEnds
551
- ? 'No value is dated on one of the filer\'s fiscal-year ends — a cover-page figure such as shares outstanding is dated after the year closes. Try period_type: "quarterly" or "all" for every reported date.'
552
- : 'The filer\'s fiscal-year ends could not be read from companyfacts, so its year-end values cannot be picked out — try period_type: "quarterly" or "all" for every reported date.';
554
+ shown = ytdRows;
555
+ shownUnit = newest.unit;
556
+ }
557
+ else {
558
+ if (!newestFramed) {
559
+ const pointer = conceptLineCaveats(undefined, relatedReadings())[0];
560
+ throw ctx.fail('no_frame_data', `'${conceptTag}' exists for this company but has no standard-period data.`, { ...(pointer ? { recovery: { hint: pointer } } : {}), tag: conceptTag });
561
+ }
562
+ // Filter by period type using frame pattern (fp reflects the filing, not the data point)
563
+ let filtered = Array.from(byFrameClean.values()).filter((u) => matchesPeriodType(u.frame, effectivePeriodType));
564
+ // If period_type filter removed everything, check for instant-concept fallback (#48)
565
+ if (filtered.length === 0 && byFrameClean.size > 0) {
566
+ const sample = byFrameClean.values().next().value;
567
+ const hasInstant = sample && /I$/.test(sample.frame);
568
+ /**
569
+ * Post-fetch instant fallback (#48): when `period_type` was NOT explicitly set
570
+ * and the annual filter emptied a non-empty series whose frames are all instant
571
+ * (CY####Q#I), return the full set. The caller asked for the concept's default
572
+ * period — the right answer is the series that actually exists, not an error.
573
+ */
574
+ if (hasInstant && input.period_type === undefined) {
575
+ filtered = Array.from(byFrameClean.values());
576
+ resolvedPeriodType = 'all';
553
577
  }
554
578
  else {
555
- hint =
556
- effectivePeriodType === 'annual'
557
- ? 'No annual data found — try period_type: "quarterly" or "all".'
558
- : 'No quarterly data found — try period_type: "annual" or "all".';
559
- }
560
- if (filtered.length === 0) {
561
- throw ctx.fail('no_period_data', `No ${effectivePeriodType} data for '${conceptTag}'.`, {
562
- recovery: { hint },
563
- tag: conceptTag,
564
- period_type: effectivePeriodType,
565
- });
579
+ let hint;
580
+ if (hasInstant) {
581
+ /**
582
+ * An explicit annual view of an instant concept is its values dated on
583
+ * the filer's fiscal-year ends (#167) — each annual report's own year
584
+ * and the comparative years it restates, the same set
585
+ * `compare_companies` aligns on, read from companyfacts only here, where
586
+ * the call otherwise fails, and reusing a payload already read. Keyed
587
+ * on the framed value's `end`, never its holder's form or quarter: a
588
+ * year end SEC framed on a later 10-Q keeps that holder's provenance,
589
+ * and a June year end lands on `Q2I`.
590
+ */
591
+ await readFactsForYearEnds();
592
+ const yearEnds = facts
593
+ ? new Set(filerFiscalYearEndsWithComparatives(facts))
594
+ : undefined;
595
+ filtered = yearEnds
596
+ ? [...byFrameClean.values()].filter((u) => /I$/.test(u.frame) && yearEnds.has(u.end))
597
+ : [];
598
+ hint = yearEnds
599
+ ? 'No value is dated on one of the filer\'s fiscal-year ends — a cover-page figure such as shares outstanding is dated after the year closes. Try period_type: "quarterly" or "all" for every reported date.'
600
+ : 'The filer\'s fiscal-year ends could not be read from companyfacts, so its year-end values cannot be picked out — try period_type: "quarterly" or "all" for every reported date.';
601
+ }
602
+ else {
603
+ hint =
604
+ effectivePeriodType === 'annual'
605
+ ? 'No annual data found — try period_type: "quarterly" or "all".'
606
+ : 'No quarterly data found — try period_type: "annual" or "all".';
607
+ }
608
+ if (filtered.length === 0) {
609
+ throw ctx.fail('no_period_data', `No ${effectivePeriodType} data for '${conceptTag}'.`, {
610
+ recovery: { hint },
611
+ tag: conceptTag,
612
+ period_type: effectivePeriodType,
613
+ });
614
+ }
566
615
  }
567
616
  }
617
+ // Sort newest first
618
+ filtered.sort((a, b) => b.end.localeCompare(a.end));
619
+ if (yearEndsUnread) {
620
+ untestedYears = filtered
621
+ .filter((u) => isQuarterlyForm(u.form) && matchesPeriodType(u.frame, 'annual'))
622
+ .map((u) => u.frame);
623
+ }
624
+ shown = filtered.map((u) => ({ ...u, period: u.frame }));
625
+ shownUnit = newestFramed.unit;
568
626
  }
569
- // Sort newest first
570
- filtered.sort((a, b) => b.end.localeCompare(a.end));
571
627
  /**
572
628
  * Staleness reads the concept across units, so a convenience translation
573
629
  * the filer stopped publishing is not reported as a series that stopped;
@@ -576,49 +632,83 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
576
632
  */
577
633
  const newestAcrossUnits = [...byUnit.values()]
578
634
  .flatMap((frames) => [...frames.values()])
579
- .reduce((newest, unit) => (unit.end > newest.end ? unit : newest), newestFramed);
580
- const stalenessReference = {
635
+ .reduce((newest, unit) => (!newest || unit.end > newest.end ? unit : newest), newestFramed);
636
+ /**
637
+ * A year-to-date series is the same concept line, so it reads the frames too, but
638
+ * its rows can end after every frame (a 10-Q's nine months close a quarter SEC
639
+ * frames under no period): the newest row shown then measures the line, named by
640
+ * its interval (#284). Off `ytd` this is the frame passed in.
641
+ */
642
+ const throughYtd = (framed) => newestYtd && (!framed || newestYtd.end > framed.end) ? newestYtd : framed;
643
+ const seriesNewest = throughYtd(newestAcrossUnits);
644
+ /**
645
+ * The filer's newest XBRL annual report may be one SEC's XBRL data holds none of the
646
+ * statement facts of (#269). Only a series ending before that report's period, with
647
+ * no value from it, can be missing it, and only companyfacts can say whether the
648
+ * filer's other statements are too: it is read for that alone, reusing a payload in
649
+ * hand and never retrying one that found nothing. Where the caveat fires, that
650
+ * payload's newest period is the staleness reference, so the gap is named once, by
651
+ * its cause, rather than also measured against today.
652
+ */
653
+ let reportGap;
654
+ let stalenessReference = {
581
655
  date: new Date().toISOString().slice(0, 10),
582
656
  kind: 'current-date',
583
657
  };
584
- const conceptStopped = seriesStalenessCaveats(conceptTag, conceptResponse.label, newestAcrossUnits, stalenessReference).length > 0;
585
- const otherUnits = rankedUnits.filter((key) => key !== newestFramed.unit);
658
+ if (report &&
659
+ newestAcrossUnits &&
660
+ newestAcrossUnits.end < report.reportDate &&
661
+ !allUnits.some((unit) => unit.accn === report.accessionNumber)) {
662
+ const payload = facts === undefined ? await reportReads.companyFacts(match.cik) : (facts ?? undefined);
663
+ if (payload) {
664
+ const reported = newestReportedPeriod(payload, input.taxonomy);
665
+ reportGap = annualReportGapCaveat(payload, report, reported);
666
+ if (reportGap)
667
+ stalenessReference = { date: reported, kind: 'reported-period' };
668
+ }
669
+ }
670
+ const conceptStopped = seriesStalenessCaveats(conceptTag, conceptResponse.label, seriesNewest, stalenessReference)
671
+ .length > 0;
672
+ const otherUnits = rankedUnits.filter((key) => key !== shownUnit);
586
673
  const otherUnitSpans = otherUnits
587
- .map((key) => describeUnitFrames(key, byUnit.get(key)?.values() ?? []))
674
+ .map((key) => describeUnitPeriods(key, shownByUnit.get(key) ?? new Map(), ytd ? ' to ' : '–'))
588
675
  .join('; ');
589
- /** The 10-Q-held years shown that a failed companyfacts read may have left untested (#148). */
590
- const untestedYears = yearEndsUnread
591
- ? filtered
592
- .filter((u) => isQuarterlyForm(u.form) && matchesPeriodType(u.frame, 'annual'))
593
- .map((u) => u.frame)
594
- : [];
595
676
  /**
596
677
  * Off-calendar filers lose a whole calendar quarter from the frame-tagged
597
678
  * series — SEC reports fiscal Q4 as the 10-K residual, never as a discrete
598
679
  * quarterly fact — so a caller sees a gap with no way to tell "did not
599
680
  * report" from "frame tagging does not expose it". `fetch_frames` already
600
681
  * flags the same hazard from the period side; this names the specific
601
- * quarter for this filer (#95). Detection reads the resolved frames, so it
682
+ * quarter for this filer (#95). A filer whose interim reports give the later
683
+ * quarters only as year-to-date values keeps one quarter a year, and that
684
+ * caveat points at `ytd` (#284). Detection reads the resolved frames, so it
602
685
  * runs over the full deduped set rather than the period-filtered slice.
603
686
  */
604
687
  const caveats = [
605
- ...(resolvedPeriodType === 'annual' ? [] : missingQuarterCaveats(byFrameClean.keys())),
688
+ ...(reportGap ? [reportGap] : []),
689
+ ...(resolvedPeriodType === 'quarterly' || resolvedPeriodType === 'all'
690
+ ? [
691
+ ...missingQuarterCaveats(byFrameClean.keys()),
692
+ ...singleQuarterCaveats(byFrameClean.keys(), (ytdByUnit.get(shownUnit)?.size ?? 0) > 0),
693
+ ]
694
+ : []),
606
695
  /**
607
696
  * The tag that won the walk can be one SEC retired years ago, which
608
697
  * happens exactly when no current tag reports for this filer; the values
609
698
  * look ordinary and the taxonomy label is the only tell (#98). A current
610
699
  * tag whose series simply stops carries no tell at all, so the gap to
611
700
  * today is the signal — the concept's companyconcept payloads hold no
612
- * filer-wide period to compare against (#102). A related tag the filer
701
+ * filer-wide period to compare against (#102), unless the #269 read above
702
+ * brought one. A related tag the filer
613
703
  * reports past the concept's own newest value is named in their place
614
704
  * (#258).
615
705
  */
616
- ...conceptLineCaveats(newestAcrossUnits, relatedReadings(), conceptStopped
617
- ? seriesStalenessCaveats(conceptTag, conceptResponse.label, newestFramed, stalenessReference)
706
+ ...conceptLineCaveats(seriesNewest, relatedReadings(), conceptStopped
707
+ ? seriesStalenessCaveats(conceptTag, conceptResponse.label, throughYtd(newestFramed), stalenessReference)
618
708
  : []),
619
709
  ...(otherUnits.length > 0
620
710
  ? [
621
- `Also reported in ${otherUnitSpans}. This series holds ${newestFramed.unit} values only — values in different units never share a series; pass unit: "${otherUnits[0]}" to read another.`,
711
+ `Also reported in ${otherUnitSpans}. This series holds ${shownUnit} values only — values in different units never share a series; pass unit: "${otherUnits[0]}" to read another.`,
622
712
  ]
623
713
  : []),
624
714
  ...(untestedYears.length > 0
@@ -627,8 +717,8 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
627
717
  ]
628
718
  : []),
629
719
  ];
630
- const data = filtered.map((u) => ({
631
- period: u.frame,
720
+ const data = shown.map((u) => ({
721
+ period: u.period,
632
722
  value: u.val,
633
723
  start: u.start || undefined,
634
724
  end: u.end,
@@ -642,14 +732,14 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
642
732
  let dataset;
643
733
  const bridge = getCanvasBridge();
644
734
  if (bridge && data.length > 0) {
645
- const rows = filtered.map((u) => ({
735
+ const rows = shown.map((u) => ({
646
736
  cik: match.cik,
647
737
  entity_name: match.name ?? null,
648
738
  concept: conceptTag,
649
739
  tag: u.tag,
650
740
  taxonomy,
651
741
  unit: u.unit,
652
- period: u.frame,
742
+ period: u.period,
653
743
  value: u.val,
654
744
  period_start: u.start || null,
655
745
  period_end: u.end,
@@ -671,7 +761,7 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
671
761
  concept: conceptTag,
672
762
  taxonomy,
673
763
  period_type: resolvedPeriodType,
674
- unit: newestFramed.unit,
764
+ unit: shownUnit,
675
765
  },
676
766
  });
677
767
  if (registered)
@@ -702,7 +792,7 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
702
792
  concept: conceptTag,
703
793
  label: conceptResponse.label || label,
704
794
  description: conceptResponse.description || undefined,
705
- unit: newestFramed.unit,
795
+ unit: shownUnit,
706
796
  data: inlineData,
707
797
  tags_tried: tagsTried.length > 1 ? tagsTried : undefined,
708
798
  dataset,
@@ -735,13 +825,14 @@ export const getFinancialsTool = tool('secedgar_get_financials', {
735
825
  const fy = d.fiscal_year != null ? `FY${d.fiscal_year}` : null;
736
826
  const fp = d.fiscal_period ?? null;
737
827
  const fiscalCtx = [fy, fp].filter(Boolean).join(' ');
738
- const range = d.start ? `${d.start} → ${d.end}` : d.end;
828
+ // A year-to-date row's period is already its start/end interval.
829
+ const range = d.period === `${d.start}/${d.end}` ? '' : ` | ${d.start ? `${d.start} → ${d.end}` : d.end}`;
739
830
  const filingCtx = fiscalCtx
740
831
  ? `${d.form} (${fiscalCtx}) filed ${d.filed} [${d.accession_number}]`
741
832
  : `${d.form} filed ${d.filed} [${d.accession_number}]`;
742
833
  // Rows from the concept tag carry it in the header line above.
743
834
  const tagCtx = d.tag === result.concept ? '' : ` | tag ${d.tag}`;
744
- lines.push(`${d.period}: ${formatted} (raw ${d.value}) | ${range} | ${filingCtx}${tagCtx}`);
835
+ lines.push(`${d.period}: ${formatted} (raw ${d.value})${range} | ${filingCtx}${tagCtx}`);
745
836
  }
746
837
  if (result.dataset) {
747
838
  const sliceNote = result.dataset.row_count > result.data.length