@cyanheads/secedgar-mcp-server 0.15.15 → 0.16.0

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 +14 -9
  2. package/CLAUDE.md +14 -9
  3. package/README.md +17 -15
  4. package/changelog/0.16.x/0.16.0.md +34 -0
  5. package/dist/config/server-config.d.ts +14 -0
  6. package/dist/config/server-config.d.ts.map +1 -1
  7. package/dist/config/server-config.js +38 -13
  8. package/dist/config/server-config.js.map +1 -1
  9. package/dist/index.js +16 -8
  10. package/dist/index.js.map +1 -1
  11. package/dist/mcp-server/tools/definitions/company-search.tool.d.ts +66 -0
  12. package/dist/mcp-server/tools/definitions/company-search.tool.d.ts.map +1 -1
  13. package/dist/mcp-server/tools/definitions/company-search.tool.js +24 -13
  14. package/dist/mcp-server/tools/definitions/company-search.tool.js.map +1 -1
  15. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts +104 -0
  16. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts.map +1 -1
  17. package/dist/mcp-server/tools/definitions/compare-companies.tool.js +21 -11
  18. package/dist/mcp-server/tools/definitions/compare-companies.tool.js.map +1 -1
  19. package/dist/mcp-server/tools/definitions/dataframe-query.tool.d.ts +87 -2
  20. package/dist/mcp-server/tools/definitions/dataframe-query.tool.d.ts.map +1 -1
  21. package/dist/mcp-server/tools/definitions/dataframe-query.tool.js +41 -25
  22. package/dist/mcp-server/tools/definitions/dataframe-query.tool.js.map +1 -1
  23. package/dist/mcp-server/tools/definitions/fetch-frames.tool.d.ts +92 -0
  24. package/dist/mcp-server/tools/definitions/fetch-frames.tool.d.ts.map +1 -1
  25. package/dist/mcp-server/tools/definitions/fetch-frames.tool.js +20 -4
  26. package/dist/mcp-server/tools/definitions/fetch-frames.tool.js.map +1 -1
  27. package/dist/mcp-server/tools/definitions/find-holders.tool.d.ts +67 -0
  28. package/dist/mcp-server/tools/definitions/find-holders.tool.d.ts.map +1 -1
  29. package/dist/mcp-server/tools/definitions/find-holders.tool.js +35 -15
  30. package/dist/mcp-server/tools/definitions/find-holders.tool.js.map +1 -1
  31. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.d.ts +106 -0
  32. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.d.ts.map +1 -1
  33. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js +22 -12
  34. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js.map +1 -1
  35. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts +108 -0
  36. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts.map +1 -1
  37. package/dist/mcp-server/tools/definitions/get-filing.tool.js +19 -9
  38. package/dist/mcp-server/tools/definitions/get-filing.tool.js.map +1 -1
  39. package/dist/mcp-server/tools/definitions/get-financials.tool.js +1 -1
  40. package/dist/mcp-server/tools/definitions/get-financials.tool.js.map +1 -1
  41. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.d.ts +91 -0
  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 +20 -10
  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 +79 -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 +31 -13
  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 +134 -1
  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 +284 -85
  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 +70 -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 +27 -15
  56. package/dist/mcp-server/tools/definitions/get-material-events.tool.js.map +1 -1
  57. package/dist/mcp-server/tools/definitions/index.d.ts +24 -4
  58. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  59. package/dist/mcp-server/tools/definitions/index.js +24 -24
  60. package/dist/mcp-server/tools/definitions/index.js.map +1 -1
  61. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts +101 -0
  62. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts.map +1 -1
  63. package/dist/mcp-server/tools/definitions/search-filings.tool.js +48 -29
  64. package/dist/mcp-server/tools/definitions/search-filings.tool.js.map +1 -1
  65. package/dist/mcp-server/tools/form-filter.d.ts +13 -0
  66. package/dist/mcp-server/tools/form-filter.d.ts.map +1 -0
  67. package/dist/mcp-server/tools/form-filter.js +16 -0
  68. package/dist/mcp-server/tools/form-filter.js.map +1 -0
  69. package/dist/mcp-server/tools/limit-clamp.d.ts +65 -0
  70. package/dist/mcp-server/tools/limit-clamp.d.ts.map +1 -0
  71. package/dist/mcp-server/tools/limit-clamp.js +78 -0
  72. package/dist/mcp-server/tools/limit-clamp.js.map +1 -0
  73. package/dist/services/edgar/edgar-api-service.d.ts +18 -8
  74. package/dist/services/edgar/edgar-api-service.d.ts.map +1 -1
  75. package/dist/services/edgar/edgar-api-service.js +149 -32
  76. package/dist/services/edgar/edgar-api-service.js.map +1 -1
  77. package/dist/services/edgar/types.d.ts +3 -3
  78. package/package.json +6 -5
  79. package/server.json +3 -3
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * @fileoverview Fetch 13F-HR quarterly institutional holdings by parsing the SEC EDGAR
3
- * information table XML. Institution lookup only — `company` is the 13F filer.
3
+ * information table XML, composed with the quarter's 13F-HR/A amendments (#198).
4
+ * Institution lookup only — `company` is the 13F filer.
4
5
  * The reverse direction (which institutions hold an issuer) is secedgar_find_holders,
