@cyanheads/secedgar-mcp-server 0.20.0 → 0.20.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 (79) hide show
  1. package/AGENTS.md +23 -22
  2. package/CLAUDE.md +23 -22
  3. package/README.md +21 -9
  4. package/changelog/0.20.x/0.20.1.md +39 -0
  5. package/changelog/template.md +10 -8
  6. package/dist/index.js +2 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/mcp-server/tools/definitions/company-search.tool.js +1 -1
  9. package/dist/mcp-server/tools/definitions/company-search.tool.js.map +1 -1
  10. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts.map +1 -1
  11. package/dist/mcp-server/tools/definitions/compare-companies.tool.js +35 -21
  12. package/dist/mcp-server/tools/definitions/compare-companies.tool.js.map +1 -1
  13. package/dist/mcp-server/tools/definitions/dataframe-query.tool.d.ts.map +1 -1
  14. package/dist/mcp-server/tools/definitions/dataframe-query.tool.js +28 -5
  15. package/dist/mcp-server/tools/definitions/dataframe-query.tool.js.map +1 -1
  16. package/dist/mcp-server/tools/definitions/fetch-frames.tool.d.ts.map +1 -1
  17. package/dist/mcp-server/tools/definitions/fetch-frames.tool.js +4 -2
  18. package/dist/mcp-server/tools/definitions/fetch-frames.tool.js.map +1 -1
  19. package/dist/mcp-server/tools/definitions/find-holders.tool.js +3 -3
  20. package/dist/mcp-server/tools/definitions/find-holders.tool.js.map +1 -1
  21. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js +1 -1
  22. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js.map +1 -1
  23. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts +14 -2
  24. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/get-filing.tool.js +220 -86
  26. package/dist/mcp-server/tools/definitions/get-filing.tool.js.map +1 -1
  27. package/dist/mcp-server/tools/definitions/get-financials.tool.d.ts.map +1 -1
  28. package/dist/mcp-server/tools/definitions/get-financials.tool.js +82 -18
  29. package/dist/mcp-server/tools/definitions/get-financials.tool.js.map +1 -1
  30. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.js +3 -3
  31. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.js.map +1 -1
  32. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.d.ts +18 -2
  33. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.d.ts.map +1 -1
  34. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.js +299 -104
  35. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.js.map +1 -1
  36. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.js +5 -5
  37. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.js.map +1 -1
  38. package/dist/mcp-server/tools/definitions/get-material-events.tool.js +1 -1
  39. package/dist/mcp-server/tools/definitions/get-material-events.tool.js.map +1 -1
  40. package/dist/mcp-server/tools/definitions/get-snapshot.tool.d.ts.map +1 -1
  41. package/dist/mcp-server/tools/definitions/get-snapshot.tool.js +24 -22
  42. package/dist/mcp-server/tools/definitions/get-snapshot.tool.js.map +1 -1
  43. package/dist/mcp-server/tools/definitions/index.d.ts +17 -2
  44. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  45. package/dist/mcp-server/tools/definitions/search-concepts.tool.d.ts.map +1 -1
  46. package/dist/mcp-server/tools/definitions/search-concepts.tool.js +16 -11
  47. package/dist/mcp-server/tools/definitions/search-concepts.tool.js.map +1 -1
  48. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts +2 -0
  49. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts.map +1 -1
  50. package/dist/mcp-server/tools/definitions/search-filings.tool.js +88 -40
  51. package/dist/mcp-server/tools/definitions/search-filings.tool.js.map +1 -1
  52. package/dist/services/edgar/call-scope.d.ts +13 -1
  53. package/dist/services/edgar/call-scope.d.ts.map +1 -1
  54. package/dist/services/edgar/call-scope.js +4 -1
  55. package/dist/services/edgar/call-scope.js.map +1 -1
  56. package/dist/services/edgar/concept-map.d.ts.map +1 -1
  57. package/dist/services/edgar/concept-map.js +18 -2
  58. package/dist/services/edgar/concept-map.js.map +1 -1
  59. package/dist/services/edgar/concept-series.d.ts +32 -1
  60. package/dist/services/edgar/concept-series.d.ts.map +1 -1
  61. package/dist/services/edgar/concept-series.js +72 -1
  62. package/dist/services/edgar/concept-series.js.map +1 -1
  63. package/dist/services/edgar/edgar-api-service.d.ts +2 -12
  64. package/dist/services/edgar/edgar-api-service.d.ts.map +1 -1
  65. package/dist/services/edgar/edgar-api-service.js +18 -31
  66. package/dist/services/edgar/edgar-api-service.js.map +1 -1
  67. package/dist/services/edgar/filing-to-text.d.ts +20 -8
  68. package/dist/services/edgar/filing-to-text.d.ts.map +1 -1
  69. package/dist/services/edgar/filing-to-text.js +583 -51
  70. package/dist/services/edgar/filing-to-text.js.map +1 -1
  71. package/dist/services/edgar/fiscal-periods.d.ts +2 -0
  72. package/dist/services/edgar/fiscal-periods.d.ts.map +1 -1
  73. package/dist/services/edgar/fiscal-periods.js +1 -1
  74. package/dist/services/edgar/fiscal-periods.js.map +1 -1
  75. package/dist/services/edgar/types.d.ts +9 -6
  76. package/dist/services/edgar/types.d.ts.map +1 -1
  77. package/package.json +8 -8
  78. package/server.json +3 -3
  79. package/skills/secedgar-guide/SKILL.md +16 -2
