@cyanheads/secedgar-mcp-server 0.20.1 → 0.21.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 (107) hide show
  1. package/AGENTS.md +26 -19
  2. package/CLAUDE.md +26 -19
  3. package/README.md +19 -10
  4. package/changelog/0.21.x/0.21.0.md +35 -0
  5. package/dist/mcp-server/prompts/definitions/company-analysis.prompt.js +3 -3
  6. package/dist/mcp-server/prompts/definitions/company-analysis.prompt.js.map +1 -1
  7. package/dist/mcp-server/tools/annual-report-reads.d.ts +50 -0
  8. package/dist/mcp-server/tools/annual-report-reads.d.ts.map +1 -0
  9. package/dist/mcp-server/tools/annual-report-reads.js +141 -0
  10. package/dist/mcp-server/tools/annual-report-reads.js.map +1 -0
  11. package/dist/mcp-server/tools/calendar-quarter.d.ts +22 -0
  12. package/dist/mcp-server/tools/calendar-quarter.d.ts.map +1 -0
  13. package/dist/mcp-server/tools/calendar-quarter.js +34 -0
  14. package/dist/mcp-server/tools/calendar-quarter.js.map +1 -0
  15. package/dist/mcp-server/tools/definitions/company-search.tool.d.ts.map +1 -1
  16. package/dist/mcp-server/tools/definitions/company-search.tool.js +10 -21
  17. package/dist/mcp-server/tools/definitions/company-search.tool.js.map +1 -1
  18. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts +12 -2
  19. package/dist/mcp-server/tools/definitions/compare-companies.tool.d.ts.map +1 -1
  20. package/dist/mcp-server/tools/definitions/compare-companies.tool.js +120 -29
  21. package/dist/mcp-server/tools/definitions/compare-companies.tool.js.map +1 -1
  22. package/dist/mcp-server/tools/definitions/find-holders.tool.d.ts.map +1 -1
  23. package/dist/mcp-server/tools/definitions/find-holders.tool.js +9 -16
  24. package/dist/mcp-server/tools/definitions/find-holders.tool.js.map +1 -1
  25. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.d.ts +24 -9
  26. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.d.ts.map +1 -1
  27. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js +125 -46
  28. package/dist/mcp-server/tools/definitions/get-beneficial-owners.tool.js.map +1 -1
  29. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts +10 -0
  30. package/dist/mcp-server/tools/definitions/get-filing.tool.d.ts.map +1 -1
  31. package/dist/mcp-server/tools/definitions/get-filing.tool.js +150 -6
  32. package/dist/mcp-server/tools/definitions/get-filing.tool.js.map +1 -1
  33. package/dist/mcp-server/tools/definitions/get-financials.tool.d.ts.map +1 -1
  34. package/dist/mcp-server/tools/definitions/get-financials.tool.js +53 -34
  35. package/dist/mcp-server/tools/definitions/get-financials.tool.js.map +1 -1
  36. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.d.ts.map +1 -1
  37. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.js +2 -3
  38. package/dist/mcp-server/tools/definitions/get-fund-holdings.tool.js.map +1 -1
  39. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.d.ts +24 -0
  40. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.d.ts.map +1 -1
  41. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.js +266 -70
  42. package/dist/mcp-server/tools/definitions/get-insider-transactions.tool.js.map +1 -1
  43. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.d.ts +12 -0
  44. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.d.ts.map +1 -1
  45. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.js +16 -31
  46. package/dist/mcp-server/tools/definitions/get-institutional-holdings.tool.js.map +1 -1
  47. package/dist/mcp-server/tools/definitions/get-material-events.tool.d.ts +15 -0
  48. package/dist/mcp-server/tools/definitions/get-material-events.tool.d.ts.map +1 -1
  49. package/dist/mcp-server/tools/definitions/get-material-events.tool.js +107 -54
  50. package/dist/mcp-server/tools/definitions/get-material-events.tool.js.map +1 -1
  51. package/dist/mcp-server/tools/definitions/get-snapshot.tool.d.ts +5 -0
  52. package/dist/mcp-server/tools/definitions/get-snapshot.tool.d.ts.map +1 -1
  53. package/dist/mcp-server/tools/definitions/get-snapshot.tool.js +48 -17
  54. package/dist/mcp-server/tools/definitions/get-snapshot.tool.js.map +1 -1
  55. package/dist/mcp-server/tools/definitions/index.d.ts +274 -226
  56. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -1
  57. package/dist/mcp-server/tools/definitions/search-concepts.tool.js +1 -1
  58. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts +16 -0
  59. package/dist/mcp-server/tools/definitions/search-filings.tool.d.ts.map +1 -1
  60. package/dist/mcp-server/tools/definitions/search-filings.tool.js +42 -28
  61. package/dist/mcp-server/tools/definitions/search-filings.tool.js.map +1 -1
  62. package/dist/mcp-server/tools/filing-dates.d.ts +46 -0
  63. package/dist/mcp-server/tools/filing-dates.d.ts.map +1 -0
  64. package/dist/mcp-server/tools/filing-dates.js +93 -0
  65. package/dist/mcp-server/tools/filing-dates.js.map +1 -0
  66. package/dist/mcp-server/tools/limit-clamp.d.ts.map +1 -1
  67. package/dist/mcp-server/tools/limit-clamp.js +6 -2
  68. package/dist/mcp-server/tools/limit-clamp.js.map +1 -1
  69. package/dist/services/edgar/body-text-decoder.d.ts +33 -0
  70. package/dist/services/edgar/body-text-decoder.d.ts.map +1 -0
  71. package/dist/services/edgar/body-text-decoder.js +103 -0
  72. package/dist/services/edgar/body-text-decoder.js.map +1 -0
  73. package/dist/services/edgar/concept-map.d.ts.map +1 -1
  74. package/dist/services/edgar/concept-map.js +70 -12
  75. package/dist/services/edgar/concept-map.js.map +1 -1
  76. package/dist/services/edgar/concept-series.d.ts +80 -1
  77. package/dist/services/edgar/concept-series.d.ts.map +1 -1
  78. package/dist/services/edgar/concept-series.js +134 -10
  79. package/dist/services/edgar/concept-series.js.map +1 -1
  80. package/dist/services/edgar/edgar-api-service.d.ts.map +1 -1
  81. package/dist/services/edgar/edgar-api-service.js +12 -8
  82. package/dist/services/edgar/edgar-api-service.js.map +1 -1
  83. package/dist/services/edgar/eight-k-items.d.ts +19 -1
  84. package/dist/services/edgar/eight-k-items.d.ts.map +1 -1
  85. package/dist/services/edgar/eight-k-items.js +24 -1
  86. package/dist/services/edgar/eight-k-items.js.map +1 -1
  87. package/dist/services/edgar/filing-to-text.d.ts +13 -6
  88. package/dist/services/edgar/filing-to-text.d.ts.map +1 -1
  89. package/dist/services/edgar/filing-to-text.js +23 -3
  90. package/dist/services/edgar/filing-to-text.js.map +1 -1
  91. package/dist/services/edgar/form4-amendments.d.ts +63 -0
  92. package/dist/services/edgar/form4-amendments.d.ts.map +1 -0
  93. package/dist/services/edgar/form4-amendments.js +99 -0
  94. package/dist/services/edgar/form4-amendments.js.map +1 -0
  95. package/dist/services/edgar/mirror/companyfacts-sync.d.ts +6 -1
  96. package/dist/services/edgar/mirror/companyfacts-sync.d.ts.map +1 -1
  97. package/dist/services/edgar/mirror/companyfacts-sync.js +29 -6
  98. package/dist/services/edgar/mirror/companyfacts-sync.js.map +1 -1
  99. package/dist/services/edgar/ownership-parser.d.ts +5 -0
  100. package/dist/services/edgar/ownership-parser.d.ts.map +1 -1
  101. package/dist/services/edgar/ownership-parser.js +3 -0
  102. package/dist/services/edgar/ownership-parser.js.map +1 -1
  103. package/dist/services/edgar/types.d.ts +3 -1
  104. package/dist/services/edgar/types.d.ts.map +1 -1
  105. package/package.json +1 -1
  106. package/server.json +3 -3
  107. package/skills/secedgar-guide/SKILL.md +8 -5