5
6
  * which searches the information tables by CUSIP and returns filer CIKs to feed back
6
7
  * into this tool (#81).
@@ -8,10 +9,11 @@
8
9
  */
9
10
  import { tool, z } from '@cyanheads/mcp-ts-core';
10
11
  import { JsonRpcErrorCode, McpError, validationError } from '@cyanheads/mcp-ts-core/errors';
12
+ import { limitClamp, withLimitClamps, } from '../limit-clamp.js';
11
13
  import { dataframeGuidance, getCanvasBridge, toDatasetField, } from '../../../services/canvas-bridge/canvas-bridge.js';
12
14
  import { CallScope } from '../../../services/edgar/call-scope.js';
13
15
  import { getEdgarApiService } from '../../../services/edgar/edgar-api-service.js';
14
- import { parseInfoTableXml, parseThirteenFCoverPage } from '../../../services/edgar/ownership-parser.js';
16
+ import { parseInfoTableXml, parseThirteenFCoverPage, } from '../../../services/edgar/ownership-parser.js';
15
17
  import { ARCHIVE_PAGE_SCAN_CAP, SubmissionsArchiveWalk, } from '../../../services/edgar/submissions-archive.js';
16
18
  /**
17
19
  * Map a quarter string like "2025-Q4" to its calendar quarter-end date (YYYY-MM-DD) — the
@@ -37,8 +39,9 @@ function addMaybe(a, b) {
37
39
  /**
38
40
  * Collapse info-table sub-lines into distinct positions, keyed by (CUSIP ?? issuer, class,
39
41
  * put/call). Sums market value and shares; drops `investment_discretion` — a per-sub-line
40
- * attribute with no meaning once managers/accounts are rolled up. Sorted by value descending,
41
- * so a small `limit` returns the largest distinct holdings.
42
+ * attribute with no meaning once managers/accounts are rolled up — and unions the source
43
+ * accessions, so a position merged across an original and its amendment names both. Sorted
44
+ * by value descending, so a small `limit` returns the largest distinct holdings.
42
45
  */
43
46
  function consolidatePositions(rows) {
44
47
  const byPosition = new Map();
@@ -48,9 +51,18 @@ function consolidatePositions(rows) {
48
51
  if (existing) {
49
52
  existing.market_value_usd = addMaybe(existing.market_value_usd, r.market_value_usd);
50
53
  existing.shares_or_principal_amount = addMaybe(existing.shares_or_principal_amount, r.shares_or_principal_amount);
54
+ for (const accession of r.source_accession_numbers) {
55
+ if (!existing.source_accession_numbers.includes(accession)) {
56
+ existing.source_accession_numbers.push(accession);
57
+ }
58
+ }
51
59
  }
52
60
  else {
53
- byPosition.set(key, { ...r, investment_discretion: undefined });
61
+ byPosition.set(key, {
62
+ ...r,
63
+ investment_discretion: undefined,
64
+ source_accession_numbers: [...r.source_accession_numbers],
65
+ });
54
66
  }
55
67
  }
56
68
  return [...byPosition.values()].sort((a, b) => (b.market_value_usd ?? 0) - (a.market_value_usd ?? 0));
@@ -78,6 +90,131 @@ function findInfoTableDocument(items) {
78
90
  return (candidates.find((it) => /informationtable|infotable|form13f/i.test(it.name))?.name ??
79
91
  candidates[0]?.name);
80
92
  }
93
+ /**
94
+ * Read a 13F filing's information table: the index, the table document it names, and the
95
+ * parse. Two requests. SEC failures other than a 404 throw from the service.
96
+ */
97
+ async function readInfoTable(api, cik, accession, scope) {
98
+ const index = await api.tryGetFilingIndex(cik, accession, scope);
99
+ if (!index)
100
+ return { kind: 'no_index' };
101
+ const document = findInfoTableDocument(index.directory.item);
102
+ if (!document)
103
+ return { kind: 'no_document', documents: index.directory.item.map((i) => i.name) };
104
+ const xml = await api.tryGetFilingDocument(cik, accession, document, scope);
105
+ if (!xml)
106
+ return { kind: 'no_table', document };
107
+ try {
108
+ return { kind: 'ok', holdings: parseInfoTableXml(xml).holdings };
109
+ }
110
+ catch {
111
+ return { kind: 'unparseable' };
112
+ }
113
+ }
114
+ /**
115
+ * Normalize one accession's parsed rows to whole USD and tag them with their source. SEC's
116
+ * 2022 Form 13F amendments (effective 2023-01-03) switched Information Table Column 4 from
117
+ * thousands of dollars to whole dollars, and an amendment filed after that date reports whole
118
+ * dollars even for a pre-2023 quarter, so the unit follows each accession's own filing date —
119
+ * the literal compliance boundary, and always present (unlike the cover-page period).
120
+ */
121
+ function toHoldingRows(holdings, accession, filingDate) {
122
+ const scale = filingDate < '2023-01-03' ? 1000 : 1;
123
+ return holdings.map((h) => ({
124
+ issuer_name: h.issuer_name,
125
+ title_of_class: h.title_of_class,
126
+ cusip: h.cusip,
127
+ market_value_usd: h.value_reported === undefined ? undefined : h.value_reported * scale,
128
+ shares_or_principal_amount: h.shares_or_principal_amount,
129
+ shares_or_principal_type: h.shares_or_principal_type,
130
+ put_call: h.put_call,
131
+ investment_discretion: h.investment_discretion,
132
+ source_accession_numbers: [accession],
133
+ }));
134
+ }
135
+ /**
136
+ * Identity of a raw row for the NEW HOLDINGS containment test. Value is left out: its unit
137
+ * changed at 2023-01-03, so a resubmitted row filed across that date differs only in scale.
138
+ */
139
+ const rowIdentity = (r) => `${r.cusip ?? r.issuer_name}|${r.title_of_class ?? ''}|${r.put_call ?? ''}|${r.investment_discretion ?? ''}|${r.shares_or_principal_amount ?? ''}|${r.shares_or_principal_type ?? ''}`;
140
+ /**
141
+ * True when `table` repeats every row of `composed`, counting duplicates. A NEW HOLDINGS
142
+ * amendment should list only the added securities, but some filers resubmit the whole table
143
+ * under that type (First Eagle's 2026-Q2 amendment repeats all 614 original rows plus 2);
144
+ * appending it would double the portfolio, so it is applied as the restatement it is.
145
+ */
146
+ function repeatsEveryRow(table, composed) {
147
+ if (composed.length === 0)
148
+ return false;
149
+ const counts = new Map();
150
+ for (const r of table)
151
+ counts.set(rowIdentity(r), (counts.get(rowIdentity(r)) ?? 0) + 1);
152
+ for (const r of composed) {
153
+ const left = counts.get(rowIdentity(r)) ?? 0;
154
+ if (left === 0)
155
+ return false;
156
+ counts.set(rowIdentity(r), left - 1);
157
+ }
158
+ return true;
159
+ }
160
+ /**
161
+ * Compose a quarter's holdings from its original 13F-HR and same-period amendments, in
162
+ * acceptance order. A RESTATEMENT replaces everything composed before it (earlier NEW
163
+ * HOLDINGS included), and the original counts as one: the base is the last restatement whose
164
+ * table reads, walking back to the original, and nothing before it is read (`superseded`).
165
+ * Each NEW HOLDINGS after the base is read and appended — or applied as a restatement when
166
+ * its table repeats every composed row. An amendment whose type or table cannot be read is
167
+ * `not_applied`; `readTable` returns undefined for it.
168
+ */
169
+ async function composeHoldings(steps, originalRows, readTable) {
170
+ let base = 0;
171
+ let rows = originalRows;
172
+ for (let i = steps.length - 1; i >= 0; i--) {
173
+ const step = steps[i];
174
+ if (step.kind === 'original') {
175
+ base = i;
176
+ break;
177
+ }
178
+ if (step.kind !== 'RESTATEMENT')
179
+ continue;
180
+ const table = await readTable(step);
181
+ if (table) {
182
+ base = i;
183
+ rows = table;
184
+ step.status = 'restatement';
185
+ break;
186
+ }
187
+ step.status = 'not_applied';
188
+ }
189
+ for (const step of steps.slice(0, base))
190
+ if (!step.kind)
191
+ step.status = 'not_applied';
192
+ let applied = [steps[base]];
193
+ for (const step of steps.slice(base + 1)) {
194
+ // A restatement past the base was tried in the backward pass and did not read.
195
+ if (step.kind !== 'NEW HOLDINGS') {
196
+ step.status = 'not_applied';
197
+ continue;
198
+ }
199
+ const table = await readTable(step);
200
+ if (!table)
201
+ step.status = 'not_applied';
202
+ else if (repeatsEveryRow(table, rows)) {
203
+ for (const earlier of applied)
204
+ if (earlier.kind !== 'original')
205
+ earlier.status = 'superseded';
206
+ applied = [step];
207
+ rows = table;
208
+ step.status = 'restatement';
209
+ }
210
+ else {
211
+ applied.push(step);
212
+ rows = [...rows, ...table];
213
+ step.status = 'new_holdings';
214
+ }
215
+ }
216
+ return { accessions: applied.map((s) => s.accession), rows };
217
+ }
81
218
  /**
82
219
  * Periodic-report forms that mark an operating company (not an institutional manager).
83
220
  * A filer with any of these and no 13F-HR is misrouted here — the caller wants
@@ -87,6 +224,17 @@ const OPERATING_COMPANY_FORMS = ['10-K', '10-K/A', '10-Q', '10-Q/A', '8-K', '8-K
87
224
  /** The holdings report, and the notice a manager files instead when others report its holdings. */
88
225
  const HOLDINGS_REPORT_FORM = '13F-HR';
89
226
  const NOTICE_FORMS = new Set(['13F-NT', '13F-NT/A']);
227
+ /**
228
+ * Composition order: acceptance time, which separates two amendments filed the same day
229
+ * (Advisors Asset Management's 2020-Q2 restatement and new-holdings amendment, 2026-08-27,
230
+ * a minute apart), then filing date when a block lacks it, then accession. `amendmentNo`
231
+ * is not a key — filers skip numbers.
232
+ */
233
+ function compositionOrder(a, b) {
234
+ return ((a.acceptanceDateTime || a.filingDate).localeCompare(b.acceptanceDateTime || b.filingDate) ||
235
+ a.filingDate.localeCompare(b.filingDate) ||
236
+ a.accessionNumber.localeCompare(b.accessionNumber));
237
+ }
90
238
  /**
91
239
  * Zip a submissions block (the recent window or an archive page) into its 13F-HR,
92
240
  * 13F-HR/A and 13F-NT notice rows, newest filed first. Read off the submissions fetch the
@@ -100,6 +248,7 @@ function thirteenFRows(block) {
100
248
  if (form !== HOLDINGS_REPORT_FORM && form !== '13F-HR/A' && !NOTICE_FORMS.has(form))
101
249
  continue;
102
250
  out.push({
251
+ acceptanceDateTime: block.acceptanceDateTime?.[i] ?? '',
103
252
  accessionNumber: block.accessionNumber[i] ?? '',
104
253
  filingDate: block.filingDate[i] ?? '',
105
254
  form,
@@ -128,15 +277,18 @@ function optionalLookupFailure(err) {
128
277
  ].includes(err.code));
129
278
  }
130
279
  const amendmentIdentity = z.object({
131
- accession_number: z.string().describe('Amendment accession for secedgar_get_filing.'),
132
- filing_date: z.string().describe('Amendment filing date (YYYY-MM-DD).'),
280
+ accession_number: z.string().describe('Accession for secedgar_get_filing.'),
281
+ filing_date: z.string().describe('Filing date (YYYY-MM-DD).'),
282
+ applied_as: z
283
+ .enum(['restatement', 'new_holdings', 'superseded', 'not_applied'])
284
+ .describe('Composition role.'),
133
285
  });
134
286
  const amendmentSchema = z.discriminatedUnion('amendment_type', [
135
287
  amendmentIdentity
136
288
  .extend({
137
289
  amendment_type: z.enum(['RESTATEMENT', 'NEW HOLDINGS']).describe('Cover-page type.'),
138
290
  })
139
- .describe('Readable amendment.'),
291
+ .describe('Typed amendment.'),
140
292
  amendmentIdentity
141
293
  .extend({
142
294
  amendment_type: z.literal('UNAVAILABLE').describe('Type could not be read.'),
@@ -144,11 +296,21 @@ const amendmentSchema = z.discriminatedUnion('amendment_type', [
144
296
  .enum(['missing_header', 'unreadable_header', 'lookup_failed', 'lookup_stopped'])
145
297
  .describe('Why the type is unavailable; inspect with secedgar_get_filing.'),
146
298
  })
147
- .describe('Amendment with unavailable type.'),
299
+ .describe('Untyped amendment.'),
148
300
  ]);
301
+ /** `limit`: a page holds at most 500 holdings rows (#197). */
302
+ const holdingsLimit = limitClamp({
303
+ tool: 'secedgar_get_institutional_holdings',
304
+ field: 'limit',
305
+ min: 1,
306
+ cap: 500,
307
+ bound: 1000,
308
+ shape: (n) => n.default(20),
309
+ description: 'Maximum number of holdings rows to return. 13F filings from large institutions can contain thousands of positions. Default 20.',
310
+ });
149
311
  export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_holdings', {
150
312
  title: 'Get Institutional Holdings',
151
- description: 'Read an institutional manager\'s original 13F-HR information table. company is the filer: a 10-digit CIK, ticker, or name; names outside the ticker file use EDGAR entity search, and ambiguous names return candidates. For managers holding an issuer, use secedgar_find_holders and pass its filer_cik here. Positions carry issuer, CUSIP, shares, whole-USD market value, and option designation. Same-period amendments are disclosed separately, never merged; read them with secedgar_get_filing. By default, sub-lines consolidate into positions sorted by value; consolidate=false preserves raw filing order. Page with limit, offset and returned next_offset. When canvas is available, the original report\'s full parsed positions are staged as df_<id>: inspect with secedgar_dataframe_describe, then aggregate or join on cusip + reporting_period with secedgar_dataframe_query. Managers below $100M in 13(f) securities may not file. Use secedgar_search_filings with forms=["13F-HR"] for broader search.',
313
+ description: 'Read an institutional manager\'s 13F-HR information table for a quarter. company is the filer: a 10-digit CIK, ticker, or name; names outside the ticker file use EDGAR entity search, and ambiguous names return candidates. For managers holding an issuer, use secedgar_find_holders and pass its filer_cik here. Positions carry issuer, CUSIP, shares, whole-USD market value, option designation, and the accessions they came from. Same-period 13F-HR/A amendments are composed in acceptance order: a RESTATEMENT replaces the rows, a NEW HOLDINGS amendment adds its rows, and each amendment reports how it was applied. By default, sub-lines consolidate into positions sorted by value; consolidate=false preserves raw filing order, each filing\'s rows after the last. Page with limit, offset and returned next_offset. When canvas is available, the full composed positions are staged as df_<id>: inspect with secedgar_dataframe_describe, then aggregate or join on cusip + reporting_period with secedgar_dataframe_query. Managers below $100M in 13(f) securities may not file. Use secedgar_search_filings with forms=["13F-HR"] for broader search.',
152
314
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
153
315
  errors: [
154
316
  {
@@ -201,13 +363,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
201
363
  .string()
202
364
  .optional()
203
365
  .describe('Reporting quarter to target, in "YYYY-QN" format (e.g., "2025-Q4"), matched exactly against each 13F-HR\'s period of report. When omitted, returns the most recent 13F-HR in the submissions feed\'s recent window (the last year or 1,000 filings, whichever holds more). Quarters map to the filing window: Q4 2025 = filings submitted roughly Jan–Mar 2026. A quarter older than the recent window is looked up in the archive, reading forward from the quarter end up to 10 archive pages. A quarter the manager covered with a 13F-NT notice (holdings reported by other managers) fails naming that notice.'),
204
- limit: z
205
- .number()
206
- .int()
207
- .min(1)
208
- .max(500)
209
- .default(20)
210
- .describe('Maximum number of holdings rows to return. 13F filings from large institutions can contain thousands of positions. Default 20.'),
366
+ limit: holdingsLimit.schema(true),
211
367
  offset: z
212
368
  .number()
213
369
  .int()
@@ -222,27 +378,29 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
222
378
  // Other tools' spellings of the company parameter, and this tool's former one (#115).
223
379
  inputAliases: { ticker: 'company', cik: 'company', ticker_or_cik: 'company' },
224
380
  output: z.object({
225
- filer_name: z.string().describe('Name of the institutional filer (the 13F submitter).'),
381
+ filer_name: z.string().describe('Institutional filer name (the 13F submitter).'),
226
382
  filer_cik: z.string().describe('CIK of the 13F filer, zero-padded to 10 digits.'),
227
383
  reporting_period: z
228
384
  .string()
229
385
  .optional()
230
386
  .describe('Cover-page quarter end (YYYY-MM-DD). Absent if omitted.'),
231
- filing_date: z.string().describe('Date the 13F was submitted (YYYY-MM-DD).'),
232
- accession_number: z
233
- .string()
234
- .describe('Accession number of this 13F-HR — pass to secedgar_get_filing.'),
387
+ filing_date: z.string().describe('Original 13F-HR filing date (YYYY-MM-DD).'),
388
+ accession_number: z.string().describe('Original 13F-HR accession for secedgar_get_filing.'),
235
389
  amendments: z
236
- .array(amendmentSchema.describe('Same-period amendment; its holdings are not merged.'))
390
+ .array(amendmentSchema.describe('Same-period 13F-HR/A.'))
237
391
  .optional()
238
- .describe('Known amendments to the original report. Absent when none were found.'),
392
+ .describe('Known amendments, newest filed first. Absent if none.'),
239
393
  amendment_search_complete: z
240
394
  .boolean()
241
395
  .optional()
242
396
  .describe('False if archive discovery was bounded or unavailable.'),
243
- total_holdings_in_filing: z
397
+ composed_accessions: z
398
+ .array(z.string())
399
+ .describe('Accessions whose rows form holdings, in application order.'),
400
+ total_holdings_in_filing: z.number().describe('Original 13F-HR raw row count.'),
401
+ total_holdings_composed: z
244
402
  .number()
245
- .describe('Original raw row count before consolidation or paging.'),
403
+ .describe('Composed raw row count before consolidation or paging.'),
246
404
  total_positions: z
247
405
  .number()
248
406
  .optional()
@@ -264,7 +422,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
264
422
  market_value_usd: z
265
423
  .number()
266
424
  .optional()
267
- .describe('Whole USD at report date; pre-2023-01-03 filing values scaled from thousands. Absent if unreported.'),
425
+ .describe('Whole USD at report date; values filed before 2023-01-03 scaled from thousands. Absent if unreported.'),
268
426
  shares_or_principal_amount: z
269
427
  .number()
270
428
  .optional()
@@ -281,9 +439,12 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
281
439
  .enum(['SOLE', 'DFND', 'OTR'])
282
440
  .optional()
283
441
  .describe('SOLE sole, DFND shared/advised, OTR other. Absent if unreported or consolidated.'),
442
+ source_accession_numbers: z
443
+ .array(z.string())
444
+ .describe('Accessions the row came from, in application order.'),
284
445
  })
285
446
  .describe('One row from the 13F information table.'))
286
- .describe('`limit` rows from `offset`: positions by market value when consolidate=true, else raw rows in filing order.'),
447
+ .describe('`limit` rows from `offset`: positions by value when consolidate=true, else raw rows in application order.'),
287
448
  dataset: z
288
449
  .object({
289
450
  name: z
@@ -293,13 +454,13 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
293
454
  expires_at: z.string().describe('ISO 8601 expiry timestamp.'),
294
455
  })
295
456
  .optional()
296
- .describe('Original-report positions, shaped by consolidate; join on cusip + reporting_period. Amendment positions are excluded. Absent without canvas or holdings.'),
457
+ .describe('Composed positions, shaped by consolidate; join on cusip + reporting_period. Absent without canvas or holdings.'),
297
458
  }),
298
459
  enrichment: {
299
460
  notice: z
300
461
  .string()
301
462
  .optional()
302
- .describe('Amendment disclosure, incomplete discovery, paging, and dataframe guidance.'),
463
+ .describe('Amendment composition, discovery, paging, and dataframe guidance.'),
303
464
  truncated: z
304
465
  .boolean()
305
466
  .optional()
@@ -308,6 +469,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
308
469
  cap: z.number().optional().describe('The limit cap applied.'),
309
470
  },
310
471
  async handler(input, ctx) {
472
+ const limit = holdingsLimit.apply(input.limit, ctx);
311
473
  const api = getEdgarApiService();
312
474
  const callScope = new CallScope(ctx.signal);
313
475
  // Resolve entity to CIK. Ticker/CIK/name go through the ticker cache first; on a
@@ -458,21 +620,22 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
458
620
  : '';
459
621
  throw ctx.fail('no_filings_found', `No 13F-HR filings found for '${input.company}' for quarter "${input.quarter}".${searched}`);
460
622
  }
461
- // Get the filing index to find the information table document
462
- const filingIndex = await api.tryGetFilingIndex(match.cik, filingMeta.accessionNumber, callScope);
463
- if (!filingIndex) {
464
- throw ctx.fail('no_info_table', `Filing ${filingMeta.accessionNumber} index could not be fetched.`);
465
- }
466
- const infoTableDoc = findInfoTableDocument(filingIndex.directory.item);
467
- if (!infoTableDoc) {
468
- throw ctx.fail('no_info_table', `No information table XML found in filing ${filingMeta.accessionNumber}.`, {
469
- accession_number: filingMeta.accessionNumber,
470
- available_documents: filingIndex.directory.item.map((i) => i.name),
471
- });
472
- }
473
- const xmlText = await api.tryGetFilingDocument(match.cik, filingMeta.accessionNumber, infoTableDoc, callScope);
474
- if (!xmlText) {
475
- throw ctx.fail('no_info_table', `Information table document '${infoTableDoc}' could not be fetched.`);
623
+ // The original's information table is required: a failure here fails the call.
624
+ const originalTable = await readInfoTable(api, match.cik, filingMeta.accessionNumber, callScope);
625
+ switch (originalTable.kind) {
626
+ case 'ok':
627
+ break;
628
+ case 'no_index':
629
+ throw ctx.fail('no_info_table', `Filing ${filingMeta.accessionNumber} index could not be fetched.`);
630
+ case 'no_document':
631
+ throw ctx.fail('no_info_table', `No information table XML found in filing ${filingMeta.accessionNumber}.`, {
632
+ accession_number: filingMeta.accessionNumber,
633
+ available_documents: originalTable.documents,
634
+ });
635
+ case 'no_table':
636
+ throw ctx.fail('no_info_table', `Information table document '${originalTable.document}' could not be fetched.`);
637
+ case 'unparseable':
638
+ throw ctx.fail('no_info_table', `Failed to parse information table XML for filing ${filingMeta.accessionNumber}.`);
476
639
  }
477
640
  // Pull reporting period and filing-manager name from the primary_doc.xml cover page.
478
641
  // The CIK resolver only knows names for ticker-listed entities, but most 13F filers
@@ -481,30 +644,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
481
644
  const { filerName, reportingPeriod } = primaryXml
482
645
  ? parseThirteenFCoverPage(primaryXml)
483
646
  : { filerName: undefined, reportingPeriod: undefined };
484
- let parsed;
485
- try {
486
- parsed = parseInfoTableXml(xmlText);
487
- }
488
- catch {
489
- throw ctx.fail('no_info_table', `Failed to parse information table XML for filing ${filingMeta.accessionNumber}.`);
490
- }
491
- // SEC's 2022 Form 13F amendments (effective 2023-01-03) switched Information Table
492
- // Column 4 from thousands of dollars to whole dollars. Normalize older filings (still
493
- // reported in thousands) up to whole USD using the filing date — the literal compliance
494
- // boundary, and always present (unlike the cover-page reporting period).
495
- const valuesInThousands = filingMeta.filingDate < '2023-01-03';
496
- const toUsd = (v) => v === undefined ? undefined : valuesInThousands ? v * 1000 : v;
497
- const rows = parsed.holdings.map((h) => ({
498
- issuer_name: h.issuer_name,
499
- title_of_class: h.title_of_class,
500
- cusip: h.cusip,
501
- market_value_usd: toUsd(h.value_reported),
502
- shares_or_principal_amount: h.shares_or_principal_amount,
503
- shares_or_principal_type: h.shares_or_principal_type,
504
- put_call: h.put_call,
505
- investment_discretion: h.investment_discretion,
506
- }));
507
- const positions = input.consolidate ? consolidatePositions(rows) : rows;
647
+ const originalRows = toHoldingRows(originalTable.holdings, filingMeta.accessionNumber, filingMeta.filingDate);
508
648
  /** Discovery is optional enrichment after the original is readable. Resume an
509
649
  * archive walk that found the original so later-filed amendments are included.
510
650
  * Every request shares the primary operation's failure budget and cancellation.
@@ -533,7 +673,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
533
673
  .filter((r) => r.form === '13F-HR/A' && amendmentPeriod && r.reportDate === amendmentPeriod)
534
674
  .map((r) => [r.accessionNumber, r])).values(),
535
675
  ].sort((a, b) => b.filingDate.localeCompare(a.filingDate));
536
- const amendments = [];
676
+ const entries = [];
537
677
  for (const amendment of samePeriod) {
538
678
  let amendmentType;
539
679
  let unavailableReason = 'lookup_stopped';
@@ -553,18 +693,66 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
553
693
  err.code === JsonRpcErrorCode.RateLimited || callScope.remainingMs === 0;
554
694
  }
555
695
  }
556
- amendments.push({
557
- accession_number: amendment.accessionNumber,
558
- filing_date: amendment.filingDate,
559
- ...(amendmentType
560
- ? { amendment_type: amendmentType }
561
- : { amendment_type: 'UNAVAILABLE', unavailable_reason: unavailableReason }),
696
+ entries.push({
697
+ amendmentType,
698
+ step: {
699
+ accession: amendment.accessionNumber,
700
+ kind: amendmentType,
701
+ row: amendment,
702
+ status: 'superseded',
703
+ },
704
+ unavailableReason,
562
705
  });
563
706
  }
707
+ // Compose the quarter. Each amendment table read is two more requests (index and
708
+ // table) on the same CallScope; a 429 or a spent failure budget stops further reads,
709
+ // as it stops the cover reads above, and a caller cancel still fails the call.
710
+ const original = {
711
+ accession: filingMeta.accessionNumber,
712
+ kind: 'original',
713
+ row: filingMeta,
714
+ status: 'superseded',
715
+ };
716
+ const steps = [original, ...entries.map((e) => e.step)].sort((a, b) => compositionOrder(a.row, b.row));
717
+ const composed = await composeHoldings(steps, originalRows, async (step) => {
718
+ if (disclosureBlocked)
719
+ return;
720
+ try {
721
+ const read = await readInfoTable(api, match.cik, step.accession, callScope);
722
+ // An amendment exists to change rows: an empty table is unreadable, never a
723
+ // restatement that blanks the quarter.
724
+ if (read.kind !== 'ok' || read.holdings.length === 0)
725
+ return;
726
+ return toHoldingRows(read.holdings, step.accession, step.row.filingDate);
727
+ }
728
+ catch (err) {
729
+ callScope.signal.throwIfAborted();
730
+ if (!optionalLookupFailure(err))
731
+ throw err;
732
+ disclosureBlocked =
733
+ err.code === JsonRpcErrorCode.RateLimited || callScope.remainingMs === 0;
734
+ return;
735
+ }
736
+ });
737
+ const amendments = entries.map((e) => ({
738
+ accession_number: e.step.accession,
739
+ filing_date: e.step.row.filingDate,
740
+ applied_as: e.step.status,
741
+ ...(e.amendmentType
742
+ ? { amendment_type: e.amendmentType }
743
+ : { amendment_type: 'UNAVAILABLE', unavailable_reason: e.unavailableReason }),
744
+ }));
745
+ const positions = input.consolidate ? consolidatePositions(composed.rows) : composed.rows;
746
+ const notApplied = amendments.filter((a) => a.applied_as === 'not_applied');
564
747
  const amendmentNotice = [
565
748
  ...(amendments.length > 0
566
749
  ? [
567
- `Holdings and dataframe contain the original report only; ${amendments.length} same-period amendment(s) are not merged. Read each with secedgar_get_filing: ${amendments.map((a) => `${a.accession_number} (filed ${a.filing_date}, ${a.amendment_type}${a.amendment_type === 'UNAVAILABLE' ? `: ${a.unavailable_reason}` : ''})`).join('; ')}.`,
750
+ `Holdings and dataframe compose the original 13F-HR with its same-period amendments, applied in acceptance order: a RESTATEMENT replaces the rows, NEW HOLDINGS adds them. Amendments, newest filed first: ${amendments.map((a) => `${a.accession_number} (filed ${a.filing_date}, ${a.amendment_type}${a.amendment_type === 'UNAVAILABLE' ? `: ${a.unavailable_reason}` : ''}, ${a.applied_as})`).join('; ')}. Rows come from ${composed.accessions.join(', ')}, in that order.`,
751
+ ]
752
+ : []),
753
+ ...(notApplied.length > 0
754
+ ? [
755
+ `Not applied, since the type or information table could not be read: ${notApplied.map((a) => a.accession_number).join(', ')} — inspect with secedgar_get_filing.`,
568
756
  ]
569
757
  : []),
570
758
  ...(!amendmentSearchComplete
@@ -596,6 +784,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
596
784
  market_value_usd: p.market_value_usd ?? null,
597
785
  put_call: p.put_call ?? null,
598
786
  investment_discretion: p.investment_discretion ?? null,
787
+ source_accession_numbers: p.source_accession_numbers,
599
788
  })),
600
789
  sourceTool: 'secedgar_get_institutional_holdings',
601
790
  queryParams: {
@@ -604,6 +793,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
604
793
  quarter: input.quarter,
605
794
  consolidate: input.consolidate,
606
795
  accession_number: filingMeta.accessionNumber,
796
+ composed_accessions: composed.accessions,
607
797
  },
608
798
  });
609
799
  if (registered)
@@ -612,7 +802,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
612
802
  // Offset paging over the whole ordered position list — the retrieval path for
613
803
  // rows past `limit` when no canvas is available to hold the full set (#94). The
614
804
  // information table is parsed whole, so slicing it is contiguous and stable.
615
- const pageEnd = input.offset + input.limit;
805
+ const pageEnd = input.offset + limit;
616
806
  const holdings = positions.slice(input.offset, pageEnd);
617
807
  const nextOffset = pageEnd < positions.length ? pageEnd : undefined;
618
808
  // One chain, because `notice` is last-wins across notice/truncated: each arm
@@ -635,7 +825,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
635
825
  if (holdings.length > 0 && nextOffset !== undefined) {
636
826
  ctx.enrich.truncated({
637
827
  shown: holdings.length,
638
- cap: input.limit,
828
+ cap: limit,
639
829
  ...(notices.length > 0 && { guidance: notices.join(' ') }),
640
830
  });
641
831
  }
@@ -644,7 +834,9 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
644
834
  ctx.log.info('Institutional holdings retrieved', {
645
835
  cik: match.cik,
646
836
  accessionNumber: filingMeta.accessionNumber,
647
- totalHoldings: parsed.holdings.length,
837
+ totalHoldings: originalRows.length,
838
+ composedRows: composed.rows.length,
839
+ composedAccessions: composed.accessions.length,
648
840
  totalPositions: positions.length,
649
841
  returned: holdings.length,
650
842
  datasetName: dataset?.name,
@@ -657,7 +849,9 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
657
849
  accession_number: filingMeta.accessionNumber,
658
850
  amendments: amendments.length > 0 ? amendments : undefined,
659
851
  amendment_search_complete: amendmentSearchComplete,
660
- total_holdings_in_filing: parsed.holdings.length,
852
+ composed_accessions: composed.accessions,
853
+ total_holdings_in_filing: originalRows.length,
854
+ total_holdings_composed: composed.rows.length,
661
855
  total_positions: input.consolidate ? positions.length : undefined,
662
856
  offset: input.offset,
663
857
  next_offset: nextOffset,
@@ -668,16 +862,17 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
668
862
  format: (result) => {
669
863
  const period = result.reporting_period ? ` (period: ${result.reporting_period})` : '';
670
864
  const countLine = result.total_positions !== undefined
671
- ? `Showing ${result.holdings.length} of ${result.total_positions} positions (consolidated from ${result.total_holdings_in_filing} info-table rows)`
672
- : `Showing ${result.holdings.length} of ${result.total_holdings_in_filing} info-table rows`;
865
+ ? `Showing ${result.holdings.length} of ${result.total_positions} positions (consolidated from ${result.total_holdings_composed} info-table rows)`
866
+ : `Showing ${result.holdings.length} of ${result.total_holdings_composed} info-table rows`;
673
867
  const lines = [
674
868
  `**13F-HR Holdings** — ${result.filer_name} (CIK ${result.filer_cik})`,
675
869
  `Filed: ${result.filing_date}${period} | Accession: ${result.accession_number}`,
676
870
  countLine,
871
+ `Composed from: ${result.composed_accessions.join(', ')} (${result.total_holdings_composed} rows; original 13F-HR: ${result.total_holdings_in_filing})`,
677
872
  ];
678
873
  lines.push(`Page offset: ${result.offset} (${result.holdings.length} shown)`);
679
874
  for (const amendment of result.amendments ?? []) {
680
- lines.push(`Amendment: ${amendment.accession_number}, filed ${amendment.filing_date}, ${amendment.amendment_type}${amendment.amendment_type === 'UNAVAILABLE' ? ` (${amendment.unavailable_reason})` : ''} — read with secedgar_get_filing; holdings remain from the original report.`);
875
+ lines.push(`Amendment: ${amendment.accession_number}, filed ${amendment.filing_date}, ${amendment.amendment_type}${amendment.amendment_type === 'UNAVAILABLE' ? ` (${amendment.unavailable_reason})` : ''} — applied as ${amendment.applied_as}${amendment.applied_as === 'not_applied' ? '; inspect with secedgar_get_filing' : ''}.`);
681
876
  }
682
877
  if (result.amendment_search_complete !== undefined)
683
878
  lines.push(result.amendment_search_complete
@@ -699,7 +894,7 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
699
894
  const classStr = h.title_of_class ? ` (${h.title_of_class})` : '';
700
895
  const discStr = h.investment_discretion ? ` | discretion: ${h.investment_discretion}` : '';
701
896
  lines.push(`**${h.issuer_name}**${classStr}${cusipStr}${putCallStr}`);
702
- lines.push(`${sharesStr} | ${valueStr}${discStr}`);
897
+ lines.push(`${sharesStr} | ${valueStr}${discStr} | source: ${h.source_accession_numbers.join(', ')}`);
703
898
  }
704
899
  if (result.dataset) {
705
900
  const note = result.dataset.row_count > result.holdings.length
@@ -710,4 +905,8 @@ export const getInstitutionalHoldingsTool = tool('secedgar_get_institutional_hol
710
905
  return [{ type: 'text', text: lines.join('\n') }];
711
906
  },
712
907
  });
908
+ /** `secedgar_get_institutional_holdings` as this deployment's `EDGAR_CLAMP_OVERSIZED_LIMITS` builds it. */
909
+ export function createGetInstitutionalHoldingsTool(options) {
910
+ return withLimitClamps(getInstitutionalHoldingsTool, [holdingsLimit], options);
911
+ }
713
912
  //# sourceMappingURL=get-institutional-holdings.tool.js.map