@@ -85,8 +85,14 @@ export declare const getFilingTool: import("@cyanheads/mcp-ts-core").ToolDefinit
85
85
  }, {
86
86
  readonly reason: "filing_not_found";
87
87
  readonly code: JsonRpcErrorCode.NotFound;
88
- readonly when: "No filing matches the accession number under any candidate CIK";
88
+ readonly when: "No EDGAR source lists the accession number — no directory tried holds it, full-text search has no record of it, and SEC serves no index page for it — or the lookups that could show it were unavailable";
89
89
  readonly recovery: "Verify the accession number and pass the company CIK explicitly.";
90
+ }, {
91
+ readonly reason: "filing_not_served";
92
+ readonly code: JsonRpcErrorCode.ServiceUnavailable;
93
+ readonly when: "EDGAR shows the filing exists — full-text search lists it, SEC serves its index page, or this server read it earlier — but the SEC archive answered 404 for its directory listing under every CIK tried, an answer SEC caches for several minutes";
94
+ readonly recovery: "Retry the same call in a few minutes — the SEC archive is not serving this existing filing right now, and nothing in the request needs to change.";
95
+ readonly retryable: true;
90
96
  }, {
91
97
  readonly reason: "offset_out_of_range";
92
98
  readonly code: JsonRpcErrorCode.ValidationError;
@@ -210,8 +216,14 @@ export declare function createGetFilingTool(options: LimitClampOptions): import(
210
216
  }, {
211
217
  readonly reason: "filing_not_found";
212
218
  readonly code: JsonRpcErrorCode.NotFound;
213
- readonly when: "No filing matches the accession number under any candidate CIK";
219
+ readonly when: "No EDGAR source lists the accession number — no directory tried holds it, full-text search has no record of it, and SEC serves no index page for it — or the lookups that could show it were unavailable";
214
220
  readonly recovery: "Verify the accession number and pass the company CIK explicitly.";
221
+ }, {
222
+ readonly reason: "filing_not_served";
223
+ readonly code: JsonRpcErrorCode.ServiceUnavailable;
224
+ readonly when: "EDGAR shows the filing exists — full-text search lists it, SEC serves its index page, or this server read it earlier — but the SEC archive answered 404 for its directory listing under every CIK tried, an answer SEC caches for several minutes";
225
+ readonly recovery: "Retry the same call in a few minutes — the SEC archive is not serving this existing filing right now, and nothing in the request needs to change.";
226
+ readonly retryable: true;
215
227
  }, {
216
228
  readonly reason: "offset_out_of_range";
217
229
  readonly code: JsonRpcErrorCode.ValidationError;
@@ -1 +1 @@
1
- {"version":3,"file":"get-filing.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/get-filing.tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAY,MAAM,+BAA+B,CAAC;AAE3E,OAAO,EACL,KAAK,iBAAiB,EAGvB,MAAM,mCAAmC,CAAC;AA4L3C,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6pBxB,CAAC;AAEH,2FAA2F;AAC3F,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAE7D"}
1
+ {"version":3,"file":"get-filing.tool.d.ts","sourceRoot":"","sources":["../../../../src/mcp-server/tools/definitions/get-filing.tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAQ,CAAC,EAAE,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAY,MAAM,+BAA+B,CAAC;AAE3E,OAAO,EACL,KAAK,iBAAiB,EAGvB,MAAM,mCAAmC,CAAC;AA4M3C,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqsBxB,CAAC;AAEH,2FAA2F;AAC3F,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAE7D"}
@@ -9,7 +9,7 @@ import { limitClamp, withLimitClamps, } from '../limit-clamp.js';
9
9
  import { SEC_UPSTREAM_ERRORS } from '../sec-upstream-errors.js';
10
10
  import { CallScope } from '../../../services/edgar/call-scope.js';
11
11
  import { filingArchiveUrl, getEdgarApiService } from '../../../services/edgar/edgar-api-service.js';
12
- import { detectHeadings, filingToExtract, findPhrase, foldForHeadingMatch, getExtractCache, headingKey, isTocHeading, linkedSectionStart, MARKER_TITLE_RE, matchSectionLine, setExtractCache, spaceRunInMarker, windowText, withoutSubItemLabel, } from '../../../services/edgar/filing-to-text.js';
12
+ import { deleteExtractCache, detectHeadings, filingToExtract, findPhrase, foldForHeadingMatch, getExtractCache, headingKey, isTocHeading, linkedSectionStart, MARKER_TITLE_RE, matchSectionLine, setExtractCache, spaceRunInMarker, windowText, withoutSubItemLabel, } from '../../../services/edgar/filing-to-text.js';
13
13
  const MAX_DOCUMENTS_IN_FORMAT = 10;
14
14
  /**
15
15
  * Per-category cap on the catalog rendered into an error message. Distinct from
@@ -67,7 +67,7 @@ const contentLimit = limitClamp({
67
67
  cap: 200_000,
68
68
  bound: 1_000_000,
69
69
  shape: (n) => n.default(50000),
70
- description: 'Maximum characters of document text to return per page. 10-K filings can exceed 500,000 characters; S-1/A can exceed 1,000,000. Default 50,000 captures ~12,000 words (typically business overview, risk factors, and MD&A). Increase to 200,000 for full financial statements, or decrease for quick summaries. Page on with offset; section and find open a page at a heading or a phrase.',
70
+ description: 'Characters of document text per page. Default 50,000 (about 12,000 words); 200,000 fits full financial statements, and a 10-K can pass 500,000. Page on with offset; section and find open a page at a heading or a phrase.',
71
71
  });
72
72
  export const getFilingTool = tool('secedgar_get_filing', {
73
73
  description: "Fetch a specific filing's metadata and document content by accession number. Returns the primary document as readable text. Use offset/next_offset for multi-page access to large filings (10-K, S-1 can exceed 1M chars): pass the next_offset from a truncated response as offset, without section or find, to read the next page. Use section to jump directly to a heading (e.g. 'risk factors', 'item 7') without needing an offset, or find to open the page at a phrase in the text (e.g. 'net revenue retention') and list where it occurs.",
@@ -109,9 +109,16 @@ export const getFilingTool = tool('secedgar_get_filing', {
109
109
  {
110
110
  reason: 'filing_not_found',
111
111
  code: JsonRpcErrorCode.NotFound,
112
- when: 'No filing matches the accession number under any candidate CIK',
112
+ when: 'No EDGAR source lists the accession number — no directory tried holds it, full-text search has no record of it, and SEC serves no index page for it — or the lookups that could show it were unavailable',
113
113
  recovery: 'Verify the accession number and pass the company CIK explicitly.',
114
114
  },
115
+ {
116
+ reason: 'filing_not_served',
117
+ code: JsonRpcErrorCode.ServiceUnavailable,
118
+ when: 'EDGAR shows the filing exists — full-text search lists it, SEC serves its index page, or this server read it earlier — but the SEC archive answered 404 for its directory listing under every CIK tried, an answer SEC caches for several minutes',
119
+ recovery: 'Retry the same call in a few minutes — the SEC archive is not serving this existing filing right now, and nothing in the request needs to change.',
120
+ retryable: true,
121
+ },
115
122
  {
116
123
  reason: 'offset_out_of_range',
117
124
  code: JsonRpcErrorCode.ValidationError,
@@ -141,7 +148,7 @@ export const getFilingTool = tool('secedgar_get_filing', {
141
148
  .string()
142
149
  .regex(/^\d{1,10}$/, 'Expected a CIK of 1-10 digits')
143
150
  .optional()
144
- .describe("Filer CIK, digits only (resolve via secedgar_company_search if you have a ticker or name). Optional but recommended — speeds up archive lookup. If omitted, the filer is looked up from the accession number through EDGAR full-text search (2001 onward) and the accession number's own prefix, which for many filings is a filing agent's CIK, and when none of those directories serves the filing, through the filers its index page names."),
151
+ .describe("Filer CIK, digits only (from secedgar_company_search). Optional but faster. Omitted, the filer is found from the accession number through full-text search (2001 on) and its prefix, often a filing agent's CIK, then through the filers its index page names."),
145
152
  content_limit: contentLimit.schema(true),
146
153
  document: z
147
154
  .string()
@@ -150,7 +157,7 @@ export const getFilingTool = tool('secedgar_get_filing', {
150
157
  include_xbrl: z
151
158
  .boolean()
152
159
  .default(false)
153
- .describe('Include XBRL viewer artifacts and machine-readable taxonomy files (R*.htm fragments, *_cal/_def/_lab/_pre.xml linkbases, *_htm.xml inline instance, *.xsd schemas, MetaLinks.json, FilingSummary.xml, Show.js, report.css, *-xbrl.zip, Financial_Report.xlsx, EX-101.* technical exhibits) under documents.xbrl. Off by default — these dominate filing indexes (~100 entries on a typical 10-K) and are rarely relevant when reading filing content.'),
160
+ .describe('List XBRL viewer artifacts and taxonomy files (R*.htm, linkbase and instance .xml, .xsd, MetaLinks.json, FilingSummary.xml, Show.js, report.css, *-xbrl.zip, Financial_Report.xlsx, EX-101.* exhibits) under documents.xbrl. Off by default: about 100 entries on a typical 10-K, rarely needed to read it.'),
154
161
  offset: z
155
162
  .number()
156
163
  .int()
@@ -161,12 +168,12 @@ export const getFilingTool = tool('secedgar_get_filing', {
161
168
  .string()
162
169
  .min(1)
163
170
  .optional()
164
- .describe("Jump to a named section, matched against every detected heading and the document's own lines (e.g. 'risk factors', 'item 7', 'item 2.02', 'certain relationships'). The first match wins, in this order: a heading equal to the value, or whose title after its Item/Part marker equals it; the first Item or Part heading containing it; a document line equal to it — a subheading the outline omits ('Liquidity and Capital Resources') — unless the line labels a table row; the first other heading containing it; a table-row label equal to it, else a document line starting with it. In a proxy statement (DEF 14A and its variants), whose ITEM headings are ballot proposals, the first heading of any kind containing the value comes before both document-line steps. Within each heading step a body heading wins over a table-of-contents row, which lands only when nothing else at that step matches; a table-of-contents row that links to its section lands on that section. A line landing says so in the notice; table-of-contents rows and wrapped cross-references are never line landings. A leading 20-F sub-item label on a heading or line ('3D.', 'B.') is ignored, so 'risk factors' reaches '3D. RISK FACTORS'; the value itself is matched as given. A value ending in a number matches only that number: 'item 1' reaches Item 1 and Item 1A, never Items 10–16, and 'part i' never reaches Part II. Every step ignores case, whitespace, and quote style, so a heading copied from the outline resolves whether it carries the filing's non-breaking spaces and curly quotes or plain ones; the steps comparing a whole heading or line (equal to, starting with) also ignore the punctuation between an Item or Part marker and its title, so 'Item 1A Risk Factors' reaches 'Item 1A. – Risk Factors'. For a phrase in the text that is not a heading, use find. Takes precedence over find and offset, so leave it out when paging on with next_offset. On a miss, the error message includes the detected outline so you can pick the correct heading."),
171
+ .describe("Jump to a heading or document line (e.g. 'risk factors', 'item 7'), ignoring case, whitespace, and quote style; 'item 1' never reaches Item 10. For a phrase that is not a heading, use find. Outranks find and offset, so leave it out when paging with next_offset."),
165
172
  find: z
166
173
  .string()
167
174
  .max(MAX_FIND_CHARS)
168
175
  .optional()
169
- .describe("Open the page at a phrase in the document's text (e.g. 'net revenue retention') and list where it occurs. Matched as a substring, ignoring case, whitespace runs, and quote style, so a phrase broken across a line matches; no patterns or whole-word matching. The page opens at the first occurrence at or after offset — at its line's start when that is at most 200 characters earlier, else at the first word starting within those 200 — and occurrences lists up to 20 from there with context, occurrences_total counting the whole document. Blank reads as omitted. With find, offset is where the search starts, so leave find out when paging on with next_offset; section takes precedence over find."),
176
+ .describe("Open the page at a phrase (e.g. 'net revenue retention') and list up to 20 occurrences from there. A substring match ignoring case, whitespace runs, and quote style; no patterns. The search starts at offset, so leave find out when paging with next_offset; section outranks it. Blank is omitted."),
170
177
  }),
171
178
  output: z.object({
172
179
  accession_number: z.string().describe('Filing accession number, normalized to dash format.'),
@@ -273,7 +280,8 @@ export const getFilingTool = tool('secedgar_get_filing', {
273
280
  const resolved = await resolveFilingArchive(api, scope, accn, input.cik, document);
274
281
  if (!resolved.ok) {
275
282
  // Each miss below comes after every directory the filer lookups found was
276
- // tried, so the filer's own CIK is the way out an archive miss offers (#203).
283
+ // tried, so the filer's own CIK is the way out an archive miss offers (#203) —
284
+ // except a filing EDGAR shows exists, which only a retry reaches (#256).
277
285
  const lookupNote = resolved.kind !== 'binary_document' && resolved.filerLookupFailed
278
286
  ? `${FILER_LOOKUP_UNAVAILABLE} `
279
287
  : '';
@@ -345,11 +353,30 @@ export const getFilingTool = tool('secedgar_get_filing', {
345
353
  },
346
354
  });
347
355
  }
356
+ if (resolved.kind === 'filing_not_served') {
357
+ const source = resolved.evidence === 'full_text_search'
358
+ ? 'EDGAR full-text search lists it'
359
+ : 'SEC serves its index page';
360
+ const { ciksTried } = resolved;
361
+ throw ctx.fail('filing_not_served', `Filing '${accn}' exists — ${source} — but the SEC archive answered 404 for its directory listing under ${ciksTried.length === 1 ? 'CIK' : 'CIKs'} ${ciksTried.join(', ')}.`, {
362
+ accession_number: accn,
363
+ ciks_tried: ciksTried,
364
+ ...(resolved.filerLookupFailed && {
365
+ recovery: {
366
+ hint: `${lookupNote}${ctx.recoveryFor('filing_not_served').recovery.hint}`,
367
+ },
368
+ }),
369
+ });
370
+ }
348
371
  const cikSuffix = resolved.providedCik
349
372
  ? ` (CIK ${resolved.providedCik.padStart(10, '0')})`
350
373
  : '';
374
+ // A lookup that could have shown the filing exists was unavailable, so a retry
375
+ // can reach what this call could not (#215, #256).
351
376
  const recoveryHint = resolved.providedCik
352
- ? `${lookupNote}Verify the accession number and CIK are correct.`
377
+ ? resolved.filerLookupFailed
378
+ ? `${lookupNote}Verify the accession number and CIK are correct, or retry in a minute.`
379
+ : 'Verify the accession number and CIK are correct.'
353
380
  : resolved.filerLookupFailed
354
381
  ? `${lookupNote}Pass ${FILER_CIK}, or retry in a minute.`
355
382
  : 'Verify the accession number and pass the company CIK explicitly.';
@@ -378,14 +405,15 @@ export const getFilingTool = tool('secedgar_get_filing', {
378
405
  else {
379
406
  // Cache hit — still need metadata. Re-resolve the index under the CIK whose
380
407
  // archive served the cached text (no candidate search, no document body fetch).
381
- // A resolution failure here is a real failure (EDGAR index unavailable or the
382
- // filing gone): fail honestly rather than fabricating placeholder metadata.
408
+ // The cached text shows the filing exists, so an archive that no longer serves
409
+ // its listing there is SEC's to clear, not a missing filing (#256): fail as
410
+ // such rather than fabricating placeholder metadata. The entry goes, so the
411
+ // next call resolves the filing in full and answers what SEC shows then —
412
+ // a filing SEC has since removed fails filing_not_found there.
383
413
  const metaResolved = await resolveFilingMeta(api, scope, accn, cached.cik, document);
384
414
  if (!metaResolved.ok) {
385
- throw ctx.fail('filing_not_found', `Filing '${accn}' could not be resolved.`, {
386
- accession_number: accn,
387
- cik: input.cik,
388
- });
415
+ deleteExtractCache(cacheKey);
416
+ throw ctx.fail('filing_not_served', `Filing '${accn}' exists — this server read it earlier under CIK ${cached.cik} — but the SEC archive is not serving it there now.`, { accession_number: accn, ciks_tried: [cached.cik] });
389
417
  }
390
418
  resolvedCik = cached.cik;
391
419
  index = metaResolved.index;
@@ -441,6 +469,9 @@ export const getFilingTool = tool('secedgar_get_filing', {
441
469
  else if (landing?.source === 'line-over-heading') {
442
470
  lineNotice = `No detected heading equals section '${sectionText}', so this page starts at the first document line that does, ahead of headings that only contain it.`;
443
471
  }
472
+ else if (landing?.source === 'line-over-toc') {
473
+ lineNotice = `No detected heading outside the table of contents matches section '${sectionText}', so this page starts at the first document line that does.`;
474
+ }
444
475
  if (landing === undefined) {
445
476
  // Render the outline into the message itself — clients reliably see only
446
477
  // message + recovery hint, not error data (#70).
@@ -633,7 +664,7 @@ export function createGetFilingTool(options) {
633
664
  return withLimitClamps(getFilingTool, [contentLimit], options);
634
665
  }
635
666
  /**
636
- * A heading or `section` value folded for {@link sectionMatches}: Unicode
667
+ * A heading or `section` value folded for {@link sectionMatchRank}: Unicode
637
668
  * whitespace runs and typographic quotes folded on both operands, so a heading
638
669
  * re-sent from a rendered outline still matches the bytes it came from (#106),
639
670
  * with a space read in where a marker runs straight into its title
@@ -644,41 +675,61 @@ function foldForSectionMatch(value) {
644
675
  return foldForHeadingMatch(spaceRunInMarker(value));
645
676
  }
646
677
  /**
647
- * Whether a folded `section` needle matches a folded heading: a substring match,
648
- * except that a needle ending in a number never continues into a longer one.
649
- * A trailing digit never runs on into another digit — `item 1` matches `Item 1.`
650
- * and `Item 1A`, never `Item 12`. Plain-text outlines keep their TOC rows (they
651
- * are worded differently from the body heading, so dedup leaves them), and a TOC
652
- * row for Item 10–16 precedes the body Item 1, so a bare substring test landed
653
- * `item 1` on the wrong Item (#136). A trailing roman numeral (`part i`, a word
654
- * of `i`, `v`, and `x`) ends at a space, punctuation, or the heading's end, so
655
- * `part i` never matches `PART II`, `PART III`, or `PART IV` — a 10-Q printing
656
- * Part I only in its table of contents otherwise landed `part i` on its body
657
- * `PART II - OTHER INFORMATION`. Every occurrence is checked, not just the first.
658
- * Both operands arrive folded with a run-in marker spaced
659
- * ({@link foldForSectionMatch}), so the numeral of "Part IFinancial Information"
660
- * ends where heading detection ends it (#180).
678
+ * How a folded `section` needle matches a folded heading: 0 for a substring
679
+ * match, 1 for a match only where a needle ending in a digit runs on into a
680
+ * letter, undefined for none. Rank 0 is falsy, so a caller tests for undefined.
681
+ *
682
+ * A needle ending in a number never continues into a longer one. A trailing
683
+ * digit never runs on into another digit — `item 1` matches `Item 1.` and `Item
684
+ * 1A`, never `Item 12`. Plain-text outlines keep their TOC rows (they are worded
685
+ * differently from the body heading, so dedup leaves them), and a TOC row for
686
+ * Item 10–16 precedes the body Item 1, so a bare substring test landed `item 1`
687
+ * on the wrong Item (#136). A trailing roman numeral (`part i`, a word of `i`,
688
+ * `v`, and `x`) ends at a space, punctuation, or the heading's end, so `part i`
689
+ * never matches `PART II`, `PART III`, or `PART IV` — a 10-Q printing Part I only
690
+ * in its table of contents otherwise landed `part i` on its body `PART II -
691
+ * OTHER INFORMATION`.
692
+ *
693
+ * A digit running on into a letter ranks 1, after every match where the number
694
+ * ends: `item 9` takes Item 9 ahead of Items 9A–9C, and `item 7` Item 7 ahead of
695
+ * Item 7A. Intel's 10-K (0000050863-26-000011) prints Item 9 only on a
696
+ * cross-reference index row, and `item 9` landed on its Item 9C row (#257).
697
+ *
698
+ * Every occurrence is checked and the best kept, not just the first ("ITEM 1A
699
+ * AND ITEM 1" ranks 0 for `item 1`). Both operands arrive folded with a run-in
700
+ * marker spaced ({@link foldForSectionMatch}), so the numeral of "Part
701
+ * IFinancial Information" ends where heading detection ends it (#180).
661
702
  */
662
- function sectionMatches(heading, needle) {
663
- const continuation = /\d$/.test(needle)
664
- ? /\d/
703
+ function sectionMatchRank(heading, needle) {
704
+ const end = /\d$/.test(needle)
705
+ ? 'digit'
665
706
  : /(?:^|\s)[ivx]{1,4}$/.test(needle)
666
- ? /[\p{L}\p{N}]/u
707
+ ? 'roman'
667
708
  : undefined;
668
709
  const at = heading.indexOf(needle);
669
710
  if (at === -1)
670
- return false;
671
- if (continuation === undefined || !continuation.test(heading.charAt(at + needle.length))) {
672
- return true;
673
- }
674
- return occursBeforeBoundary(heading, needle, at + 1, continuation);
711
+ return;
712
+ if (end === undefined)
713
+ return 0;
714
+ const first = occurrenceRank(heading.charAt(at + needle.length), end);
715
+ return first === 0 ? 0 : bestOccurrenceRank(heading, needle, at + 1, end, first);
675
716
  }
676
717
  /**
677
- * Whether `needle` occurs in `heading` at or after `from` with no `continuation`
678
- * character after it, over every occurrence in one Knuth–Morris–Pratt pass.
679
- * Reached only after a first occurrence that runs on.
718
+ * The rank of one occurrence of a needle ending in `end`, from the character
719
+ * after it (`next`, empty at the heading's end): 0 where no letter or digit
720
+ * follows, 1 where a digit runs on into a letter, else undefined.
680
721
  */
681
- function occursBeforeBoundary(heading, needle, from, continuation) {
722
+ function occurrenceRank(next, end) {
723
+ if (!/[\p{L}\p{N}]/u.test(next))
724
+ return 0;
725
+ return end === 'digit' && !/\d/.test(next) ? 1 : undefined;
726
+ }
727
+ /**
728
+ * The best rank of `needle` in `heading` over `best` and every occurrence at or
729
+ * after `from`, in one Knuth–Morris–Pratt pass that stops at the first rank-0
730
+ * occurrence. Reached only after a first occurrence that runs on.
731
+ */
732
+ function bestOccurrenceRank(heading, needle, from, end, best) {
682
733
  const fallback = new Int32Array(needle.length);
683
734
  for (let i = 1, k = 0; i < needle.length; i++) {
684
735
  while (k > 0 && needle[i] !== needle[k])
@@ -687,18 +738,32 @@ function occursBeforeBoundary(heading, needle, from, continuation) {
687
738
  k++;
688
739
  fallback[i] = k;
689
740
  }
741
+ let rank = best;
690
742
  for (let i = from, k = 0; i < heading.length; i++) {
691
743
  while (k > 0 && heading[i] !== needle[k])
692
744
  k = fallback[k - 1] ?? 0;
693
745
  if (heading[i] === needle[k])
694
746
  k++;
695
747
  if (k === needle.length) {
696
- if (!continuation.test(heading.charAt(i + 1)))
697
- return true;
748
+ const found = occurrenceRank(heading.charAt(i + 1), end);
749
+ if (found === 0)
750
+ return 0;
751
+ rank ??= found;
698
752
  k = fallback[k - 1] ?? 0;
699
753
  }
700
754
  }
701
- return false;
755
+ return rank;
756
+ }
757
+ /**
758
+ * Whether an Item or Part heading's title — the text after its marker — opens on
759
+ * the keyed value `key`, which ends where no letter or digit follows: "Item 15.
760
+ * Exhibits and Financial Statement Schedules" opens on `exhibits`; "Item 16. Form
761
+ * 10-K Summary" does not open on `summary`, and no title opens on a marker value
762
+ * (`item 6`).
763
+ */
764
+ function titleOpensOn(heading, key) {
765
+ const title = MARKER_TITLE_RE.exec(headingKey(heading.heading))?.[2];
766
+ return title?.startsWith(key) === true && !/[\p{L}\p{N}]/u.test(title.charAt(key.length));
702
767
  }
703
768
  /**
704
769
  * Where `section` lands, over every detected heading (#169) and the document's
@@ -711,18 +776,26 @@ function occursBeforeBoundary(heading, needle, from, continuation) {
711
776
  * II") has no title and is never a candidate here. This tier keeps "risk
712
777
  * factors" on "Item 1A. Risk Factors." when an earlier all-caps heading
713
778
  * merely contains the words.
714
- * 2. The first Item or Part heading that {@link sectionMatches}: a value inside
715
- * an Item title names that Item ("compensation" → "Item 11. Executive
716
- * Compensation"), where a line equal to it is often a table-row label.
779
+ * 2. The first Item or Part heading that contains the value
780
+ * ({@link sectionMatchRank}): a value inside an Item title names that Item
781
+ * ("compensation" → "Item 11. Executive Compensation"), where a line equal to
782
+ * it is often a table-row label. A TOC row here whose title opens on the
783
+ * value ({@link titleOpensOn}) points at a section printed under a line, so
784
+ * it gives way to tiers 3–5 and lands only when no line matches the value
785
+ * (#257): Intel's 10-K (0000050863-26-000011) prints its Items only on a
786
+ * cross-reference index, and its "Item 15. Exhibits and Financial Statement
787
+ * Schedules" row took `exhibits` from the body's "Exhibits" line. A marker
788
+ * value (`item 6`) opens no title, so a TOC row still takes it (#174).
717
789
  * 3. A document line equal to the value ({@link matchSectionLine}) that labels
718
790
  * no table row.
719
- * 4. The first other heading that {@link sectionMatches}. One that merely holds
720
- * the word ("NOTE 3. BUSINESS COMBINATIONS" for "business", "COST OF
721
- * REVENUES" for "revenue") ranks after a line printing the value alone.
791
+ * 4. The first other heading that contains the value. One that merely holds the
792
+ * word ("NOTE 3. BUSINESS COMBINATIONS" for "business", "COST OF REVENUES"
793
+ * for "revenue") ranks after a line printing the value alone.
722
794
  * 5. A document line equal to the value that labels a table row, else one
723
- * starting with the value. A row label ranks after every heading containing
724
- * the value (#184): every line equal to `revenue` in Microsoft's 2004 10-K
725
- * labels a row, and in tier 3 one took the value from its MD&A heading.
795
+ * starting with the value, else a table's column-header row whose first cell
796
+ * equals it (#257). A row label ranks after every heading containing the
797
+ * value (#184): every line equal to `revenue` in Microsoft's 2004 10-K labels
798
+ * a row, and in tier 3 one took the value from its MD&A heading.
726
799
  *
727
800
  * Inside each heading tier, a heading on a table-of-contents row
728
801
  * ({@link isTocHeading}) ranks after every body heading of the tier, and lands
@@ -734,9 +807,12 @@ function occursBeforeBoundary(heading, needle, from, continuation) {
734
807
  * line. They are not pushed behind the line tiers: a body heading over a page
735
808
  * number reads as a TOC row too, and behind the line tiers CCC's `item 6` left
736
809
  * its body "Item 6. Reserved." for a bare TOC marker line. The line tiers skip
737
- * TOC rows already.
810
+ * TOC rows already. In tiers 2 and 4 the match rank goes first: a value's number
811
+ * ending (`item 9` in "Item 9.") ahead of one running on into a letter ("Item
812
+ * 9A"), so the order is exact body, exact TOC, letter body, letter TOC.
738
813
  *
739
- * The line tiers share one pass over the text, run only when tiers 1 and 2 miss.
814
+ * The line tiers share one pass over the text, run only when tiers 1 and 2 miss
815
+ * or tier 2's match is a TOC row that gives way.
740
816
  *
741
817
  * A proxy statement (`proxy`) keeps tier 1, then every heading containing the
742
818
  * value, then the line tiers: its ITEM headings are ballot proposals, not the
@@ -747,25 +823,25 @@ function occursBeforeBoundary(heading, needle, from, continuation) {
747
823
  */
748
824
  function resolveSection(text, headings, section, proxy) {
749
825
  /**
750
- * The earliest heading of the best rank `rank` gives (0, then 1; undefined is
751
- * no match), every body heading ahead of every TOC row.
826
+ * The earliest heading in the lowest slot: `rank` gives each heading's match
827
+ * rank (0, then 1; undefined is no match), and `slot` places a match by its
828
+ * rank and whether it sits on a TOC row — read for matches only.
752
829
  */
753
- const best = (rank) => {
830
+ const best = (rank, slot) => {
754
831
  const earliest = [];
755
832
  for (const h of headings) {
756
833
  const r = rank(h);
757
834
  if (r === undefined)
758
835
  continue;
759
- const slot = r + (isTocHeading(text, h) ? 2 : 0);
760
- if (slot === 0)
836
+ const s = slot(r, isTocHeading(text, h) ? 1 : 0);
837
+ if (s === 0)
761
838
  return h;
762
- earliest[slot] ??= h;
839
+ earliest[s] ??= h;
763
840
  }
764
841
  return earliest.find((h) => h !== undefined);
765
842
  };
766
- /** The first heading `matches` accepts, a body heading ahead of every TOC row. */
767
- const first = (matches) => best((h) => (matches(h) ? 0 : undefined));
768
843
  const exactNeedle = headingKey(section);
844
+ // Tier 1: every body heading ahead of every TOC row, then the equal ahead of the labelled.
769
845
  const exact = best((h) => {
770
846
  const key = headingKey(h.heading);
771
847
  const title = MARKER_TITLE_RE.exec(key)?.[2];
@@ -775,7 +851,7 @@ function resolveSection(text, headings, section, proxy) {
775
851
  return 0;
776
852
  const labelled = [key, title].some((k) => k !== undefined && withoutSubItemLabel(k) === exactNeedle);
777
853
  return labelled ? 1 : undefined;
778
- });
854
+ }, (r, toc) => r + 2 * toc);
779
855
  const onHeading = (heading) => ({
780
856
  heading,
781
857
  offset: heading.offset,
@@ -784,26 +860,32 @@ function resolveSection(text, headings, section, proxy) {
784
860
  if (exact)
785
861
  return onHeading(exact);
786
862
  const needle = foldForSectionMatch(section);
787
- const contains = (h) => sectionMatches(foldForSectionMatch(h.heading), needle);
863
+ /** The first heading `keep` accepts that contains the value, ranked as tiers 2 and 4 rank. */
864
+ const firstContaining = (keep) => best((h) => (keep(h) ? sectionMatchRank(foldForSectionMatch(h.heading), needle) : undefined), (r, toc) => 2 * r + toc);
788
865
  if (proxy) {
789
- const heading = first(contains);
866
+ const heading = firstContaining(() => true);
790
867
  if (heading)
791
868
  return onHeading(heading);
792
869
  const line = matchSectionLine(text, section);
793
870
  return line ? { offset: line.offset, source: 'line' } : undefined;
794
871
  }
795
- const itemOrPart = first((h) => isStructuralHeading(h) && contains(h));
796
- if (itemOrPart)
872
+ const itemOrPart = firstContaining(isStructuralHeading);
873
+ const pointer = itemOrPart !== undefined &&
874
+ titleOpensOn(itemOrPart, exactNeedle) &&
875
+ isTocHeading(text, itemOrPart);
876
+ if (itemOrPart && !pointer)
797
877
  return onHeading(itemOrPart);
798
878
  const line = matchSectionLine(text, section);
799
- // Tier 2 missed, so any heading containing the value is a non-Item one.
800
- const other = first(contains);
879
+ if (itemOrPart && !line)
880
+ return onHeading(itemOrPart);
881
+ const other = firstContaining((h) => !isStructuralHeading(h));
882
+ const lineSource = itemOrPart ? 'line-over-toc' : 'line';
801
883
  if (line?.equal)
802
- return { offset: line.offset, source: other ? 'line-over-heading' : 'line' };
884
+ return { offset: line.offset, source: other ? 'line-over-heading' : lineSource };
803
885
  if (other)
804
886
  return onHeading(other);
805
887
  if (line)
806
- return { offset: line.offset, source: 'line' };
888
+ return { offset: line.offset, source: lineSource };
807
889
  return;
808
890
  }
809
891
  /** Whether the character at `at` is whitespace as `\s` reads it; false past either end. */
@@ -1000,17 +1082,18 @@ function normalizeAccessionNumber(input) {
1000
1082
  return `${input.slice(0, 10)}-${input.slice(10, 12)}-${input.slice(12)}`;
1001
1083
  }
1002
1084
  /**
1003
- * At most this many parties the filing's index page names are tried past the
1004
- * candidate CIKs (#203). A filing lives under every party's directory, so the
1005
- * first untried one almost always serves it; a group filing can name dozens.
1085
+ * At most this many filers are tried past the candidate CIKs: the parties the
1086
+ * filing's index page names (#203), or, with `cik`, the filers full-text search
1087
+ * records (#256). A filing lives under every party's directory, so the first
1088
+ * untried one almost always serves it; a group filing can name dozens.
1006
1089
  */
1007
- const INDEX_PAGE_PARTY_CAP = 3;
1090
+ const FALLBACK_FILER_CAP = 3;
1008
1091
  /**
1009
1092
  * Resolve filing archive: fetch index + primary document HTML.
1010
1093
  * Used on cache misses to get both the document content and index metadata.
1011
1094
  *
1012
1095
  * When no candidate directory serves the filing, the filing's index page names its
1013
- * parties, and up to {@link INDEX_PAGE_PARTY_CAP} of them not yet tried are
1096
+ * parties, and up to {@link FALLBACK_FILER_CAP} of them not yet tried are
1014
1097
  * searched the same way (#203). A pre-2001 accession filed through an agent needs
1015
1098
  * it: full-text search has no record before 2001, and the agent's directory, the
1016
1099
  * only other candidate, holds no copy the archive serves. The page costs one
@@ -1018,10 +1101,21 @@ const INDEX_PAGE_PARTY_CAP = 3;
1018
1101
  * listing named the target but the archive did not serve it, or no directory
1019
1102
  * answered at all — a document no listing names is missing from every party's
1020
1103
  * directory alike.
1104
+ *
1105
+ * SEC's archive also answers 404 for an existing filing's listing at times, and
1106
+ * caches that answer for minutes, longer than the call's failure budget, so a
1107
+ * filing no directory serves is told apart from one that does not exist by what
1108
+ * shows EDGAR holds it (#256): the full-text search hit already in hand, or the
1109
+ * index page answering.
1110
+ * With `cik`, which skips the search, one full-text search is sent when neither the
1111
+ * directories nor the page answered, and the filers it names are tried like the
1112
+ * page's parties. A filing shown to exist fails `filing_not_served`; the success
1113
+ * path sends no request for any of this.
1021
1114
  */
1022
1115
  async function resolveFilingArchive(api, scope, accessionNumber, providedCik, requestedDocument) {
1023
1116
  const candidates = await resolveCandidateCiks(api, scope, accessionNumber, providedCik);
1024
1117
  let filerLookupFailed = candidates.filerLookupFailed;
1118
+ let evidence = candidates.listed ? 'full_text_search' : undefined;
1025
1119
  const search = {
1026
1120
  tried: new Set(),
1027
1121
  requestedNotServed: false,
@@ -1033,9 +1127,18 @@ async function resolveFilingArchive(api, scope, accessionNumber, providedCik, re
1033
1127
  if (!search.lastIndexed?.items.length || search.requestedNotServed || search.primaryNotServed) {
1034
1128
  const parties = await readFilingParties(api, scope, accessionNumber);
1035
1129
  filerLookupFailed ||= parties === undefined;
1036
- const untried = (parties ?? [])
1037
- .filter((cik) => !search.tried.has(cik))
1038
- .slice(0, INDEX_PAGE_PARTY_CAP);
1130
+ // The page answering at all shows the filing exists, whatever parties it names.
1131
+ if (parties)
1132
+ evidence ??= 'index_page';
1133
+ let others = parties ?? [];
1134
+ if (providedCik && !parties && !search.lastIndexed) {
1135
+ const listed = await lookUpFilingCiks(api, scope, accessionNumber);
1136
+ filerLookupFailed ||= listed === undefined;
1137
+ if (listed?.length)
1138
+ evidence ??= 'full_text_search';
1139
+ others = listed ?? [];
1140
+ }
1141
+ const untried = others.filter((cik) => !search.tried.has(cik)).slice(0, FALLBACK_FILER_CAP);
1039
1142
  if (untried.length > 0) {
1040
1143
  const refound = await searchArchive(api, scope, accessionNumber, untried, requestedDocument, search);
1041
1144
  if (refound)
@@ -1044,6 +1147,16 @@ async function resolveFilingArchive(api, scope, accessionNumber, providedCik, re
1044
1147
  }
1045
1148
  const { lastIndexed } = search;
1046
1149
  if (!lastIndexed?.items.length) {
1150
+ // Every directory tried answered 404 for the listing, while a source shows the filing.
1151
+ if (evidence && !lastIndexed) {
1152
+ return {
1153
+ ok: false,
1154
+ kind: 'filing_not_served',
1155
+ ciksTried: [...search.tried],
1156
+ evidence,
1157
+ filerLookupFailed,
1158
+ };
1159
+ }
1047
1160
  return { ok: false, kind: 'filing_not_found', providedCik, filerLookupFailed };
1048
1161
  }
1049
1162
  // Categorize as the success path does: the same primary, the header page's types.
@@ -1203,17 +1316,38 @@ async function readFilingRecords(api, scope, cik, accessionNumber) {
1203
1316
  * the CIK the accession number opens with — the filer's own, or a filing agent's.
1204
1317
  * When SEC cannot answer the search (#215), the prefix alone is searched and
1205
1318
  * `filerLookupFailed` says so; the caller's cancellation and a rate-limit refusal
1206
- * still end the call.
1319
+ * still end the call. `listed` says the search found the accession, which shows
1320
+ * EDGAR holds the filing (#256).
1207
1321
  */
1208
1322
  async function resolveCandidateCiks(api, scope, accessionNumber, providedCik) {
1209
- if (providedCik)
1210
- return { ciks: [providedCik.padStart(10, '0')], filerLookupFailed: false };
1211
- const searched = await unlessSecUnavailable(scope, () => api.findFilingCiks(accessionNumber, scope));
1323
+ if (providedCik) {
1324
+ return { ciks: [providedCik.padStart(10, '0')], filerLookupFailed: false, listed: false };
1325
+ }
1326
+ const searched = await lookUpFilingCiks(api, scope, accessionNumber);
1212
1327
  return {
1213
1328
  ciks: [...new Set([...(searched ?? []), accessionPrefixCik(accessionNumber)])],
1214
1329
  filerLookupFailed: searched === undefined,
1330
+ listed: Boolean(searched?.length),
1215
1331
  };
1216
1332
  }
1333
+ /**
1334
+ * The filers EDGAR full-text search records for the accession, in SEC's order, or
1335
+ * `undefined` when SEC could not answer the search: unavailable as
1336
+ * {@link unlessSecUnavailable} reads it, or the search endpoint answering 404, which
1337
+ * it never does for a search it ran — one matching nothing answers 200 (#256).
1338
+ */
1339
+ function lookUpFilingCiks(api, scope, accessionNumber) {
1340
+ return unlessSecUnavailable(scope, async () => {
1341
+ try {
1342
+ return await api.findFilingCiks(accessionNumber, scope);
1343
+ }
1344
+ catch (error) {
1345
+ if (error instanceof McpError && error.code === JsonRpcErrorCode.NotFound)
1346
+ return;
1347
+ throw error;
1348
+ }
1349
+ });
1350
+ }
1217
1351
  /**
1218
1352
  * The parties the filing's index page names, read under the accession number's
1219
1353
  * own prefix CIK: SEC serves the page there for any filing that exists, a filing