@@ -8,6 +8,7 @@ import { JsonRpcErrorCode, McpError } 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
10
  import { datasetSchema } from '../dataset-schema.js';
11
+ import { checkFilingDates, filingDateField } from '../filing-dates.js';
11
12
  import { fixedPoint } from '../fixed-point.js';
12
13
  import { limitClamp, withLimitClamps, } from '../limit-clamp.js';
13
14
  import { resolvedAsField } from '../resolved-as.js';
@@ -15,6 +16,7 @@ import { SEC_UPSTREAM_ERRORS } from '../sec-upstream-errors.js';
15
16
  import { dataframeGuidance, getCanvasBridge, toDatasetField, } from '../../../services/canvas-bridge/canvas-bridge.js';
16
17
  import { CallScope } from '../../../services/edgar/call-scope.js';
17
18
  import { getEdgarApiService } from '../../../services/edgar/edgar-api-service.js';
19
+ import { pairAmendments, rowKey, } from '../../../services/edgar/form4-amendments.js';
18
20
  import { nonUsListingNote } from '../../../services/edgar/listing-codes.js';
19
21
  import { parseForm4Xml, } from '../../../services/edgar/ownership-parser.js';
20
22
  import { sameCik } from '../../../services/edgar/same-cik.js';
@@ -38,34 +40,48 @@ const FILINGS_PER_TRANSACTION = 5;
38
40
  const INLINE_TRANSACTION_CAP = 100;
39
41
  /** Structured Form 4 XML became mandatory for filings on and after this date. */
40
42
  const STRUCTURED_FORM4_START = '2003-06-30';
43
+ /** Ownership forms, whose rows in a reporting owner's feed carry the issuer's file number. */
44
+ const OWNERSHIP_FORMS = new Set(['3', '3/A', '4', '4/A', '5', '5/A']);
41
45
  /**
42
- * The Form 4 / 4-A rows of a submissions block filed inside the window that `role` reads,
43
- * in block order (newest first). Only rows whose primary document is ownership XML —
44
- * EDGAR's structured Form 4 began in mid-2003, and an earlier HTML or text filing has
45
- * nothing this tool can parse, so fetching it would spend a request on an empty result.
46
- * Under `reporting_owner`, only rows the feed lists with a file number: EDGAR lists a
47
- * Form 4 in each reporting owner's feed under the issuer's file number and in the
48
- * issuer's own feed under none, so the rest name this filer as their issuer and are
49
- * counted in `issuerRows` instead of read (#260).
46
+ * The Form 4 / 4-A rows of a submissions block filed inside the window, in block order
47
+ * (newest first), and the file numbers the block shows to be the filer's own. Only rows
48
+ * whose primary document is ownership XML — EDGAR's structured Form 4 began in mid-2003,
49
+ * and an earlier HTML or text filing has nothing this tool can parse, so fetching it
50
+ * would spend a request on an empty result.
51
+ *
52
+ * EDGAR lists a Form 4 in each reporting owner's feed under the issuer's file number. In
53
+ * the issuer's own feed it lists one under none, unless the issuer is also a reporting
54
+ * owner of it — CTT Pharmaceutical is on its CEO's Form 4s — and then under the issuer's
55
+ * own number. The filer's own numbers are those on its rows of every other form, whatever
56
+ * their date, so a row under any other number is a Form 4 it filed as another issuer's
57
+ * owner (#260, #265).
50
58
  */
51
- function windowForm4Rows(block, inWindow, role) {
59
+ function windowForm4Rows(block, inWindow) {
52
60
  const rows = [];
53
- let issuerRows = 0;
61
+ const ownFileNumbers = [];
54
62
  for (let i = 0; i < block.form.length; i++) {
55
- const form = block.form[i];
63
+ const form = block.form[i] ?? '';
64
+ const fileNumber = block.fileNumber?.[i] ?? '';
65
+ if (!OWNERSHIP_FORMS.has(form)) {
66
+ if (fileNumber)
67
+ ownFileNumbers.push(fileNumber);
68
+ continue;
69
+ }
56
70
  const filingDate = block.filingDate[i] ?? '';
57
71
  const primaryDocument = block.primaryDocument[i] ?? '';
58
72
  if ((form !== '4' && form !== '4/A') || !inWindow(filingDate))
59
73
  continue;
60
74
  if (!/\.xml$/i.test(primaryDocument))
61
75
  continue;
62
- if (role === 'reporting_owner' && !block.fileNumber?.[i]) {
63
- issuerRows++;
64
- continue;
65
- }
66
- rows.push({ accessionNumber: block.accessionNumber[i] ?? '', filingDate, primaryDocument });
76
+ rows.push({
77
+ accessionNumber: block.accessionNumber[i] ?? '',
78
+ fileNumber,
79
+ filingDate,
80
+ form,
81
+ primaryDocument,
82
+ });
67
83
  }
68
- return { rows, issuerRows };
84
+ return { rows, ownFileNumbers };
69
85
  }
70
86
  /**
71
87
  * The filings a scan of at most `cap` reads from `batch` (newest first), ending on a whole
@@ -151,6 +167,85 @@ function issuerClause(tx) {
151
167
  return ids ? ` at ${ids}` : '';
152
168
  return ` at ${escapeMarkdownInline(tx.issuer_name)}${ids ? ` (${ids})` : ''}`;
153
169
  }
170
+ /** `a`, `a and b`, `a, b, and c`. */
171
+ function listed(items) {
172
+ return items.length <= 2
173
+ ? items.join(' and ')
174
+ : `${items.slice(0, -1).join(', ')}, and ${items.at(-1)}`;
175
+ }
176
+ /**
177
+ * The notice sentences on the scan's Form 4/A amendments whose filings put a row in the
178
+ * result (#267): each pair, each case no rule settled, and for a 4/A whose Form 4 predates
179
+ * the filings read, the window holding both.
180
+ */
181
+ function amendmentSentences(amendments, inResult, scan) {
182
+ const sentences = [];
183
+ const pairs = amendments.pairs.filter((pair) => inResult.has(pair.amendment) || inResult.has(pair.original));
184
+ if (pairs.length > 0) {
185
+ sentences.push(`Form 4/A amendments in this scan: ${pairs.map((pair) => `${pair.amendment} amends ${pair.original}`).join('; ')}. Rows a 4/A restates carry amended_by; leave them out of net activity (WHERE amended_by IS NULL).`);
186
+ }
187
+ // Each kind of flag is one sentence however many pairs raise it; the pair list maps each 4/A to its Form 4.
188
+ const flagged = (kind) => pairs.filter((pair) => pair[kind]);
189
+ const [shared, unmatched] = [flagged('sharedKey'), flagged('unmatched')];
190
+ const [oneShared] = shared;
191
+ if (oneShared) {
192
+ sentences.push(shared.length === 1
193
+ ? `${oneShared.amendment} restates a security, date, and code that several rows of ${oneShared.original} share, so those rows carry no amended_by; check them against it.`
194
+ : `${listed(shared.map((pair) => pair.amendment))} each restate a security, date, and code that several rows of the Form 4 it amends share, so those rows carry no amended_by; check them against the 4/A.`);
195
+ }
196
+ const [oneUnmatched] = unmatched;
197
+ if (oneUnmatched) {
198
+ sentences.push(unmatched.length === 1
199
+ ? `${oneUnmatched.amendment} holds a row matching no row of ${oneUnmatched.original} by security, date, and code — a corrected date or code — so any row it replaces carries no amended_by; check them against it.`
200
+ : `${listed(unmatched.map((pair) => pair.amendment))} each hold a row matching no row of the Form 4 it amends by security, date, and code — a corrected date or code — so any row it replaces carries no amended_by; check them against the 4/A.`);
201
+ }
202
+ for (const { original, amendments: several } of amendments.contested) {
203
+ if (!inResult.has(original) && !several.some((accession) => inResult.has(accession)))
204
+ continue;
205
+ const two = several.length === 2;
206
+ sentences.push(`${listed(several)} ${two ? 'both' : 'all'} amend ${original}, so none of its rows carries amended_by; check them against ${two ? 'both' : 'each'}.`);
207
+ }
208
+ // 4/As whose Form 4 predates the oldest date read, grouped by the date they amend. Filings
209
+ // run newest first, so the first 4/A a group meets is its newest.
210
+ const unreached = new Map();
211
+ for (const unpaired of amendments.unpaired) {
212
+ if (!inResult.has(unpaired.amendment))
213
+ continue;
214
+ if (unpaired.reason === 'no_date') {
215
+ sentences.push(`${unpaired.amendment} states no original filing date, so it pairs with no Form 4.`);
216
+ }
217
+ else if (unpaired.reason === 'several') {
218
+ sentences.push(`${unpaired.amendment} matches several Form 4s filed ${unpaired.amendsDate} by the same reporting owners, and neither period nor a shared row singles one out, so it pairs with none.`);
219
+ }
220
+ else if (unpaired.amendsDate < scan.scannedThrough) {
221
+ const group = unreached.get(unpaired.amendsDate);
222
+ if (group)
223
+ group.amendments.push(unpaired.amendment);
224
+ else {
225
+ unreached.set(unpaired.amendsDate, {
226
+ amendments: [unpaired.amendment],
227
+ newest: unpaired.filingDate,
228
+ });
229
+ }
230
+ }
231
+ else {
232
+ sentences.push(`${unpaired.amendment} amends a Form 4 filed ${unpaired.amendsDate}, but no Form 4 this call read from that date has its issuer and reporting owners.`);
233
+ }
234
+ }
235
+ for (const [amendsDate, { amendments: group, newest }] of unreached) {
236
+ // The window from the amended date to the newest 4/A holds both; name the bounds it changes.
237
+ const levers = [
238
+ scan.filedAfter !== amendsDate && `filed_after=${amendsDate}`,
239
+ scan.filedBefore !== newest && `filed_before=${newest}`,
240
+ ].filter(Boolean);
241
+ const one = group.length === 1;
242
+ const lead = `${listed(group)} ${one ? 'amends a Form 4' : 'amend Form 4s'} filed ${amendsDate}`;
243
+ sentences.push(levers.length > 0
244
+ ? `${lead}, before the filings this call read; pass ${levers.join(' and ')} to read ${one ? 'it with the Form 4 it amends' : 'them with the Form 4s they amend'}.`
245
+ : `${lead}, which this call did not reach.`);
246
+ }
247
+ return sentences;
248
+ }
154
249
  /** "between A and B" / "on or after A" / "on or before B" for notices. */
155
250
  function describeWindow(filedAfter, filedBefore) {
156
251
  if (filedAfter && filedBefore)
@@ -180,6 +275,18 @@ function ownerRelationship(owner) {
180
275
  parts.push('Other');
181
276
  return parts.join(', ') || 'Unknown';
182
277
  }
278
+ /** A CIK zero-padded to 10 digits; nothing when the filing gives none, rather than an all-zero one. */
279
+ function paddedCik(cik) {
280
+ return cik ? cik.padStart(10, '0') : undefined;
281
+ }
282
+ /** `(CIK 0000019617, 10% Owner)`, the CIK left out when the filing gives none; `escapeText` for Markdown. */
283
+ function ownerDetail(owner, escapeText = (text) => text) {
284
+ return `(${owner.cik ? `CIK ${owner.cik}, ` : ''}${escapeText(owner.relationship)})`;
285
+ }
286
+ /** `DNT Asset Trust (CIK 0002005954, 10% Owner)` — one joint filer, as the dataframe and content[] list it. */
287
+ function jointFilerLabel(owner, escapeText = (text) => text) {
288
+ return `${escapeText(owner.name)} ${ownerDetail(owner, escapeText)}`;
289
+ }
183
290
  /** `limit`: the inline list holds at most 100 transactions (#197). */
184
291
  const transactionsLimit = limitClamp({
185
292
  tool: 'secedgar_get_insider_transactions',
@@ -192,7 +299,7 @@ const transactionsLimit = limitClamp({
192
299
  });
193
300
  export const getInsiderTransactionsTool = tool('secedgar_get_insider_transactions', {
194
301
  title: 'Get Insider Transactions',
195
- description: 'Fetch Form 4 insider transactions (purchases, sales, grants, exercises) for a company by parsing SEC EDGAR ownership XML. Returns the reporting person, their relationship to the issuer, transaction date, type, shares traded (absolute magnitude), direction (acquire/dispose), price per share, and shares owned after the transaction. Covers nonDerivative transactions (open-market buys/sells, gifts) and derivative transactions (option exercises, RSU vests). With role "reporting_owner", company is instead the insider who filed (a person by CIK, or a fund or company holding 10%), and the result is that filer\'s own trades across every issuer, each transaction naming its issuer. Without a date window it reads the newest Form 4 filings; filed_after / filed_before read any period since mid-2003, reaching past the recent submissions window into the archive (e.g. insider trades in the quarter before an earnings miss). When a canvas is available, the full set of transactions parsed from the scanned filings is materialized as df_<id> (the inline list is a preview capped at limit) — inspect it with secedgar_dataframe_describe, then query it with secedgar_dataframe_query to aggregate net buy/sell by insider: SUM(CASE WHEN direction=\'dispose\' THEN -shares_traded ELSE shares_traded END). Use secedgar_search_filings with forms=["4"] to search Form 4 filings across all companies.',
302
+ description: 'Fetch Form 4 and 4/A insider transactions (purchases, sales, grants, exercises) for a company by parsing SEC EDGAR ownership XML: nonDerivative transactions (open-market buys/sells, gifts) and derivative ones (option exercises, RSU vests). With role "reporting_owner", company is instead the insider who filed (a person by CIK, or a fund or company holding 10%), and the result is that filer\'s own trades across every issuer, each transaction naming its issuer. Without a date window it reads the newest Form 4 filings; filed_after / filed_before read any period since mid-2003, past the recent submissions window into the archive. When a canvas is available, every transaction parsed from the scanned filings is materialized as df_<id> (the inline list is a preview capped at limit) — inspect it with secedgar_dataframe_describe, then aggregate net buy/sell by insider with secedgar_dataframe_query: SUM(CASE WHEN direction=\'dispose\' THEN -shares_traded ELSE shares_traded END) ... WHERE amended_by IS NULL, leaving out rows a 4/A in the scan restates. Use secedgar_search_filings with forms=["4"] to search Form 4 filings across all companies.',
196
303
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
197
304
  errors: [
198
305
  {
@@ -215,7 +322,8 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
215
322
  },
216
323
  ...SEC_UPSTREAM_ERRORS,
217
324
  ],
218
- input: z.object({
325
+ input: z
326
+ .object({
219
327
  company: z
220
328
  .string()
221
329
  .min(1)
@@ -229,27 +337,10 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
229
337
  .default('all')
230
338
  .describe('Filter by direction. "purchase" = open-market buys (code P). "sale" = open-market sells (code S). "all" includes grants, awards, exercises, gifts, and other coded transaction types as well.'),
231
339
  limit: transactionsLimit.schema(true),
232
- filed_after: z
233
- .union([
234
- z.literal(''),
235
- z
236
- .string()
237
- .regex(/^\d{4}-\d{2}-\d{2}$/, 'Expected YYYY-MM-DD')
238
- .describe('YYYY-MM-DD'),
239
- ])
240
- .optional()
241
- .describe('Only read Form 4 filings filed on or after this date (YYYY-MM-DD). A date window pages into the archive past the recent submissions window, and with a canvas every Form 4 filed inside it is parsed, up to 100. Structured Form 4 XML begins in mid-2003, so an earlier window finds nothing.'),
242
- filed_before: z
243
- .union([
244
- z.literal(''),
245
- z
246
- .string()
247
- .regex(/^\d{4}-\d{2}-\d{2}$/, 'Expected YYYY-MM-DD')
248
- .describe('YYYY-MM-DD'),
249
- ])
250
- .optional()
251
- .describe('Only read Form 4 filings filed on or before this date (YYYY-MM-DD). Use alone or with filed_after. Without either bound the tool reads the newest Form 4 filings.'),
252
- }),
340
+ filed_after: filingDateField('Only read Form 4 filings filed on or after this date (YYYY-MM-DD). A date window pages into the archive past the recent submissions window, and with a canvas every Form 4 filed inside it is parsed, up to 100. Structured Form 4 XML begins in mid-2003, so an earlier window finds nothing.'),
341
+ filed_before: filingDateField('Only read Form 4 filings filed on or before this date (YYYY-MM-DD). Use alone or with filed_after. Without either bound the tool reads the newest Form 4 filings.'),
342
+ })
343
+ .superRefine(checkFilingDates),
253
344
  // Other tools' spellings of the company and filing-date parameters, and this tool's
254
345
  // former company name (#115).
255
346
  inputAliases: {
@@ -280,10 +371,35 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
280
371
  accession_number: z
281
372
  .string()
282
373
  .describe('Form 4 accession number, for secedgar_get_filing.'),
283
- reporting_person: z.string().describe('Name of the insider who filed the Form 4.'),
374
+ form: z.enum(['4', '4/A']).describe('"4", or "4/A" for an amendment.'),
375
+ amends_filing_date: z
376
+ .string()
377
+ .optional()
378
+ .describe('4/A rows: filing date of the Form 4 it amends (YYYY-MM-DD).'),
379
+ amended_by: z
380
+ .string()
381
+ .optional()
382
+ .describe('Accession of the 4/A in this scan that restates and so supersedes this row; net activity omits it.'),
383
+ reporting_person: z
384
+ .string()
385
+ .describe('First reporting owner listed; under role reporting_owner, the one with that CIK.'),
386
+ reporting_person_cik: z
387
+ .string()
388
+ .optional()
389
+ .describe('CIK of reporting_person, zero-padded.'),
284
390
  relationship: z
285
391
  .string()
286
392
  .describe('Relationship to issuer (e.g., "Director", "Officer (CEO)", "10% Owner").'),
393
+ joint_filers: z
394
+ .array(z
395
+ .object({
396
+ name: z.string().describe('Name as filed.'),
397
+ cik: z.string().optional().describe('CIK, zero-padded.'),
398
+ relationship: z.string().describe('Relationship to issuer.'),
399
+ })
400
+ .describe('A joint filer.'))
401
+ .optional()
402
+ .describe('Other owners of a joint filing, in filing order; the trade is reported once for all.'),
287
403
  issuer_cik: z
288
404
  .string()
289
405
  .optional()
@@ -360,7 +476,7 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
360
476
  notice: z
361
477
  .string()
362
478
  .optional()
363
- .describe("Why the result is empty, the dataframe pointer, and the next call's filed_before and limit."),
479
+ .describe("Why the result is empty, the dataframe pointer, 4/A pairings, and the next call's date bounds and limit."),
364
480
  truncated: z.boolean().optional().describe('True when limit capped transactions[].'),
365
481
  shown: z.number().optional().describe('Transactions shown inline.'),
366
482
  cap: z.number().optional().describe('The limit cap applied.'),
@@ -430,32 +546,53 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
430
546
  }
431
547
  };
432
548
  const ownerRole = input.role === 'reporting_owner';
433
- // The Form 4 rows the role reads, newest first: the recent window, then in a date
434
- // window the archive pages overlapping it, read until the scan budget plus one
435
- // sentinel row is in hand or the shared page cap ends the walk.
549
+ // The in-window Form 4 rows, newest first: the recent window, then in a date window
550
+ // the archive pages overlapping it, read until the scan budget plus one sentinel row
551
+ // the role reads is in hand or the shared page cap ends the walk.
436
552
  const submissions = await readSubmissionsFeed(api.getSubmissions(match.cik, scope));
437
- /** In-window Form 4 rows naming the company as their issuer, which `reporting_owner` leaves unread. */
438
- let issuerRows = 0;
439
553
  const inWindow = (date) => (!filedAfter || date >= filedAfter) && (!filedBefore || date <= filedBefore);
440
- const select = (block) => {
441
- const selected = windowForm4Rows(block, inWindow, input.role);
442
- issuerRows += selected.issuerRows;
443
- return selected.rows;
554
+ const form4Rows = [];
555
+ /** The company's own file numbers, from every block read (#265). */
556
+ const ownFileNumbers = new Set();
557
+ const take = (block) => {
558
+ const selected = windowForm4Rows(block, inWindow);
559
+ form4Rows.push(...selected.rows);
560
+ for (const fileNumber of selected.ownFileNumbers)
561
+ ownFileNumbers.add(fileNumber);
444
562
  };
445
- const filingBatch = select(submissions.filings.recent);
563
+ /**
564
+ * Whether the scan reads a row. Under `reporting_owner`, a row listed under a file number,
565
+ * the company's as an owner; the rest name it as their issuer (#260). Otherwise a row
566
+ * listed under none or the company's own; any other number marks a Form 4 it filed as
567
+ * another issuer's owner, skipped unread (#265). Own numbers only accrue as pages are
568
+ * read, so a row skipped early can turn out to be read, never the reverse.
569
+ */
570
+ const reads = (row) => ownerRole ? row.fileNumber !== '' : !row.fileNumber || ownFileNumbers.has(row.fileNumber);
571
+ const rowsRead = () => form4Rows.filter(reads).length;
572
+ take(submissions.filings.recent);
446
573
  let walk;
447
574
  if (dateWindow) {
448
575
  walk = new SubmissionsArchiveWalk(api, submissions, { filedAfter, filedBefore, order: 'newest-first' }, scope);
449
- if (filingBatch.length <= scanCap) {
576
+ if (rowsRead() <= scanCap) {
450
577
  for await (const { block } of walk) {
451
- filingBatch.push(...select(block));
452
- if (filingBatch.length > scanCap)
578
+ take(block);
579
+ if (rowsRead() > scanCap)
453
580
  break;
454
581
  }
455
582
  }
456
583
  }
584
+ const filingBatch = form4Rows.filter(reads);
585
+ /**
586
+ * The in-window rows the role leaves unread: under `reporting_owner` those naming the
587
+ * company as issuer, otherwise those it filed as another issuer's owner.
588
+ */
589
+ const unread = form4Rows.filter((row) => !reads(row));
590
+ const issuerRows = ownerRole ? unread.length : 0;
591
+ const otherIssuerRows = ownerRole ? [] : unread;
457
592
  const { rows: filingsToScan, overCapDate } = capAtWholeDate(filingBatch, scanCap);
458
- if (filingBatch.length === 0 && !dateWindow) {
593
+ // A window holding only Form 4s filed as another issuer's owner is a success that says
594
+ // so, not a miss (#157, #265).
595
+ if (filingBatch.length === 0 && otherIssuerRows.length === 0 && !dateWindow) {
459
596
  throw ctx.fail('no_filings_found', issuerRows > 0
460
597
  ? `No Form 4 in the recent filings of '${input.company}' names it as a reporting owner; ${issuerFilingsNote(issuerRows)}`
461
598
  : `No Form 4 filings found for '${input.company}'.`);
@@ -464,7 +601,10 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
464
601
  // name its submissions document carries, already read (#260).
465
602
  const companyName = match.name ?? submissions.name;
466
603
  const transactions = [];
467
- let filingsScanned = 0;
604
+ /** The filings whose rows this call reads, for pairing each 4/A with its Form 4 (#267). */
605
+ const scanned = [];
606
+ /** Form 4 documents read, the canvas floor's measure; `filings_scanned` adds the rows skipped unread. */
607
+ let filingsRead = 0;
468
608
  let filingsOtherIssuer = 0;
469
609
  /** Filings the scan reached, and the filing date of the last — the oldest, since filings run newest first. */
470
610
  let reached = 0;
@@ -473,7 +613,7 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
473
613
  // Whole filing dates only: once limit and the floor are in hand, stop where the
474
614
  // next date begins, so filed_before the day before resumes without a gap (#261).
475
615
  if (transactions.length >= limit &&
476
- filingsScanned >= scanFloor &&
616
+ filingsRead >= scanFloor &&
477
617
  filing.filingDate !== scannedThrough) {
478
618
  break;
479
619
  }
@@ -484,7 +624,7 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
484
624
  const xmlText = await api.tryGetFilingDocument(match.cik, filing.accessionNumber, docName, scope);
485
625
  if (!xmlText)
486
626
  continue;
487
- filingsScanned++;
627
+ filingsRead++;
488
628
  let parsed;
489
629
  try {
490
630
  parsed = parseForm4Xml(xmlText);
@@ -496,15 +636,18 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
496
636
  });
497
637
  continue;
498
638
  }
499
- // The submissions feed also lists Form 4s this company filed as a reporting
500
- // owner of another issuer — that issuer's insider activity, not this one's (#157),
501
- // and under `reporting_owner` the very filings the call reads (#260).
639
+ // A Form 4 this company filed as a reporting owner of another issuer is that issuer's
640
+ // insider activity, not this one's (#157), and under `reporting_owner` the very filing
641
+ // the call reads (#260). The feed's file number skipped most unread; this drops one it
642
+ // lists under none or the company's own (#265).
502
643
  if (!ownerRole && parsed.issuer_cik && !sameCik(parsed.issuer_cik, match.cik)) {
503
644
  filingsOtherIssuer++;
504
645
  continue;
505
646
  }
506
647
  // The row's person is the first reporting owner listed — under `reporting_owner`,
507
- // the one carrying this filer's CIK, since a joint filing lists several (#260).
648
+ // the one carrying this filer's CIK, since a joint filing lists several (#260). The
649
+ // others ride on every row as joint filers: the XML ties no transaction to one owner,
650
+ // so a row per owner would multiply each trade by the owner count (#264).
508
651
  const primaryOwner = ownerRole
509
652
  ? parsed.reporting_owners.find((owner) => sameCik(owner.cik, match.cik))
510
653
  : parsed.reporting_owners[0];
@@ -515,7 +658,14 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
515
658
  continue;
516
659
  }
517
660
  const personName = primaryOwner?.name ?? 'Unknown';
661
+ const personCik = primaryOwner && paddedCik(primaryOwner.cik);
518
662
  const relationship = primaryOwner ? ownerRelationship(primaryOwner) : 'Unknown';
663
+ const jointFilers = parsed.reporting_owners
664
+ .filter((owner) => owner !== primaryOwner)
665
+ .map((owner) => {
666
+ const cik = paddedCik(owner.cik);
667
+ return { name: owner.name, ...(cik && { cik }), relationship: ownerRelationship(owner) };
668
+ });
519
669
  const rowIssuer = ownerRole
520
670
  ? {
521
671
  ...(parsed.issuer_cik && { issuer_cik: parsed.issuer_cik.padStart(10, '0') }),
@@ -523,6 +673,13 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
523
673
  ...(parsed.issuer_ticker && { issuer_ticker: parsed.issuer_ticker }),
524
674
  }
525
675
  : {};
676
+ scanned.push({
677
+ accession: filing.accessionNumber,
678
+ filingDate: filing.filingDate,
679
+ form: filing.form,
680
+ parsed,
681
+ });
682
+ const amendsDate = filing.form === '4/A' ? parsed.date_of_original_submission : undefined;
526
683
  // Collect every matching transaction — the full set backs the canvas; the
527
684
  // inline response is sliced to `limit` after the scan completes.
528
685
  for (const tx of parsed.transactions) {
@@ -536,8 +693,12 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
536
693
  filing_date: filing.filingDate,
537
694
  period_of_report: parsed.period_of_report,
538
695
  accession_number: filing.accessionNumber,
696
+ form: filing.form,
697
+ ...(amendsDate && { amends_filing_date: amendsDate }),
539
698
  reporting_person: personName,
699
+ ...(personCik && { reporting_person_cik: personCik }),
540
700
  relationship,
701
+ ...(jointFilers.length > 0 && { joint_filers: jointFilers }),
541
702
  ...rowIssuer,
542
703
  security_title: tx.security_title,
543
704
  transaction_date: tx.transaction_date,
@@ -553,13 +714,33 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
553
714
  });
554
715
  }
555
716
  }
717
+ // A row a 4/A in the scan restates is superseded: it names that 4/A, so a net-activity
718
+ // sum can leave it out and count the trade once, as corrected (#267).
719
+ const amendments = pairAmendments(scanned);
720
+ const pairOf = new Map(amendments.pairs.map((pair) => [pair.original, pair]));
721
+ for (const row of transactions) {
722
+ const pair = pairOf.get(row.accession_number);
723
+ if (pair?.restated.has(rowKey(row)))
724
+ row.amended_by = pair.amendment;
725
+ }
726
+ // The rows skipped as another issuer's that the scan passed count as scanned and as
727
+ // naming another issuer (#265): those filed on or after the oldest filing read, or every
728
+ // one when the scan read all of the company's own.
729
+ const stoppedAt = reached < filingBatch.length ? scannedThrough : undefined;
730
+ const passed = stoppedAt
731
+ ? otherIssuerRows.filter((row) => row.filingDate >= stoppedAt)
732
+ : otherIssuerRows;
733
+ const filingsScanned = filingsRead + passed.length;
734
+ filingsOtherIssuer += passed.length;
735
+ /** The oldest Form 4 the scan reached, read or passed. */
736
+ const historyThrough = passed.reduce((oldest, row) => (oldest && oldest <= row.filingDate ? oldest : row.filingDate), scannedThrough);
556
737
  // Form 4 filings past those read, and the filed_before that reaches them (#261). The
557
738
  // scan read whole filing dates, so the day before the oldest one resumes it without a
558
739
  // gap or a repeat; a date it could not finish, or an archive walk the page cap cut
559
740
  // short, resumes on that date instead, and the rows read from it come back again.
560
741
  let continuation;
561
- if (scannedThrough) {
562
- const through = scannedThrough;
742
+ if (historyThrough) {
743
+ const through = historyThrough;
563
744
  if (overCapDate) {
564
745
  continuation =
565
746
  scanCap < INSIDER_FILING_SCAN_CAP
@@ -584,7 +765,7 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
584
765
  const companyText = escapeMarkdownInline(input.company);
585
766
  // `ctx.enrich.notice` is last-wins, so the continuation closes whichever notice is set.
586
767
  const continuationTail = continuation ? ` ${continuation}` : '';
587
- if (windowText && filingBatch.length === 0) {
768
+ if (windowText && filingBatch.length === 0 && otherIssuerRows.length === 0) {
588
769
  // The walk runs newest first, so only an earlier upper bound reaches older filings.
589
770
  const walkNote = walk?.truncated ? ` ${archiveCapNote(walk)}` : '';
590
771
  const eraNote = filedBefore && filedBefore < STRUCTURED_FORM4_START
@@ -634,7 +815,9 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
634
815
  issuer_ticker: ownerRole ? (t.issuer_ticker ?? null) : (issuerTicker ?? null),
635
816
  issuer_name: ownerRole ? (t.issuer_name ?? null) : companyName,
636
817
  reporting_person: t.reporting_person,
818
+ reporting_person_cik: t.reporting_person_cik ?? null,
637
819
  relationship: t.relationship,
820
+ joint_filers: t.joint_filers?.map((owner) => jointFilerLabel(owner)).join('; ') ?? null,
638
821
  security_title: t.security_title,
639
822
  transaction_date: t.transaction_date ?? null,
640
823
  filing_date: t.filing_date,
@@ -649,6 +832,9 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
649
832
  ownership_type: t.ownership_type ?? null,
650
833
  ownership_nature: t.ownership_nature ?? null,
651
834
  accession_number: t.accession_number,
835
+ form: t.form,
836
+ amends_filing_date: t.amends_filing_date ?? null,
837
+ amended_by: t.amended_by ?? null,
652
838
  })),
653
839
  sourceTool: 'secedgar_get_insider_transactions',
654
840
  queryParams: {
@@ -678,11 +864,12 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
678
864
  (!dateWindow && submissions.filings.files.length > 0),
679
865
  })
680
866
  : continuation;
681
- if (transactions.length > 0) {
867
+ if (transactions.length > 0 && scannedThrough) {
682
868
  // Filings naming another issuer are this filer's own trades, which the other role reads (#260).
683
869
  const closing = [
684
870
  filingsOtherIssuer > 0 &&
685
871
  otherIssuerSentence(filingsOtherIssuer, `the ${filingsScanned} Form 4 filings scanned`),
872
+ ...amendmentSentences(amendments, new Set(transactions.map((row) => row.accession_number)), { scannedThrough, filedAfter, filedBefore }),
686
873
  wayOn,
687
874
  ];
688
875
  const sentences = (...parts) => parts.filter(Boolean).join(' ');
@@ -707,6 +894,7 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
707
894
  cik: match.cik,
708
895
  role: input.role,
709
896
  filingsScanned,
897
+ filingsRead,
710
898
  filingsOtherIssuer,
711
899
  transactionCount: transactions.length,
712
900
  returned: inlineTransactions.length,
@@ -721,7 +909,7 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
721
909
  transactions: inlineTransactions,
722
910
  filings_scanned: filingsScanned,
723
911
  filings_other_issuer: filingsOtherIssuer,
724
- ...(scannedThrough && { history_scanned_through: scannedThrough }),
912
+ ...(historyThrough && { history_scanned_through: historyThrough }),
725
913
  dataset,
726
914
  };
727
915
  },
@@ -759,11 +947,19 @@ export const getInsiderTransactionsTool = tool('secedgar_get_insider_transaction
759
947
  : tx.ownership_type
760
948
  ? ` (${tx.ownership_type})`
761
949
  : '';
762
- lines.push(`**${escapeMarkdownInline(tx.reporting_person)}** (${escapeMarkdownInline(tx.relationship)})${issuerClause(tx)} — ${tx.transaction_type}${derivStr}`);
950
+ const person = { cik: tx.reporting_person_cik, relationship: tx.relationship };
951
+ lines.push(`**${escapeMarkdownInline(tx.reporting_person)}** ${ownerDetail(person, escapeMarkdownInline)}${issuerClause(tx)} — ${tx.transaction_type}${derivStr}`);
952
+ if (tx.joint_filers) {
953
+ lines.push(`Joint filers: ${tx.joint_filers.map((owner) => jointFilerLabel(owner, escapeMarkdownInline)).join('; ')}`);
954
+ }
763
955
  const txDate = tx.transaction_date ?? tx.filing_date;
764
956
  const periodStr = tx.period_of_report ? ` | report period: ${tx.period_of_report}` : '';
765
957
  lines.push(`${txDate} | ${escapeMarkdownInline(tx.security_title)} | ${sharesStr} ${priceStr}${ownedStr}${ownershipStr}${periodStr}`);
766
- lines.push(`Code: ${tx.transaction_code} | Filed: ${tx.filing_date} [${tx.accession_number}]`);
958
+ const amendsStr = tx.amends_filing_date
959
+ ? ` | Amends: Form 4 filed ${tx.amends_filing_date}`
960
+ : '';
961
+ const amendedStr = tx.amended_by ? ` | Amended by: ${tx.amended_by}` : '';
962
+ lines.push(`Code: ${tx.transaction_code} | Form ${tx.form} | Filed: ${tx.filing_date} [${tx.accession_number}]${amendsStr}${amendedStr}`);
767
963
  }
768
964
  if (result.history_scanned_through) {
769
965
  lines.push(`\nHistory scanned through: ${result.history_scanned_through}`);