@levitating/tensor-mcp 1.0.0 → 4.4.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 (3) hide show
  1. package/README.md +281 -23
  2. package/dist/index.js +1222 -53
  3. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -6,6 +6,75 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
6
6
 
7
7
  // tools.ts
8
8
  import { z } from "zod";
9
+ var RECORD_TARGET_TYPES = [
10
+ "entity",
11
+ "institution",
12
+ "account",
13
+ "position",
14
+ "asset",
15
+ "transaction"
16
+ ];
17
+ var TODO_LINK_TARGET_TYPES = [
18
+ ...RECORD_TARGET_TYPES,
19
+ "todo",
20
+ "idea",
21
+ "memo"
22
+ ];
23
+ var FILE_ATTACH_TARGET_TYPES = [
24
+ ...RECORD_TARGET_TYPES,
25
+ "todo",
26
+ "idea",
27
+ "memo"
28
+ ];
29
+ var IDEA_LINK_TARGET_TYPES = [
30
+ ...RECORD_TARGET_TYPES,
31
+ "todo",
32
+ "idea",
33
+ "memo"
34
+ ];
35
+ var TODO_STATE_CATEGORIES = [
36
+ "backlog",
37
+ "unstarted",
38
+ "started",
39
+ "completed",
40
+ "canceled"
41
+ ];
42
+ var TODO_LIST_SORTS = ["manual", "created", "updated", "due", "priority"];
43
+ var IDEA_SORT_MODES = ["newest", "oldest", "updated", "title"];
44
+ var FILE_LIST_SORTS = [
45
+ "modified_desc",
46
+ "modified_asc",
47
+ "added_desc",
48
+ "added_asc",
49
+ "name_asc",
50
+ "name_desc",
51
+ "size_desc",
52
+ "size_asc"
53
+ ];
54
+ var SEARCH_RECORD_TYPES_MIRROR = [
55
+ "entity",
56
+ "institution",
57
+ "account",
58
+ "position",
59
+ "asset",
60
+ "transaction",
61
+ "file",
62
+ "todo",
63
+ "idea",
64
+ "memo"
65
+ ];
66
+ var IDEA_KINDS = ["link", "note", "image", "video"];
67
+ function tiptapDocJson(text) {
68
+ const content = text.split(/\r?\n/).map(
69
+ (line) => line.length > 0 ? { type: "paragraph", content: [{ type: "text", text: line }] } : { type: "paragraph" }
70
+ );
71
+ return JSON.stringify({ type: "doc", content });
72
+ }
73
+ function numListParam(value) {
74
+ if (value == null) return void 0;
75
+ const list = Array.isArray(value) ? value : [value];
76
+ return list.length ? list.join(",") : void 0;
77
+ }
9
78
  function registerAllTools(server2, api) {
10
79
  server2.tool(
11
80
  "list_entities",
@@ -182,12 +251,23 @@ function registerAllTools(server2, api) {
182
251
  );
183
252
  server2.tool(
184
253
  "list_assets",
185
- "List all assets (stocks, bonds, crypto, real estate, etc.)",
186
- { limit: z.number().optional(), offset: z.number().optional() },
187
- async ({ limit, offset }) => {
254
+ "List assets (stocks, bonds, crypto, real estate, etc.). Filter server-side rather than pulling the whole catalog.",
255
+ {
256
+ limit: z.number().optional(),
257
+ offset: z.number().optional(),
258
+ assetClass: z.string().optional().describe("Only assets in this asset class"),
259
+ symbol: z.string().optional().describe("Exact display symbol match (case-insensitive)"),
260
+ linked: z.boolean().optional().describe("true = only assets linked to a price provider; false = only unlinked ones"),
261
+ q: z.string().optional().describe("Case-insensitive substring across name and symbol")
262
+ },
263
+ async ({ limit, offset, assetClass, symbol, linked, q }) => {
188
264
  const params = new URLSearchParams();
189
265
  if (limit) params.set("limit", String(limit));
190
266
  if (offset) params.set("offset", String(offset));
267
+ if (assetClass) params.set("assetClass", assetClass);
268
+ if (symbol) params.set("symbol", symbol);
269
+ if (linked !== void 0) params.set("linked", String(linked));
270
+ if (q) params.set("q", q);
191
271
  const qs = params.toString();
192
272
  const data = await api("GET", `/api/assets${qs ? `?${qs}` : ""}`);
193
273
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
@@ -204,34 +284,48 @@ function registerAllTools(server2, api) {
204
284
  );
205
285
  server2.tool(
206
286
  "create_asset",
207
- "Create a new asset (stock, bond, crypto, real estate, etc.)",
287
+ "Create a new asset (stock, bond, crypto, real estate, etc.). To make an asset price itself automatically, set tickerSymbol to a market quote symbol \u2014 find one first with search_market_quotes, and pass verifyQuote+syncPrice so a bad symbol fails here instead of becoming an asset that silently never prices.",
208
288
  {
209
289
  name: z.string().describe("Asset name"),
210
290
  assetClass: z.string().describe("Asset class key (e.g. 'Equity', 'Bond', 'Crypto', 'Real Estate'). Must match an existing asset-classes row."),
211
- symbol: z.string().optional().describe("Ticker/symbol (e.g. 'AAPL', 'BTC')"),
291
+ symbol: z.string().optional().describe("Display ticker shown to humans (e.g. 'AAPL', 'BRK.B'). Cosmetic \u2014 this is NOT what prices the asset."),
292
+ tickerSymbol: z.string().optional().describe("Price-provider symbol used for sync: a Yahoo Finance ticker (AAPL, BRK-B, BTC-USD) or CG:<coingecko-id> for long-tail crypto. Get this from search_market_quotes \u2014 do not guess it. The API also accepts and returns this under the older name fmpSymbol; the two are the same field."),
212
293
  defaultCurrency: z.string().optional().describe("Default currency code. Default: USD"),
213
294
  currentPrice: z.number().optional().describe("Current price per unit as a number"),
214
- notes: z.string().optional()
295
+ notes: z.string().optional(),
296
+ verifyQuote: z.boolean().optional().describe("Resolve tickerSymbol with the price provider before saving; rejects the create if it does not resolve. Recommended whenever tickerSymbol is set."),
297
+ syncPrice: z.boolean().optional().describe("Immediately pull the current quote after creating, so the asset arrives already priced. The outcome is returned under `priceSync`.")
215
298
  },
216
- async (params) => {
217
- const data = await api("POST", "/api/assets", params);
299
+ async ({ verifyQuote, syncPrice, ...body }) => {
300
+ const params = new URLSearchParams();
301
+ if (verifyQuote) params.set("verifyQuote", "true");
302
+ if (syncPrice) params.set("syncPrice", "true");
303
+ const qs = params.toString();
304
+ const data = await api("POST", `/api/assets${qs ? `?${qs}` : ""}`, body);
218
305
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
219
306
  }
220
307
  );
221
308
  server2.tool(
222
309
  "update_asset",
223
- "Update an existing asset (partial update)",
310
+ "Update an existing asset (partial update). Set tickerSymbol to link or relink the asset to a market quote.",
224
311
  {
225
312
  id: z.number().describe("Asset ID to update"),
226
313
  name: z.string().optional(),
227
314
  assetClass: z.string().optional(),
228
- symbol: z.string().optional(),
315
+ symbol: z.string().optional().describe("Display ticker. Cosmetic \u2014 use tickerSymbol to control pricing."),
316
+ tickerSymbol: z.string().optional().describe("Price-provider symbol (Yahoo ticker or CG:<coingecko-id>). Find one with search_market_quotes. Omit to keep the existing price link. Equivalent to the older field name fmpSymbol."),
229
317
  defaultCurrency: z.string().optional(),
230
318
  currentPrice: z.number().optional(),
231
- notes: z.string().optional()
319
+ notes: z.string().optional(),
320
+ verifyQuote: z.boolean().optional().describe("Resolve tickerSymbol with the provider before saving; rejects the update if it does not resolve."),
321
+ syncPrice: z.boolean().optional().describe("Pull the current quote right after saving. Outcome returned under `priceSync`.")
232
322
  },
233
- async ({ id, ...body }) => {
234
- const data = await api("PATCH", `/api/assets/${id}`, body);
323
+ async ({ id, verifyQuote, syncPrice, ...body }) => {
324
+ const params = new URLSearchParams();
325
+ if (verifyQuote) params.set("verifyQuote", "true");
326
+ if (syncPrice) params.set("syncPrice", "true");
327
+ const qs = params.toString();
328
+ const data = await api("PATCH", `/api/assets/${id}${qs ? `?${qs}` : ""}`, body);
235
329
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
236
330
  }
237
331
  );
@@ -268,7 +362,8 @@ function registerAllTools(server2, api) {
268
362
  id: z.number().describe("Asset ID"),
269
363
  price: z.number().describe("New price value"),
270
364
  memo: z.string().optional().describe("Price update memo"),
271
- source: z.string().optional().describe("Price source (e.g. manual, bloomberg)")
365
+ source: z.string().optional().describe("Price source (e.g. manual, bloomberg)"),
366
+ confirm: z.boolean().optional().describe("true = value verified unchanged; writes 'confirm' valuation events instead of 'reprice' so routine check-ins don't flood history")
272
367
  },
273
368
  async ({ id, ...body }) => {
274
369
  const data = await api("POST", `/api/assets/${id}/prices`, body);
@@ -277,12 +372,29 @@ function registerAllTools(server2, api) {
277
372
  );
278
373
  server2.tool(
279
374
  "list_positions",
280
- "List all positions (holdings) across accounts",
281
- { limit: z.number().optional(), offset: z.number().optional() },
282
- async ({ limit, offset }) => {
375
+ "List positions (holdings) across accounts. Filter server-side instead of pulling every row \u2014 and for totals like net worth use get_portfolio_summary rather than summing these yourself.",
376
+ {
377
+ limit: z.number().optional(),
378
+ offset: z.number().optional(),
379
+ entityId: z.number().optional().describe("Only positions held by this entity"),
380
+ accountId: z.number().optional().describe("Only positions in this custody account"),
381
+ assetId: z.number().optional().describe("Only positions in this asset"),
382
+ assetClass: z.string().optional().describe("Only positions in this asset class"),
383
+ status: z.string().optional().describe("'active' or 'closed'. Omit for both."),
384
+ liability: z.boolean().optional().describe("true = only liabilities, false = only assets"),
385
+ updatedSince: z.number().optional().describe("Only positions updated at/after this epoch-ms timestamp")
386
+ },
387
+ async ({ limit, offset, entityId, accountId, assetId, assetClass, status, liability, updatedSince }) => {
283
388
  const params = new URLSearchParams();
284
389
  if (limit) params.set("limit", String(limit));
285
390
  if (offset) params.set("offset", String(offset));
391
+ if (entityId) params.set("entityId", String(entityId));
392
+ if (accountId) params.set("accountId", String(accountId));
393
+ if (assetId) params.set("assetId", String(assetId));
394
+ if (assetClass) params.set("assetClass", assetClass);
395
+ if (status) params.set("status", status);
396
+ if (liability !== void 0) params.set("liability", String(liability));
397
+ if (updatedSince) params.set("updatedSince", String(updatedSince));
286
398
  const qs = params.toString();
287
399
  const data = await api("GET", `/api/positions${qs ? `?${qs}` : ""}`);
288
400
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
@@ -290,18 +402,21 @@ function registerAllTools(server2, api) {
290
402
  );
291
403
  server2.tool(
292
404
  "create_position",
293
- "Create a new position (a holding of an asset, owned by an entity, optionally in an account)",
405
+ "Create a new position (a holding of an asset, owned by an entity, optionally in an account). Two shapes: a UNITIZED holding (shares/units \u2014 send quantity + averageCost) or a fund CAPITAL ACCOUNT (a fund LP interest, which has no units because the GP reports a balance \u2014 send costBasis instead). `costBasis` is the ONLY switch that makes a capital account; there is no inference from a missing quantity. Get the shape right at open: create_transaction refuses unitized types on a capital account, and the fund performance figures (paid-in, DPI/TVPI, IRR) exist only for one.",
294
406
  {
295
407
  entityId: z.number().describe("Owner entity ID"),
296
408
  label: z.string().describe("Display label for this position (e.g. 'AAPL @ Schwab', 'Brooklyn rental')"),
297
409
  assetClass: z.string().describe("Asset class key (e.g. 'Equity', 'Real Estate', 'Cash')"),
298
- currentValue: z.number().describe("Current value of the position (in `currency`). Negative for liabilities."),
410
+ currentValue: z.number().describe("Current value of the position (in `currency`). Negative for liabilities. For a capital account this is the GP's latest reported NAV."),
299
411
  accountId: z.number().optional().describe("Optional account ID this position lives in"),
300
- assetId: z.number().optional().describe("Optional asset ID this position references"),
412
+ assetId: z.number().optional().describe("Optional asset ID this position references. Ignored on a capital account: a fund has no units for a price to multiply, so a linked asset would rewrite its NAV to 0 on the next price sync."),
301
413
  liability: z.boolean().optional().describe("True if this is a liability (mortgage, loan). Default: false"),
302
- quantity: z.number().optional().describe("Quantity held (e.g. shares, units)"),
303
- currentPrice: z.number().optional().describe("Current price per unit"),
304
- averageCost: z.number().optional().describe("Average cost per unit"),
414
+ quantity: z.number().optional().describe("Quantity held (e.g. shares, units). MUST be omitted when costBasis is set \u2014 a capital account has no units, and the server nulls it rather than storing a second, contradictory truth."),
415
+ currentPrice: z.number().optional().describe("Current price per unit. Same rule as quantity: omit it when costBasis is set."),
416
+ averageCost: z.number().optional().describe("Average cost per unit. Same rule as quantity: omit it when costBasis is set \u2014 cost on a capital account is carried whole in costBasis, not per-unit."),
417
+ costBasis: z.number().optional().describe(
418
+ "Capital-account cost basis: total paid-in capital, less anything already returned as capital. Setting this (0 counts \u2014 a fund committed but not yet drawn) marks the position as a fund LP interest, and quantity/currentPrice/averageCost/assetId must then be left unset. Thereafter the ledger moves it: capital_call and contribution raise it, return_of_capital and recallable_distribution lower it. Omit entirely for an ordinary unitized holding."
419
+ ),
305
420
  realizedGain: z.number().optional().describe("Realized gain to date. Default: 0"),
306
421
  status: z.string().optional().describe("'active' or 'closed'. Default: 'active'"),
307
422
  currency: z.string().optional().describe("Currency code. Default: USD"),
@@ -339,7 +454,7 @@ function registerAllTools(server2, api) {
339
454
  );
340
455
  server2.tool(
341
456
  "delete_position",
342
- "Delete a position",
457
+ "PERMANENTLY delete a position and everything hanging off it, in one transaction and with no undo: its ENTIRE transaction ledger, its whole valuation-event history, its loan or fund terms, its relations to other positions, and its file/todo attachments. There is no soft delete and no restore. Deleting is NOT how you record an exit \u2014 a sold-out holding should be closed with sell_all_position, which keeps the history and the realized gain. Reach for this only to remove a position that should never have existed, and confirm with the user first.",
343
458
  { id: z.number().describe("Position ID to delete") },
344
459
  async ({ id }) => {
345
460
  const data = await api("DELETE", `/api/positions/${id}`);
@@ -355,7 +470,8 @@ function registerAllTools(server2, api) {
355
470
  amount: z.number().optional().describe("Total sale amount"),
356
471
  fees: z.number().optional().describe("Transaction fees"),
357
472
  memo: z.string().optional().describe("Sale memo"),
358
- quantity: z.number().optional().describe("Quantity to sell (defaults to all)")
473
+ quantity: z.number().optional().describe("Quantity to sell (defaults to all)"),
474
+ timestamp: z.number().optional().describe("Epoch ms backdate for the close; defaults to now")
359
475
  },
360
476
  async ({ id, ...body }) => {
361
477
  const data = await api("POST", `/api/positions/${id}/sell-all`, body);
@@ -428,12 +544,23 @@ function registerAllTools(server2, api) {
428
544
  );
429
545
  server2.tool(
430
546
  "list_transactions",
431
- "List all transactions (buys, sells, dividends, fees, etc.)",
432
- { limit: z.number().optional(), offset: z.number().optional() },
433
- async ({ limit, offset }) => {
547
+ "List transactions (buys, sells, dividends, fees, etc.). Filter by position or date range server-side.",
548
+ {
549
+ limit: z.number().optional(),
550
+ offset: z.number().optional(),
551
+ positionId: z.number().optional().describe("Only transactions against this position"),
552
+ transactionType: z.string().optional().describe("Only this transaction type (buy, sell, dividend, ...)"),
553
+ since: z.number().optional().describe("Only transactions at/after this epoch-ms timestamp"),
554
+ until: z.number().optional().describe("Only transactions at/before this epoch-ms timestamp")
555
+ },
556
+ async ({ limit, offset, positionId, transactionType, since, until }) => {
434
557
  const params = new URLSearchParams();
435
558
  if (limit) params.set("limit", String(limit));
436
559
  if (offset) params.set("offset", String(offset));
560
+ if (positionId) params.set("positionId", String(positionId));
561
+ if (transactionType) params.set("transactionType", transactionType);
562
+ if (since) params.set("since", String(since));
563
+ if (until) params.set("until", String(until));
437
564
  const qs = params.toString();
438
565
  const data = await api("GET", `/api/transactions${qs ? `?${qs}` : ""}`);
439
566
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
@@ -441,15 +568,27 @@ function registerAllTools(server2, api) {
441
568
  );
442
569
  server2.tool(
443
570
  "create_transaction",
444
- "Create a new transaction (buy, sell, dividend, fee, etc.)",
571
+ "Append a transaction to a position's ledger (buy, sell, dividend, fee, etc.). THE LEDGER IS APPEND-ONLY AND THIS WRITE IS PERMANENT. There is no way to edit or delete a transaction \u2014 position state is a non-invertible fold over the ledger, so a destructive edit would corrupt cost basis. A mistake is corrected by posting a COMPENSATING entry of the opposite type (a wrong buy is offset by a sell, a wrong capital_call by a return_of_capital), which leaves both rows visible in history. Get it right the first time, and confirm anything you are unsure of with the user before posting.",
445
572
  {
446
573
  positionId: z.number().describe("Position ID this transaction belongs to"),
447
- transactionType: z.string().describe("Transaction type key (e.g. 'buy', 'sell', 'dividend', 'fee', 'distribution')"),
448
- quantity: z.number().describe("Quantity (use 0 for cash transactions like dividends or fees)"),
449
- amount: z.number().describe("Total cash amount of the transaction. Positive for inflows, negative for outflows."),
450
- price: z.number().optional().describe("Price per unit (for buys/sells)"),
451
- fees: z.number().optional().describe("Fee amount. Default: 0"),
452
- timestamp: z.number().optional().describe("Transaction time as epoch milliseconds. Default: now."),
574
+ // This string is what an LLM reads to pick a type. When the loan types
575
+ // were missing from it, agents reached for `sell` to record a repayment
576
+ // and booked a phantom gain. mcp-server is a standalone npm package and
577
+ // deliberately does not import shared/schema (it would drag zod+drizzle
578
+ // into the published bundle), so the list is a literal — pinned against
579
+ // TRANSACTION_TYPE_KEYS by an assertion in script/smoke-clerk-api-keys.ts
580
+ // so it can never silently drift again.
581
+ transactionType: z.string().describe("Ledger type. One of: buy, sell, deposit, withdrawal, interest, dividend, transfer_in, transfer_out, contribution, capital_call, distribution, return_of_capital, recallable_distribution, management_fee, write_off, borrow, repay, fee, loan_accrual, repayment_received. THIS FIELD, NOT THE SIGN OF ANY NUMBER, IS WHAT SETS DIRECTION. buy/contribution/capital_call update cost basis; sell/distribution realize gain; dividend books income to realized gain without moving units; fee is logged with no P/L impact. For loans YOU made: loan_accrual adds PIK interest to the balance (post amount 0), repayment_received records the borrower paying you back (return of capital, no gain) \u2014 do NOT use sell/withdrawal for those. For fund LP interests (capital accounts, which have no units \u2014 post quantity 0 and put the money in amount): capital_call/contribution add paid-in capital, return_of_capital REDUCES cost basis and books no gain (use this, not distribution, for a GP returning your capital \u2014 distribution would invent a profit), recallable_distribution does the same but also restores unfunded commitment, distribution books profit, management_fee records a fee billed outside the fund (never record fees already netted inside the reported NAV \u2014 that double-counts them), write_off closes an UNDER-WATER wind-up: the fund returned less than it took, so the basis it could never return becomes a realized loss. Its AMOUNT IS DERIVED from the remaining cost basis and whatever you post is ignored \u2014 post 0. Use it only after the final return_of_capital, and only when the fund is genuinely finished; it zeroes the NAV and closes the position. It is not a distribution and never counts toward DPI or TVPI. A CAPITAL ACCOUNT ACCEPTS ONLY THOSE FUND TYPES. Posting a unitized type (buy, sell, deposit, borrow, \u2026) against a position that has a costBasis is REJECTED with a 400, because a fund has no units: a `buy 10 @ 100` would otherwise overwrite a GP-reported NAV of 1.4M with 1,000, and a `sell` would close the position outright with nothing in the app able to reopen it."),
582
+ quantity: z.number().describe("Units moved, as a POSITIVE magnitude \u2014 never negative. Direction comes from transactionType (a sell removes what a buy adds). Use 0 for cash and economic events that move no units: dividends, fees, and every capital-account entry."),
583
+ // Was documented as "positive for inflows, negative for outflows", which
584
+ // is not what the server does with it: both the unitized and the
585
+ // capital-account folds take Math.abs(amount). A negative amount was
586
+ // silently absorbed, so an agent following that instruction believed it
587
+ // had recorded an outflow and had in fact recorded an inflow.
588
+ amount: z.number().describe("Total cash that changed hands, as a POSITIVE magnitude. Do NOT signal an outflow with a negative number: the server takes the absolute value and reads direction from transactionType alone, so a negative amount is silently treated as positive rather than reversing the entry. Post 0 for loan_accrual (PIK interest \u2014 no money moves)."),
589
+ price: z.number().optional().describe("Price per unit (for buys/sells). Omit on a capital account, which has no unit price."),
590
+ fees: z.number().optional().describe("Fee amount, positive. Default: 0. Every fee is expensed exactly once: a fee on a capital_call/contribution is CAPITALIZED into cost basis, while a fee on a distribution, return_of_capital, sell or management_fee is expensed against realized gain."),
591
+ timestamp: z.number().optional().describe("Transaction time as epoch milliseconds. Default: now. ENTRIES MUST BE RECORDED IN DATE ORDER: a timestamp earlier than the position's latest activity is REJECTED with a 400, because the running state is folded in insert order and a backdate would silently mis-order the fold. When backfilling history, post oldest first. On a capital account the floor also includes dated NAV marks, so a capital call cannot be slipped in behind a mark that already reflects it."),
453
592
  memo: z.string().optional()
454
593
  },
455
594
  async (params) => {
@@ -682,35 +821,1007 @@ function registerAllTools(server2, api) {
682
821
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
683
822
  }
684
823
  );
824
+ const DATA_UPDATER_OP_TYPES = [
825
+ "asset.upsert",
826
+ "asset_price.record",
827
+ "position.open",
828
+ "transaction.record",
829
+ "account.upsert",
830
+ "entity.upsert"
831
+ ];
832
+ const DATA_APPLY_CONFIRMATION = "APPLY-DATA-UPDATER";
685
833
  server2.tool(
686
834
  "data_dry_run",
687
- "Dry-run a batch data import (validates without applying changes). Returns a preview of what would change.",
835
+ "Step 1 of the two-step batch import flow: validate a batch and preview what would change, WITHOUT writing. The preview is persisted server-side and the response echoes a requestHash \u2014 pass that hash to data_apply to execute the batch. Idempotent: replaying the same batchId with the same payload returns the stored preview; the same batchId with a different payload returns a 409 batch_conflict (pick a new batchId instead). Requires the tensor:data:dry_run scope.",
688
836
  {
837
+ batchId: z.string().describe(
838
+ "Caller-chosen batch identifier, e.g. 'import-2026-08-03-a'. Allowed characters [a-zA-Z0-9_-:.], max 128. Reuse the exact same batchId in data_apply."
839
+ ),
840
+ source: z.string().optional().describe(
841
+ "Optional provenance tag stored in the audit log (e.g. 'mcp', 'csv-import'). Max 64 chars."
842
+ ),
689
843
  operations: z.array(z.object({
690
- action: z.enum(["create", "update", "delete"]).describe("Operation type"),
691
- resource: z.string().describe("Resource type (entity, account, asset, position, transaction, institution, entity-type, role-type, account-type, asset-class)"),
692
- data: z.record(z.unknown()).optional().describe("Resource data for create/update"),
693
- id: z.number().optional().describe("Resource ID for update/delete")
694
- })).describe("Array of operations to preview")
844
+ op: z.enum(DATA_UPDATER_OP_TYPES).describe(
845
+ "Operation type. Required `data` fields per op \u2014 asset.upsert: {name, assetClass, symbol?, fmpSymbol?, defaultCurrency?, currentPrice?, notes?} (fmpSymbol is the market-data ticker \u2014 a Yahoo ticker or CG:<coingecko-id>, NOT a Financial Modeling Prep symbol; the batch API still spells it fmpSymbol, unlike the assets API which also accepts tickerSymbol. Omit it on an update to keep the existing price link, send null to unlink); asset_price.record: {price, assetId|assetSymbol|assetName, asOf? (epoch ms), source?, memo?}; position.open: {label, assetClass, currentValue, entityId|entityName?, accountId|accountName?, assetId|assetSymbol|assetName?, liability?, quantity?, currentPrice?, averageCost?, currency?, notes?}; transaction.record: {transactionType (same canonical keys as create_transaction), quantity, amount, price?, fees?, timestamp? (epoch ms), memo?, and positionId OR accountName/entityName + assetSymbol|assetName}; account.upsert: {name, accountType, entityId|entityName, institution?, currency?, notes?}; entity.upsert: {name, type, jurisdiction?, formedDate?, notes?, showInPortfolio?, tags?}"
846
+ ),
847
+ data: z.record(z.unknown()).describe("Operation payload \u2014 see the per-op field list on `op`. Never include organizationId; org scope comes from auth."),
848
+ clientRef: z.string().optional().describe("Optional caller correlation ID echoed back per-operation in the preview. Max 128 chars.")
849
+ })).min(1).max(500).describe("1-500 typed operations to preview.")
695
850
  },
696
- async ({ operations }) => {
697
- const data = await api("POST", "/api/data/dry-run", { operations });
851
+ async ({ batchId, source, operations }) => {
852
+ const data = await api("POST", "/api/v1/data/dry-run", {
853
+ batchId,
854
+ ...source !== void 0 ? { source } : {},
855
+ operations
856
+ });
698
857
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
699
858
  }
700
859
  );
701
860
  server2.tool(
702
861
  "data_apply",
703
- "Apply a batch data import (creates, updates, or deletes resources). Use data_dry_run first to preview.",
862
+ "Step 2 of the two-step batch import flow: execute a batch previously validated with data_dry_run. This does NOT accept operations \u2014 it replays the persisted dry-run identified by (batchId, requestHash), so the server refuses anything that drifted from the preview. Workflow: call data_dry_run, review the preview (fix any errors/needsClarification by re-running dry-run under a NEW batchId), then call data_apply with the batchId and the requestHash echoed by the dry-run response. Idempotent on (batchId, requestHash): replaying a completed apply returns the stored result. Requires the tensor:data:apply scope.",
704
863
  {
705
- operations: z.array(z.object({
706
- action: z.enum(["create", "update", "delete"]).describe("Operation type"),
707
- resource: z.string().describe("Resource type"),
708
- data: z.record(z.unknown()).optional().describe("Resource data for create/update"),
709
- id: z.number().optional().describe("Resource ID for update/delete")
710
- })).describe("Array of operations to apply")
864
+ batchId: z.string().describe("The batchId of a previously persisted data_dry_run batch."),
865
+ requestHash: z.string().describe("The hex requestHash echoed in that batch's data_dry_run response. Apply is refused if it does not match the persisted batch."),
866
+ confirm: z.literal(DATA_APPLY_CONFIRMATION).describe(
867
+ `Deliberate-intent sentinel. Must be exactly "${DATA_APPLY_CONFIRMATION}".`
868
+ )
869
+ },
870
+ async ({ batchId, requestHash, confirm }) => {
871
+ const data = await api("POST", "/api/v1/data/apply", { batchId, requestHash, confirm });
872
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
873
+ }
874
+ );
875
+ server2.tool(
876
+ "get_portfolio_summary",
877
+ "Net worth, total assets, total liabilities, cost basis and unrealized P/L for the organization, computed server-side in USD \u2014 optionally broken down by entity, account, asset class or currency. USE THIS instead of listing positions and adding them up: the underlying math has real subtleties (a position's stored value is a snapshot rather than a market value, liabilities are sign-mirrored, cost basis has a fallback that must not apply to priced positions) and this endpoint folds exactly the same chain the Tensor dashboard shows. The `coverage` field reports how much of the portfolio the numbers actually cover \u2014 check it before quoting a total as exact.",
878
+ {
879
+ groupBy: z.string().optional().describe("Comma-separated breakdowns: entity, account, assetClass, currency. Omit for headline totals only."),
880
+ scope: z.enum(["dashboard", "all"]).optional().describe("'dashboard' (default) counts only entities marked for portfolio display, matching the Tensor dashboard. 'all' counts every entity."),
881
+ includeClosed: z.boolean().optional().describe("Include closed positions. Default false."),
882
+ entityId: z.number().optional().describe("Restrict to one entity"),
883
+ accountId: z.number().optional().describe("Restrict to one custody account"),
884
+ assetClass: z.string().optional().describe("Restrict to one asset class")
885
+ },
886
+ async ({ groupBy, scope, includeClosed, entityId, accountId, assetClass }) => {
887
+ const params = new URLSearchParams();
888
+ if (groupBy) params.set("groupBy", groupBy);
889
+ if (scope) params.set("scope", scope);
890
+ if (includeClosed) params.set("includeClosed", "true");
891
+ if (entityId) params.set("entityId", String(entityId));
892
+ if (accountId) params.set("accountId", String(accountId));
893
+ if (assetClass) params.set("assetClass", assetClass);
894
+ const qs = params.toString();
895
+ const data = await api("GET", `/api/v1/portfolio/summary${qs ? `?${qs}` : ""}`);
896
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
897
+ }
898
+ );
899
+ server2.tool(
900
+ "search_market_quotes",
901
+ "Search the price providers (Yahoo Finance for listed instruments, CoinGecko for crypto) for market quotes matching a free-text query. Returns candidate symbols with their name and exchange. The `symbol` of the result you pick is what goes into an asset's tickerSymbol field (returned as both tickerSymbol and fmpSymbol) to make it price automatically. Always search rather than guessing a ticker \u2014 exchange suffixes and crypto ids are not predictable.",
902
+ {
903
+ q: z.string().describe("Free-text query \u2014 a company name, ticker, or coin name"),
904
+ limit: z.number().optional().describe("Max candidates to return. Default 10, max 25.")
905
+ },
906
+ async ({ q, limit }) => {
907
+ const params = new URLSearchParams({ q });
908
+ if (limit) params.set("limit", String(limit));
909
+ const data = await api("GET", `/api/v1/prices/search?${params.toString()}`);
910
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
911
+ }
912
+ );
913
+ server2.tool(
914
+ "verify_market_quote",
915
+ "Resolve a single market-quote symbol to a live price WITHOUT writing anything. Use this to confirm a symbol is real before linking it to an asset. Returns `corrected: true` when the provider answered on a different spelling than the one asked for \u2014 store the returned `symbol`, not the one you sent.",
916
+ { symbol: z.string().describe("Provider symbol to check, e.g. 'BRK-B', 'BTC-USD', or 'CG:official-trump'") },
917
+ async ({ symbol }) => {
918
+ const data = await api("GET", `/api/v1/prices/quote?symbol=${encodeURIComponent(symbol)}`);
919
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
920
+ }
921
+ );
922
+ server2.tool(
923
+ "sync_prices",
924
+ "Trigger a price sync: fetch current quotes for the organization's linked assets and record them, revaluing every position that holds them. Omit assetIds to sync the whole catalog, or pass a subset. This WRITES \u2014 each synced asset gets a price-history row and its positions are repriced. The result reports what synced, what was skipped for having no symbol, and per-symbol failure reasons.",
925
+ {
926
+ assetIds: z.array(z.number()).optional().describe("Only sync these asset IDs. Omit to sync every linked asset in the organization.")
927
+ },
928
+ async ({ assetIds }) => {
929
+ const data = await api("POST", "/api/v1/prices/sync", assetIds ? { assetIds } : {});
930
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
931
+ }
932
+ );
933
+ server2.tool(
934
+ "sync_asset_price",
935
+ "Trigger a price sync for one asset by ID. Fails if the asset has no price-provider symbol linked. Use sync_prices for bulk.",
936
+ { id: z.number().describe("Asset ID to reprice") },
937
+ async ({ id }) => {
938
+ const data = await api("POST", `/api/v1/prices/sync/${id}`);
939
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
940
+ }
941
+ );
942
+ server2.tool(
943
+ "list_changes",
944
+ "What changed in this organization's data since a timestamp \u2014 creates, updates AND deletes, across both the CRUD routes and applied data batches. Use this to catch up incrementally instead of re-listing every table. Check `coverage.complete`: when false, the requested `since` predates the audit history and the delta cannot be trusted \u2014 do a full read instead. Resume the next poll from the returned `until`.",
945
+ {
946
+ since: z.number().optional().describe("Epoch-ms lower bound (exclusive). Omit or 0 for everything on record."),
947
+ limit: z.number().optional().describe("Max changes per page. Default 500."),
948
+ resourceType: z.string().optional().describe("Only changes to this resource type, e.g. 'position', 'asset', 'entity'")
949
+ },
950
+ async ({ since, limit, resourceType }) => {
951
+ const params = new URLSearchParams();
952
+ if (since) params.set("since", String(since));
953
+ if (limit) params.set("limit", String(limit));
954
+ if (resourceType) params.set("resourceType", resourceType);
955
+ const qs = params.toString();
956
+ const data = await api("GET", `/api/v1/changes${qs ? `?${qs}` : ""}`);
957
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
958
+ }
959
+ );
960
+ server2.tool(
961
+ "search_records",
962
+ "Site-wide ranked search across every record type at once \u2014 entities, institutions, accounts, positions, assets, transactions, files, todos and ideas. Reference ids resolve directly: 'TSK-12' (todo), 'AS002' (asset), 'T042' (transaction). Lanes are scope-gated per key: each record type requires that domain's read scope (tensor:portfolio:read for the five ledger types, reference:read for institutions, files/todos/ideas:read for theirs). Memos are the one record type NO key reaches: the lane exists and no scope opens it, because memos are session-only. Lanes the key does not cover are silently omitted \u2014 the result is your slice of the org, not evidence the rest is empty \u2014 and a key covering no lane at all gets 403. Empty q returns no hits. Not for market tickers: that is search_market_quotes.",
963
+ {
964
+ q: z.string().describe("The query. Title, body and reference-id lanes, one ranking; short and literal works best."),
965
+ types: z.array(z.enum(SEARCH_RECORD_TYPES_MIRROR)).optional().describe("Restrict to these record types. Omit for all \u2014 transactions are excluded from the default set unless the query is a T-ref or you name them here explicitly. 'memo' is spelled here because it is one of Tensor's record types, not because a key can search it: naming it adds nothing, and naming it alone is the no-lane 403."),
966
+ limit: z.number().optional().describe("Max hits. Default 20, capped server-side."),
967
+ includeArchived: z.boolean().optional().describe("Include archived rows. Memos are the only lane left with an archive, and no key reaches that lane \u2014 so this flag moves nothing for an API key, and is kept because the HTTP parameter is documented and still meaningful to a session.")
968
+ },
969
+ async ({ q, types, limit, includeArchived }) => {
970
+ const params = new URLSearchParams({ q });
971
+ if (types?.length) params.set("types", types.join(","));
972
+ if (limit) params.set("limit", String(limit));
973
+ if (includeArchived) params.set("includeArchived", "1");
974
+ const data = await api("GET", `/api/search?${params.toString()}`);
975
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
976
+ }
977
+ );
978
+ server2.tool(
979
+ "list_files",
980
+ "List files as a flat export manifest \u2014 each with a human folder/filename path, checksum, and size. Read-only (scope tensor:files:read). This is the backup/mirroring view; to find and manage files the way the Files page does (folders, search, Trash), use browse_files instead. Download URLs are OFF by default: set urls=true only when you are about to fetch the bytes. A presigned URL is unauthenticated bearer access to a private financial file and it stays in this conversation after the call, so prefer inventorying first (compare updatedAt/checksumSha256) and then requesting urls=true with ids for just the files that changed. Every URL issued is recorded in Tensor's file access log. Entries with encrypted=true are stored as encrypted envelopes, so their downloadUrl returns ciphertext rather than the file. They ARE mirrorable, but only with a registered device: pass deviceId together with urls=true and each encrypted row also carries a `wrappedDek`, its per-file key sealed to that device's public key. Decrypt it with the device's private key, which this API never sees. Without deviceId you get ciphertext and no key \u2014 say so plainly instead of archiving bytes nobody can open. A row carrying `unreadable: true` and a `reason` could not be served (unsignable object, or key material that would not unwrap); skip it and keep paging \u2014 the rest of the page is unaffected.",
981
+ {
982
+ limit: z.number().optional().describe("Page size. Default 200, max 1000."),
983
+ offset: z.number().optional().describe("Pagination offset. Default 0."),
984
+ urls: z.boolean().optional().describe("Mint short-lived presigned download URLs for this page. Default false \u2014 request only when actually downloading."),
985
+ ids: z.array(z.number()).optional().describe("Restrict the page to these file ids (max 200). Pair with urls to fetch links for just what changed."),
986
+ deviceId: z.number().optional().describe(
987
+ "Release decryption keys for this page's encrypted files, each wrapped to the public key of this registered device. Requires urls=true (a key without its ciphertext is refused with a 400). The device must be enrolled beforehand from a browser session via POST /api/files/devices \u2014 an API key can USE a device by id but can never create one \u2014 and an unknown or revoked id returns 404. Omit it unless you hold the device's private key."
988
+ )
989
+ },
990
+ async ({ limit, offset, urls, ids, deviceId }) => {
991
+ const params = new URLSearchParams();
992
+ if (limit) params.set("limit", String(limit));
993
+ if (offset) params.set("offset", String(offset));
994
+ if (urls) params.set("urls", "1");
995
+ if (ids?.length) params.set("ids", ids.join(","));
996
+ if (deviceId != null) params.set("deviceId", String(deviceId));
997
+ const qs = params.toString();
998
+ const data = await api("GET", `/api/files/manifest${qs ? `?${qs}` : ""}`);
999
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1000
+ }
1001
+ );
1002
+ server2.tool(
1003
+ "browse_files",
1004
+ 'Browse the file library the way the Files page does: live files, narrowed by folder, by attached ledger record, or by title/filename search \u2014 or the Trash. Distinct from list_files, which is the flat export manifest (storage keys, checksums, optional download URLs) for backup agents: use browse_files to find and manage files, list_files to mirror them. Returns metadata and attachment links, never bytes \u2014 get_file_download_url mints those. Requires the tensor:files:read scope. Each row\'s `links` array additionally requires the LINKED record type\'s own read scope \u2014 tensor:portfolio:read for entity/account/position/asset/transaction, tensor:reference:read for institution \u2014 and rows your key cannot read are omitted silently, so an empty `links` means "none you can read", not "none". The file itself is never withheld: which entity someone filed it against is a separate question from whether the file is your business.',
1005
+ {
1006
+ limit: z.number().optional().describe("Max results. Default 500."),
1007
+ offset: z.number().optional().describe("Pagination offset"),
1008
+ folderId: z.number().optional().describe("Only files whose home is this folder (see list_file_folders). Omit for every folder."),
1009
+ targetType: z.enum(FILE_ATTACH_TARGET_TYPES).optional().describe("With targetId: only files attached to this record. Any attachment endpoint, not just the ledger six \u2014 the filter reads the `links` table since the 2026-08 fold, so a todo, idea or memo target is a question it can answer (it returned an empty list for those before). Needs that record type's read scope too (tensor:portfolio:read, tensor:reference:read for an institution, tensor:todos:read, tensor:ideas:read) \u2014 this pair names the subject of the question, so it is refused rather than ignored. A memo target is therefore always a 403 for a key."),
1010
+ targetId: z.number().optional().describe("The record id targetType points at. Send both or neither."),
1011
+ q: z.string().optional().describe("Case-insensitive substring over title and filename"),
1012
+ trash: z.boolean().optional().describe("true = list the Trash instead of live files. Default false."),
1013
+ // ORDERING, and the last thing the Files page could ask for that this
1014
+ // tool could not. It is a SERVER-side order, which is what makes it worth
1015
+ // having: the listing is capped, so re-sorting a page locally orders the
1016
+ // window and not the library — "the ten biggest files" computed that way
1017
+ // is the ten biggest of the most recent five hundred. Optional, so every
1018
+ // existing caller is unaffected; that is what makes it a MINOR bump.
1019
+ sort: z.enum(FILE_LIST_SORTS).optional().describe(
1020
+ "Row order: <column>_<direction> over modified (updated_at), added (created_at), name (title, A-Z at _asc) and size. Default added_desc \u2014 newest first, the order every previous release returned. Sizes compare the PLAINTEXT length, so an encrypted file sorts by what it is rather than by its envelope. Not a filter: an unrecognised value is ignored and the default order comes back, never a 400. Names order by the database collation, not a natural sort \u2014 'Q10' precedes 'Q9'."
1021
+ )
1022
+ },
1023
+ async ({ limit, offset, folderId, targetType, targetId, q, trash, sort }) => {
1024
+ const params = new URLSearchParams();
1025
+ if (limit) params.set("limit", String(limit));
1026
+ if (offset) params.set("offset", String(offset));
1027
+ if (folderId != null) params.set("folderId", String(folderId));
1028
+ if (targetType) params.set("targetType", targetType);
1029
+ if (targetId != null) params.set("targetId", String(targetId));
1030
+ if (q) params.set("q", q);
1031
+ if (trash) params.set("trash", "1");
1032
+ if (sort) params.set("sort", sort);
1033
+ const qs = params.toString();
1034
+ const data = await api("GET", `/api/files${qs ? `?${qs}` : ""}`);
1035
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1036
+ }
1037
+ );
1038
+ server2.tool(
1039
+ "get_file",
1040
+ 'Get one file\'s metadata: title, filename, folder, size, MIME type, encryption envelope version, and its attachment links. Never returns bytes \u2014 use get_file_download_url for those. Requires the tensor:files:read scope, and the `links` array additionally requires each linked record type\'s own read scope (tensor:portfolio:read for entity/account/position/asset/transaction, tensor:reference:read for institution). Links your key cannot read are dropped without an error, so an empty `links` means "none you can read", not "none" \u2014 do not report a file as unfiled on the strength of it.',
1041
+ { id: z.number().describe("File ID") },
1042
+ async ({ id }) => {
1043
+ const data = await api("GET", `/api/files/${id}`);
1044
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1045
+ }
1046
+ );
1047
+ server2.tool(
1048
+ "create_file_upload_url",
1049
+ "Step 1 of the three-step upload (presign \u2192 PUT \u2192 confirm): approve filename/type/size and mint a presigned PUT URL plus a server-assigned storageKey. HTTP PUT the raw bytes to `url` (Content-Length is pinned to the approved size), then call confirm_file_upload with the storageKey \u2014 nothing is persisted until confirm, and an abandoned presign just expires. OBEY THE ECHOED TERMS: a response with envelopeVersion 1 means this server stores files encrypted, so the PUT body must be a TDE1 envelope built client-side with your own AES-256 key (passed as `dek` at confirm) \u2014 a plaintext upload will be rejected at the confirm step. Upload quota is charged per byte per hour. Requires the tensor:files:write scope.",
1050
+ {
1051
+ filename: z.string().describe("Original filename. Display data only \u2014 never used in storage paths."),
1052
+ mimeType: z.string().describe("The file's MIME type. Must be on Tensor's upload allow-list; 'Unsupported file type.' means it is not."),
1053
+ sizeBytes: z.number().describe("PLAINTEXT byte size of the file (the cap is on the file, not the envelope)"),
1054
+ envelopeVersion: z.union([z.literal(0), z.literal(1)]).optional().describe("Capability announcement, not an instruction: 1 = this client can build a TDE1 encrypted envelope, 0/omit = plaintext only. The server decides and echoes the terms."),
1055
+ chunkSize: z.number().optional().describe("Requested TDE1 frame size in bytes. Omit for the default; upload under whatever the response echoes.")
1056
+ },
1057
+ async (params) => {
1058
+ const data = await api("POST", "/api/files/upload-url", params);
1059
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1060
+ }
1061
+ );
1062
+ server2.tool(
1063
+ "confirm_file_upload",
1064
+ "Step 3 of the upload: confirm the object landed and create the file row (metadata plus optional record links) in one transaction. Size and MIME are read from the stored object, never believed from the client, and a confirm that fails validation deletes the uploaded object rather than leaving an orphan. For an encrypted upload (the presign said envelopeVersion 1) pass envelopeVersion, chunkSize, mimeType and the base64 `dek` the envelope was encrypted with \u2014 the server wraps the key before storing it and never keeps it raw. Requires the tensor:files:write scope.",
1065
+ {
1066
+ storageKey: z.string().describe("The storageKey minted by create_file_upload_url"),
1067
+ title: z.string().describe("Display title"),
1068
+ filename: z.string().describe("Original filename"),
1069
+ folderId: z.number().optional().describe("Home folder id (see list_file_folders). Omit for the root."),
1070
+ notes: z.string().optional(),
1071
+ checksumSha256: z.string().optional().describe("SHA-256 of the plaintext bytes, stored so backup agents can verify mirrors"),
1072
+ links: z.array(z.object({
1073
+ targetType: z.enum(FILE_ATTACH_TARGET_TYPES),
1074
+ targetId: z.number()
1075
+ })).optional().describe("Attach to records at create time \u2014 same effect as attach_file_link afterwards, same vocabulary, and since 2026-08 the same scope gate: a target your key cannot read is a 403 here too, not a quietly-accepted attachment."),
1076
+ envelopeVersion: z.union([z.literal(0), z.literal(1)]).optional().describe("The terms the bytes were actually uploaded under: 1 = TDE1 envelope, 0/omit = plaintext. Must match what the presign dictated \u2014 a plaintext confirm on an encryption-enabled server is rejected."),
1077
+ chunkSize: z.number().optional().describe("TDE1 frame size used. Required when envelopeVersion is 1."),
1078
+ mimeType: z.string().optional().describe("The file's real MIME type. Required when envelopeVersion is 1 (ciphertext is opaque, so the stored object cannot answer); ignored for plaintext."),
1079
+ dek: z.string().optional().describe("Base64 AES-256 key the envelope was encrypted with. Required when envelopeVersion is 1.")
1080
+ },
1081
+ async (params) => {
1082
+ const data = await api("POST", "/api/files", params);
1083
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1084
+ }
1085
+ );
1086
+ server2.tool(
1087
+ "update_file",
1088
+ "Rename, move or annotate a file \u2014 a partial update of title / folderId / notes only. The bytes and the original filename are immutable; new content is a new upload. Requires the tensor:files:write scope.",
1089
+ {
1090
+ id: z.number().describe("File ID"),
1091
+ title: z.string().optional(),
1092
+ folderId: z.number().nullable().optional().describe("New home folder id, or null for the root"),
1093
+ notes: z.string().nullable().optional()
1094
+ },
1095
+ async ({ id, ...body }) => {
1096
+ const data = await api("PATCH", `/api/files/${id}`, body);
1097
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1098
+ }
1099
+ );
1100
+ server2.tool(
1101
+ "delete_file",
1102
+ "Move a file to the Trash (soft delete). The stored bytes stay put and restore_file undoes it. The permanent purge that actually destroys bytes is deliberately not reachable with an API key \u2014 it is UI-only, so a key cannot unrecoverably delete a file. Requires the tensor:files:write scope.",
1103
+ { id: z.number().describe("File ID") },
1104
+ async ({ id }) => {
1105
+ const data = await api("DELETE", `/api/files/${id}`);
1106
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1107
+ }
1108
+ );
1109
+ server2.tool(
1110
+ "restore_file",
1111
+ "Restore a file from the Trash. 404 when the file is not in the Trash. Requires the tensor:files:write scope.",
1112
+ { id: z.number().describe("File ID") },
1113
+ async ({ id }) => {
1114
+ const data = await api("POST", `/api/files/${id}/restore`);
1115
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1116
+ }
1117
+ );
1118
+ server2.tool(
1119
+ "get_file_download_url",
1120
+ "Mint a short-lived presigned download URL for one file's bytes (works on trashed files too, as a recovery aid). A presigned URL is unauthenticated bearer access to a private financial file and it stays in this conversation after the call \u2014 request one only when actually about to fetch the bytes, and never re-post it. Every issuance is recorded in Tensor's file access log. For an ENCRYPTED file (envelopeVersion 1) the URL points at ciphertext and the response also carries the raw `dek` \u2014 a permanent key release, likewise access-logged \u2014 with which the client must decrypt the TDE1 envelope itself. Requires the tensor:files:read scope.",
1121
+ {
1122
+ id: z.number().describe("File ID"),
1123
+ inline: z.boolean().optional().describe("Ask for preview (inline) disposition instead of download. Honored only for previewable plaintext types.")
1124
+ },
1125
+ async ({ id, inline }) => {
1126
+ const data = await api("GET", `/api/files/${id}/download-url${inline ? "?inline=1" : ""}`);
1127
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1128
+ }
1129
+ );
1130
+ server2.tool(
1131
+ "list_file_links",
1132
+ `List a file's attachments. Any record type since the 2026-08 fold \u2014 the six ledger records (entity, institution, account, position, asset, transaction) plus todo, idea and memo. Each row's id is the linkId that detach_file_link takes, and NOT the target record's id; each row also carries \`label\`, the target's resolved name. Requires the tensor:files:read scope, and each ROW additionally requires that record type's own read scope \u2014 tensor:portfolio:read for entity/account/position/asset/transaction, tensor:reference:read for institution, tensor:todos:read for todo, tensor:ideas:read for idea. A memo row is readable by no key at all. Rows your key cannot read are omitted silently, so an empty answer means "none you can read", not "none".`,
1133
+ { id: z.number().describe("File ID") },
1134
+ async ({ id }) => {
1135
+ const data = await api("GET", `/api/files/${id}/links`);
1136
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1137
+ }
1138
+ );
1139
+ server2.tool(
1140
+ "attach_file_link",
1141
+ "Attach a file to a record \u2014 a ledger record, a todo, an idea or a memo. Idempotent: re-attaching an existing pair adds nothing and returns the same linkId. Requires the tensor:files:write scope AND the target record type's read scope (tensor:portfolio:read for entity/account/position/asset/transaction, tensor:reference:read for institution, tensor:todos:read for todo, tensor:ideas:read for idea; a memo is refused for every key) \u2014 filing a file against position 12 is an assertion about position 12, so a target you may not read is refused out loud with a 403 naming the missing scope rather than dropped. The refusal comes before the file is even loaded, so it cannot double as an existence check on the file id.",
1142
+ {
1143
+ id: z.number().describe("File ID"),
1144
+ targetType: z.enum(FILE_ATTACH_TARGET_TYPES).describe("Record kind to attach to. Not 'file' \u2014 a file attached to a file is not a thing to file against."),
1145
+ targetId: z.number().describe("The record's ID")
1146
+ },
1147
+ async ({ id, ...body }) => {
1148
+ const data = await api("POST", `/api/files/${id}/links`, body);
1149
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1150
+ }
1151
+ );
1152
+ server2.tool(
1153
+ "detach_file_link",
1154
+ "Detach a file from a record. Only the link is removed \u2014 the file and the record are untouched. Requires the tensor:files:write scope AND the linked record type's read scope (tensor:portfolio:read for entity/account/position/asset/transaction, tensor:reference:read for institution, tensor:todos:read for todo, tensor:ideas:read for idea) \u2014 the route reads the edge before removing it, so a key cannot unfile a record it is not allowed to see. Removing a link that is not there stays a 200: the call was always idempotent, and there is no target type to make a scope decision about.",
1155
+ {
1156
+ id: z.number().describe("File ID"),
1157
+ linkId: z.number().describe("The link's id from list_file_links \u2014 not the target record's id")
1158
+ },
1159
+ async ({ id, linkId }) => {
1160
+ const data = await api("DELETE", `/api/files/${id}/links/${linkId}`);
1161
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1162
+ }
1163
+ );
1164
+ server2.tool(
1165
+ "list_file_folders",
1166
+ "List every file folder: id, name, parentId nesting, and an optional pin to one ledger record. Requires the tensor:files:read scope.",
1167
+ {},
1168
+ async () => {
1169
+ const data = await api("GET", "/api/file-folders");
1170
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1171
+ }
1172
+ );
1173
+ server2.tool(
1174
+ "create_file_folder",
1175
+ "Create a file folder. Folders nest via parentId (depth-capped and cycle-checked server-side). Setting targetType + targetId pins the folder to one ledger record's Files tab \u2014 a pin is a home, not an access rule. Requires the tensor:files:write scope.",
1176
+ {
1177
+ name: z.string().describe("Folder name"),
1178
+ parentId: z.number().nullable().optional().describe("Parent folder id, or null/omit for top level"),
1179
+ notes: z.string().optional(),
1180
+ targetType: z.enum(RECORD_TARGET_TYPES).nullable().optional().describe("With targetId, pin the folder to one LEDGER record. Send both or neither. Still the six, deliberately: a pin is a `file_folders` column rather than an edge and was left out of the 2026-08 fold \u2014 do not reach for FILE_ATTACH_TARGET_TYPES here."),
1181
+ targetId: z.number().nullable().optional()
1182
+ },
1183
+ async (params) => {
1184
+ const data = await api("POST", "/api/file-folders", params);
1185
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1186
+ }
1187
+ );
1188
+ server2.tool(
1189
+ "update_file_folder",
1190
+ "Rename, move or re-pin a file folder (partial update). Requires the tensor:files:write scope.",
1191
+ {
1192
+ id: z.number().describe("Folder ID"),
1193
+ name: z.string().optional(),
1194
+ parentId: z.number().nullable().optional().describe("New parent folder id, or null for top level"),
1195
+ notes: z.string().nullable().optional(),
1196
+ targetType: z.enum(RECORD_TARGET_TYPES).nullable().optional(),
1197
+ targetId: z.number().nullable().optional()
1198
+ },
1199
+ async ({ id, ...body }) => {
1200
+ const data = await api("PATCH", `/api/file-folders/${id}`, body);
1201
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1202
+ }
1203
+ );
1204
+ server2.tool(
1205
+ "delete_file_folder",
1206
+ "Delete an EMPTY file folder. Refused with a 409 while the folder still holds files or sub-folders \u2014 move or delete those first; nothing is ever cascaded. Requires the tensor:files:write scope.",
1207
+ { id: z.number().describe("Folder ID") },
1208
+ async ({ id }) => {
1209
+ const data = await api("DELETE", `/api/file-folders/${id}`);
1210
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1211
+ }
1212
+ );
1213
+ server2.tool(
1214
+ "list_todos",
1215
+ "List todos, filtered server-side (filters AND-combine; an unparseable value is dropped rather than rejected, so the result widens, never silently narrows). The default is the live list: Trash is excluded and sub-tasks are included \u2014 set trash for the Trash, topLevelOnly for just the roots, or parentId for one todo's checklist. Requires the tensor:todos:read scope.",
1216
+ {
1217
+ limit: z.number().optional().describe("Max results. Default 500."),
1218
+ offset: z.number().optional().describe("Pagination offset"),
1219
+ stateId: z.number().optional().describe("Only todos in this workflow state (see list_todo_states)"),
1220
+ category: z.enum(TODO_STATE_CATEGORIES).optional().describe("Only todos whose state has this category \u2014 the stable axis; states are org-renamable labels over it"),
1221
+ // One id or several, OR-combined server-side. See numListParam.
1222
+ assigneeId: z.union([z.number(), z.array(z.number())]).optional().describe("Only todos assigned to this user \u2014 or to any of these users; pass one id or an array"),
1223
+ priority: z.number().optional().describe("Exact priority: 0 = none, 1 = urgent, 2 = high, 3 = medium, 4 = low"),
1224
+ labelId: z.union([z.number(), z.array(z.number())]).optional().describe("Only todos carrying this label \u2014 or any of these labels; pass one id or an array (see list_todo_labels)"),
1225
+ parentId: z.number().optional().describe("Only sub-tasks of this todo"),
1226
+ topLevelOnly: z.boolean().optional().describe("Only top-level todos (no parent). Ignored when parentId is set."),
1227
+ targetType: z.enum(TODO_LINK_TARGET_TYPES).optional().describe("With targetId: only todos linked to this record. Any link endpoint, not just the ledger six \u2014 the filter reads the `links` table, so a todo, idea or memo target is a question it can answer. Unlike the other filters this pair is refused rather than dropped when your key lacks the target type's read scope (403): it names another domain's record, and dropping it would widen the answer to every todo. A memo target is therefore always a 403 for a key."),
1228
+ targetId: z.number().optional().describe("The record id targetType points at"),
1229
+ q: z.string().optional().describe("Case-insensitive substring over title and body text"),
1230
+ trash: z.boolean().optional().describe("Only todos in Trash (deleted, still recoverable) instead of the live list"),
1231
+ sort: z.enum(TODO_LIST_SORTS).optional().describe("Order: manual (the board's rank order, default), created, updated, due, or priority")
1232
+ },
1233
+ async ({ limit, offset, stateId, category, assigneeId, priority, labelId, parentId, topLevelOnly, targetType, targetId, q, trash, sort }) => {
1234
+ const params = new URLSearchParams();
1235
+ if (limit) params.set("limit", String(limit));
1236
+ if (offset) params.set("offset", String(offset));
1237
+ if (stateId) params.set("stateId", String(stateId));
1238
+ if (category) params.set("category", category);
1239
+ const assignees = numListParam(assigneeId);
1240
+ if (assignees) params.set("assigneeId", assignees);
1241
+ if (priority !== void 0) params.set("priority", String(priority));
1242
+ const labels = numListParam(labelId);
1243
+ if (labels) params.set("labelId", labels);
1244
+ if (parentId != null) params.set("parentId", String(parentId));
1245
+ else if (topLevelOnly) params.set("parentId", "null");
1246
+ if (targetType) params.set("targetType", targetType);
1247
+ if (targetId) params.set("targetId", String(targetId));
1248
+ if (q) params.set("q", q);
1249
+ if (trash) params.set("trash", "1");
1250
+ if (sort) params.set("sort", sort);
1251
+ const qs = params.toString();
1252
+ const data = await api("GET", `/api/todos${qs ? `?${qs}` : ""}`);
1253
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1254
+ }
1255
+ );
1256
+ server2.tool(
1257
+ "get_todo",
1258
+ "Get one todo by ID: title, body (bodyJson is the TipTap document, bodyText the server-derived plain text), state, priority, labels, record links, and sub-task counts. Requires the tensor:todos:read scope.",
1259
+ { id: z.number().describe("Todo ID") },
1260
+ async ({ id }) => {
1261
+ const data = await api("GET", `/api/todos/${id}`);
1262
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1263
+ }
1264
+ );
1265
+ server2.tool(
1266
+ "get_todo_subtree",
1267
+ "The shape of the branch under a todo: direct child count, total descendant count, how many of those descendants are in Trash (trashedDescendantCount), the max depth, and whether the walk truncated. Read this before deleting or re-parenting a todo with sub-tasks, so you can name what the operation takes with it. Requires the tensor:todos:read scope.",
1268
+ { id: z.number().describe("Todo ID") },
1269
+ async ({ id }) => {
1270
+ const data = await api("GET", `/api/todos/${id}/subtree`);
1271
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1272
+ }
1273
+ );
1274
+ server2.tool(
1275
+ "get_todo_activity",
1276
+ "One todo's activity feed (creates, edits, state moves, comments), folded on read from the data-mutation audit log \u2014 there is no separate activity table, and that log has a 90-DAY RETENTION, so this is a rolling window, not permanent history. Returns the latest 50 entries. Requires the tensor:todos:read scope.",
1277
+ { id: z.number().describe("Todo ID") },
1278
+ async ({ id }) => {
1279
+ const data = await api("GET", `/api/todos/${id}/activity`);
1280
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1281
+ }
1282
+ );
1283
+ server2.tool(
1284
+ "create_todo",
1285
+ "Create a todo. `stateId` must name an existing workflow state \u2014 call list_todo_states first. `body` is PLAIN TEXT: the tool wraps it into the TipTap JSON document Tensor stores (bodyJson, never HTML; one paragraph per line) and the server derives the searchable text from it. Requires the tensor:todos:write scope, plus each `links` entry's target type read scope (same rule as attach_todo_link).",
1286
+ {
1287
+ title: z.string().describe("Todo title (max 512 chars)"),
1288
+ stateId: z.number().describe("Workflow state ID from list_todo_states"),
1289
+ body: z.string().optional().describe("Body as plain text; each line becomes a paragraph. Stored as TipTap JSON, never HTML."),
1290
+ priority: z.number().optional().describe("0 = none (default), 1 = urgent, 2 = high, 3 = medium, 4 = low"),
1291
+ assigneeId: z.number().optional().describe("User ID to assign"),
1292
+ parentId: z.number().optional().describe("Create as a sub-task of this todo"),
1293
+ dueDate: z.string().optional().describe("Due date in ISO format YYYY-MM-DD"),
1294
+ labelIds: z.array(z.number()).optional().describe("Label IDs to attach at create (see list_todo_labels)"),
1295
+ // TODO_LINK_TARGET_TYPES, not RECORD_TARGET_TYPES. This enum was the six
1296
+ // ledger records while `insertTodoSchema` was, which was faithful then and
1297
+ // is not now: the server accepts all nine here, the same set
1298
+ // attach_todo_link takes, because both are the same write through
1299
+ // `createLink`. A narrow enum would make "create a todo already linked to
1300
+ // a memo" unaskable while "create it, then attach_todo_link" worked.
1301
+ links: z.array(z.object({
1302
+ targetType: z.enum(TODO_LINK_TARGET_TYPES),
1303
+ targetId: z.number()
1304
+ })).optional().describe("File the todo against records at create time \u2014 same set and same effect as attach_todo_link afterwards: any of the six ledger records, another todo, an idea or a memo. Not 'file' (see attach_todo_file). Each entry needs the target type's read scope on top of tensor:todos:write, and a denied one fails the whole create with a 403 rather than being dropped \u2014 so a memo entry is refused for any key.")
1305
+ },
1306
+ async ({ body, ...rest }) => {
1307
+ const payload = { ...rest };
1308
+ if (body !== void 0 && body.trim().length > 0) payload.bodyJson = tiptapDocJson(body);
1309
+ const data = await api("POST", "/api/todos", payload);
1310
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1311
+ }
1312
+ );
1313
+ server2.tool(
1314
+ "update_todo",
1315
+ "Update a todo (partial). `body` is plain text and REPLACES the whole body (wrapped to the stored TipTap JSON; an empty string clears it). Re-parenting has its own verb \u2014 set_todo_parent. Pass expectedUpdatedAt (the updatedAt you loaded) to opt into stale-write detection: the update is then refused with a 409 carrying the current row if someone else changed the todo in between. Requires the tensor:todos:write scope.",
1316
+ {
1317
+ id: z.number().describe("Todo ID"),
1318
+ title: z.string().optional(),
1319
+ stateId: z.number().optional().describe("Move to this workflow state"),
1320
+ body: z.string().optional().describe("New body as plain text \u2014 replaces the existing body; empty string clears it"),
1321
+ priority: z.number().optional().describe("0 = none, 1 = urgent, 2 = high, 3 = medium, 4 = low"),
1322
+ assigneeId: z.number().nullable().optional().describe("User ID, or null to unassign"),
1323
+ dueDate: z.string().nullable().optional().describe("ISO YYYY-MM-DD, or null to clear"),
1324
+ expectedUpdatedAt: z.number().optional().describe("The todo's updatedAt as you loaded it \u2014 enables the stale-write check")
1325
+ },
1326
+ async ({ id, body, ...rest }) => {
1327
+ const payload = { ...rest };
1328
+ if (body !== void 0) {
1329
+ if (body.trim().length > 0) {
1330
+ payload.bodyJson = tiptapDocJson(body);
1331
+ } else {
1332
+ payload.bodyJson = null;
1333
+ payload.bodyText = null;
1334
+ }
1335
+ }
1336
+ const data = await api("PATCH", `/api/todos/${id}`, payload);
1337
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1338
+ }
1339
+ );
1340
+ server2.tool(
1341
+ "delete_todo",
1342
+ "Move a todo AND the whole branch of sub-tasks under it to Trash, atomically. This is a SOFT delete: nothing is destroyed, every row keeps its place in the tree, and restore_todo puts it back. The response reports how many live descendants went with it (`trashedDescendants`; `truncated: true` means that count is a floor \u2014 the delete itself always takes the whole branch). Trash empties itself 60 days after deletion; permanently deleting sooner is session-only and has no tool here. Requires the tensor:todos:write scope.",
1343
+ { id: z.number().describe("Todo ID") },
1344
+ async ({ id }) => {
1345
+ const data = await api("DELETE", `/api/todos/${id}`);
1346
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1347
+ }
1348
+ );
1349
+ server2.tool(
1350
+ "restore_todo",
1351
+ "Take a todo out of Trash, back to the place in the list it was deleted from. Descendants stay deleted by default (a sub-task deleted separately and on purpose must not come back because its parent did); pass cascade: true to restore every deleted descendant with it. Refused with 409 when an ancestor is still in Trash \u2014 restoring under a deleted parent would put the todo in no list at all; pass withAncestors: true to bring the chain above back too. Requires the tensor:todos:write scope.",
1352
+ {
1353
+ id: z.number().describe("Todo ID"),
1354
+ cascade: z.boolean().optional().describe("Also restore every deleted descendant. Default false."),
1355
+ withAncestors: z.boolean().optional().describe("Also restore any ancestor still in Trash. Default false, which makes that case a 409.")
1356
+ },
1357
+ async ({ id, cascade, withAncestors }) => {
1358
+ const data = await api("POST", `/api/todos/${id}/restore`, { cascade, withAncestors });
1359
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1360
+ }
1361
+ );
1362
+ server2.tool(
1363
+ "set_todo_parent",
1364
+ "Move a todo under another todo, or to the top level (parentId: null). The todo is re-ranked inside its new sibling set in the same transaction. Self-parenting, cycles and exceeding the depth cap are refused with a 409 that says which. Requires the tensor:todos:write scope.",
1365
+ {
1366
+ id: z.number().describe("Todo ID to move"),
1367
+ parentId: z.number().nullable().describe("New parent todo ID, or null for top level")
1368
+ },
1369
+ async ({ id, parentId }) => {
1370
+ const data = await api("POST", `/api/todos/${id}/parent`, { parentId });
1371
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1372
+ }
1373
+ );
1374
+ server2.tool(
1375
+ "reorder_todo",
1376
+ "Move a todo within the manual sort order, optionally into a different workflow state at the same time. beforeId / afterId name the sibling todos it should land between \u2014 beforeId sits immediately above the moved todo, afterId immediately below; pass one, both, or neither (omitted/null means that end of the list). Neighbors are resolved within the todo's own sibling set (its parent's checklist, or the target state for top-level todos). Requires the tensor:todos:write scope.",
1377
+ {
1378
+ id: z.number().describe("Todo ID to move"),
1379
+ stateId: z.number().optional().describe("Move into this workflow state as part of the reorder"),
1380
+ beforeId: z.number().nullable().optional().describe("The sibling that should end up immediately ABOVE the moved todo"),
1381
+ afterId: z.number().nullable().optional().describe("The sibling that should end up immediately BELOW the moved todo")
1382
+ },
1383
+ async ({ id, ...body }) => {
1384
+ const data = await api("POST", `/api/todos/${id}/reorder`, body);
1385
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1386
+ }
1387
+ );
1388
+ server2.tool(
1389
+ "set_todo_labels",
1390
+ "Replace a todo's ENTIRE label set in one call \u2014 whole-set semantics: labels not named are removed, and [] clears them all. Max 50. Requires the tensor:todos:write scope.",
1391
+ {
1392
+ id: z.number().describe("Todo ID"),
1393
+ labelIds: z.array(z.number()).describe("The full desired set of label IDs")
1394
+ },
1395
+ async ({ id, labelIds }) => {
1396
+ const data = await api("PUT", `/api/todos/${id}/labels`, { labelIds });
1397
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1398
+ }
1399
+ );
1400
+ server2.tool(
1401
+ "list_todo_comments",
1402
+ "List a todo's comment thread. Each comment carries bodyJson (the TipTap document) and bodyText (server-derived plain text \u2014 read this one). Requires the tensor:todos:read scope.",
1403
+ { id: z.number().describe("Todo ID") },
1404
+ async ({ id }) => {
1405
+ const data = await api("GET", `/api/todos/${id}/comments`);
1406
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1407
+ }
1408
+ );
1409
+ server2.tool(
1410
+ "create_todo_comment",
1411
+ "Comment on a todo. `body` is PLAIN TEXT \u2014 the tool wraps it into the TipTap JSON document Tensor stores (never HTML), one paragraph per line. Empty comments are rejected. Requires the tensor:todos:write scope.",
1412
+ {
1413
+ id: z.number().describe("Todo ID"),
1414
+ body: z.string().describe("Comment text (plain text; each line becomes a paragraph)")
1415
+ },
1416
+ async ({ id, body }) => {
1417
+ const data = await api("POST", `/api/todos/${id}/comments`, { bodyJson: tiptapDocJson(body) });
1418
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1419
+ }
1420
+ );
1421
+ server2.tool(
1422
+ "update_todo_comment",
1423
+ "Edit a todo comment YOU wrote \u2014 the server answers 404 for anyone else's, indistinguishable from a missing comment. `body` is plain text and replaces the whole comment; comments cannot be deleted through the API, only edited. Requires the tensor:todos:write scope.",
1424
+ {
1425
+ id: z.number().describe("Todo ID"),
1426
+ commentId: z.number().describe("Comment ID"),
1427
+ body: z.string().describe("Replacement comment text (plain text)")
1428
+ },
1429
+ async ({ id, commentId, body }) => {
1430
+ const data = await api("PATCH", `/api/todos/${id}/comments/${commentId}`, { bodyJson: tiptapDocJson(body) });
1431
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1432
+ }
1433
+ );
1434
+ server2.tool(
1435
+ "list_todo_states",
1436
+ "List the org's todo workflow states: key, label, category (backlog | unstarted | started | completed | canceled), color, position, and how many todos hold each (usageCount). Category is the load-bearing axis \u2014 grouping, completed_at stamping and 'hide done' read it, never the label. Requires the tensor:todos:read scope.",
1437
+ {},
1438
+ async () => {
1439
+ const data = await api("GET", "/api/todo-states");
1440
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1441
+ }
1442
+ );
1443
+ server2.tool(
1444
+ "create_todo_state",
1445
+ "Create a todo workflow state \u2014 an org-renamable label pinned to a fixed behavioural category. Requires the tensor:todos:write scope.",
1446
+ {
1447
+ key: z.string().describe("Stable key, e.g. 'in_review'"),
1448
+ label: z.string().describe("Display label, e.g. 'In review'"),
1449
+ category: z.enum(TODO_STATE_CATEGORIES).describe("Fixed category. Entering completed/canceled stamps completed_at; leaving clears it."),
1450
+ color: z.string().optional().describe("Display color"),
1451
+ position: z.number().optional().describe("Sort position among the org's states"),
1452
+ notes: z.string().optional()
1453
+ },
1454
+ async (params) => {
1455
+ const data = await api("POST", "/api/todo-states", params);
1456
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1457
+ }
1458
+ );
1459
+ server2.tool(
1460
+ "update_todo_state",
1461
+ "Update a workflow state (partial). Renaming key/label/color/position is free; changing `category` is refused with a 409 while any todo holds the state. Requires the tensor:todos:write scope.",
1462
+ {
1463
+ id: z.number().describe("State ID"),
1464
+ key: z.string().optional(),
1465
+ label: z.string().optional(),
1466
+ category: z.enum(TODO_STATE_CATEGORIES).optional().describe("Refused (409) while todos hold this state"),
1467
+ color: z.string().nullable().optional(),
1468
+ position: z.number().optional(),
1469
+ notes: z.string().nullable().optional()
1470
+ },
1471
+ async ({ id, ...body }) => {
1472
+ const data = await api("PATCH", `/api/todo-states/${id}`, body);
1473
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1474
+ }
1475
+ );
1476
+ server2.tool(
1477
+ "delete_todo_state",
1478
+ "Delete a workflow state. Refused with a 409 while any todo still holds it (move them first) and for the last remaining state. Requires the tensor:todos:write scope.",
1479
+ { id: z.number().describe("State ID") },
1480
+ async ({ id }) => {
1481
+ const data = await api("DELETE", `/api/todo-states/${id}`);
1482
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1483
+ }
1484
+ );
1485
+ server2.tool(
1486
+ "list_todo_labels",
1487
+ "List the org's todo labels with usage counts. Requires the tensor:todos:read scope.",
1488
+ {},
1489
+ async () => {
1490
+ const data = await api("GET", "/api/todo-labels");
1491
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1492
+ }
1493
+ );
1494
+ server2.tool(
1495
+ "create_todo_label",
1496
+ "Create a todo label. Names are unique case-insensitively \u2014 a duplicate is a 409. Requires the tensor:todos:write scope.",
1497
+ {
1498
+ name: z.string().describe("Label name, 1-64 chars"),
1499
+ color: z.string().optional().describe("Hex color like #6366f1")
1500
+ },
1501
+ async (params) => {
1502
+ const data = await api("POST", "/api/todo-labels", params);
1503
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1504
+ }
1505
+ );
1506
+ server2.tool(
1507
+ "update_todo_label",
1508
+ "Rename or recolor a todo label (partial update; the rename applies everywhere the label is used). Requires the tensor:todos:write scope.",
1509
+ {
1510
+ id: z.number().describe("Label ID"),
1511
+ name: z.string().optional(),
1512
+ color: z.string().nullable().optional()
711
1513
  },
712
- async ({ operations }) => {
713
- const data = await api("POST", "/api/data/apply", { operations });
1514
+ async ({ id, ...body }) => {
1515
+ const data = await api("PATCH", `/api/todo-labels/${id}`, body);
1516
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1517
+ }
1518
+ );
1519
+ server2.tool(
1520
+ "delete_todo_label",
1521
+ "Delete a todo label. It is removed from every todo that carries it. Requires the tensor:todos:write scope.",
1522
+ { id: z.number().describe("Label ID") },
1523
+ async ({ id }) => {
1524
+ const data = await api("DELETE", `/api/todo-labels/${id}`);
1525
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1526
+ }
1527
+ );
1528
+ server2.tool(
1529
+ "list_todo_files",
1530
+ "List the files attached to a todo, newest attachment first \u2014 file metadata plus the linkId that detach_todo_file takes. These rows ARE file rows, so this needs the tensor:files:read scope as well as tensor:todos:read; without it the call is refused with a 403 naming the missing scope rather than answering with an empty list.",
1531
+ { id: z.number().describe("Todo ID") },
1532
+ async ({ id }) => {
1533
+ const data = await api("GET", `/api/todos/${id}/files`);
1534
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1535
+ }
1536
+ );
1537
+ server2.tool(
1538
+ "attach_todo_file",
1539
+ "Attach an EXISTING file to a todo. There is no upload here \u2014 upload via create_file_upload_url + confirm_file_upload, then attach the file id that came back. Idempotent for an already-attached file; refused with a 409 once the todo holds 200 attachments. Requires the tensor:todos:write scope AND tensor:files:read.",
1540
+ {
1541
+ id: z.number().describe("Todo ID"),
1542
+ fileId: z.number().describe("ID of an existing file")
1543
+ },
1544
+ async ({ id, fileId }) => {
1545
+ const data = await api("POST", `/api/todos/${id}/files`, { fileId });
1546
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1547
+ }
1548
+ );
1549
+ server2.tool(
1550
+ "detach_todo_file",
1551
+ "Detach one file from a todo. Only the attachment edge is removed \u2014 the file itself is untouched. Requires the tensor:todos:write scope AND tensor:files:read.",
1552
+ {
1553
+ id: z.number().describe("Todo ID"),
1554
+ linkId: z.number().describe("The linkId from list_todo_files \u2014 not the file id")
1555
+ },
1556
+ async ({ id, linkId }) => {
1557
+ const data = await api("DELETE", `/api/todos/${id}/files/${linkId}`);
1558
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1559
+ }
1560
+ );
1561
+ server2.tool(
1562
+ "list_todo_links",
1563
+ `List the records a todo is linked to. NOT ledger-only: since the 2026-08 fold these are rows in the one \`links\` table, so a row may name any of the six ledger records (entity, institution, account, position, asset, transaction), another todo, an idea, a memo \u2014 or a file, if a 'related' edge to one was made through the generic links API. A todo's ATTACHED files are a different edge kind and a different tool: list_todo_files. Each row's id is the linkId that detach_todo_link takes. Requires the tensor:todos:read scope, and each ROW additionally requires that record type's own read scope \u2014 tensor:portfolio:read for entity/account/position/asset/transaction, tensor:reference:read for institution, tensor:todos:read for a todo, tensor:ideas:read for an idea, tensor:files:read for a file. Rows your key cannot read are omitted silently, so an empty answer means "none you can read", not "none" \u2014 and a memo row is omitted for EVERY key, because memos are session-only.`,
1564
+ { id: z.number().describe("Todo ID") },
1565
+ async ({ id }) => {
1566
+ const data = await api("GET", `/api/todos/${id}/links`);
1567
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1568
+ }
1569
+ );
1570
+ server2.tool(
1571
+ "attach_todo_link",
1572
+ "Link a todo to another record: one of the six ledger records (entity, institution, account, position, asset, transaction), another todo, an idea, or a memo. Idempotent. Requires the tensor:todos:write scope AND the target record type's read scope (tensor:portfolio:read, tensor:reference:read for an institution, tensor:ideas:read for an idea) \u2014 asserting that a todo is about a record means being allowed to know that record exists, and a denied target is refused out loud rather than dropped. A memo target is therefore refused whatever the key carries, since no scope grants a memo. Files are not in this set: attach one with attach_todo_file, which writes the edge the todo's Files pane can see and detach.",
1573
+ {
1574
+ id: z.number().describe("Todo ID"),
1575
+ targetType: z.enum(TODO_LINK_TARGET_TYPES).describe("Record kind to link to. Not 'file' \u2014 see attach_todo_file."),
1576
+ targetId: z.number().describe("The record's ID")
1577
+ },
1578
+ async ({ id, ...body }) => {
1579
+ const data = await api("POST", `/api/todos/${id}/links`, body);
1580
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1581
+ }
1582
+ );
1583
+ server2.tool(
1584
+ "detach_todo_link",
1585
+ "Remove one of a todo's links. Only the edge goes; the todo and the record it named are untouched. Requires the tensor:todos:write scope AND the linked record type's read scope (tensor:portfolio:read, tensor:reference:read for an institution, tensor:ideas:read for an idea, tensor:files:read for a file) \u2014 the route reads the edge before removing it, so a key cannot unfile a record it is not allowed to see.",
1586
+ {
1587
+ id: z.number().describe("Todo ID"),
1588
+ linkId: z.number().describe("The link's id from list_todo_links \u2014 not the target record's id")
1589
+ },
1590
+ async ({ id, linkId }) => {
1591
+ const data = await api("DELETE", `/api/todos/${id}/links/${linkId}`);
1592
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1593
+ }
1594
+ );
1595
+ server2.tool(
1596
+ "list_ideas",
1597
+ "List ideas from the capture inbox, newest first unless sort says otherwise. Default is the live stream; trash selects the Trash instead. Filters AND-combine and unparseable values are dropped server-side \u2014 except targetType/targetId, which is refused rather than dropped (see it). Requires the tensor:ideas:read scope.",
1598
+ {
1599
+ limit: z.number().optional().describe("Max results. Default 500."),
1600
+ offset: z.number().optional().describe("Pagination offset"),
1601
+ kind: z.enum(IDEA_KINDS).optional().describe("Card shape: link, note, image or video"),
1602
+ tag: z.string().optional().describe("Only ideas carrying this tag (matching is lowercase-normalized; see list_idea_tags)"),
1603
+ site: z.string().optional().describe("Only ideas captured from this site \u2014 a bare host like 'youtube.com' (see list_idea_sites)"),
1604
+ q: z.string().optional().describe("Case-insensitive substring over title, body, url and site name"),
1605
+ targetType: z.enum(IDEA_LINK_TARGET_TYPES).optional().describe("With targetId: only ideas LINKED to this record. Any link endpoint except 'file' \u2014 an idea's files are its gallery, read through get_idea. Unlike the other filters this pair is refused rather than dropped when your key lacks the target type's read scope (403): it names another domain's record, and dropping it would widen the answer to every idea. A memo target is therefore always a 403 for a key."),
1606
+ targetId: z.number().optional().describe("The record id targetType points at. Send both or neither."),
1607
+ trash: z.boolean().optional().describe("true = the Trash instead of the live stream"),
1608
+ // ORDERING, and it is the ONE thing the web stream could ask for and this
1609
+ // tool could not. The server has parsed it since the arrangement work
1610
+ // (`parseIdeaFilters`, server/http/list-options.ts) and the page has used
1611
+ // it the whole time; the gap was here, and it is the shape `list_todos`
1612
+ // already had one noun over. Optional, so every existing caller is
1613
+ // unaffected — which is what makes it a MINOR bump rather than a major.
1614
+ sort: z.enum(IDEA_SORT_MODES).optional().describe("Row order: newest (default), oldest, updated (recently edited first), or title (A-Z). Not a filter \u2014 an unrecognised value is ignored and the default order comes back, never a 400. There is deliberately no manual order: an idea has no rank column.")
1615
+ },
1616
+ async ({ limit, offset, kind, tag, site, q, targetType, targetId, trash, sort }) => {
1617
+ const params = new URLSearchParams();
1618
+ if (limit) params.set("limit", String(limit));
1619
+ if (offset) params.set("offset", String(offset));
1620
+ if (kind) params.set("kind", kind);
1621
+ if (tag) params.set("tag", tag);
1622
+ if (site) params.set("site", site);
1623
+ if (q) params.set("q", q);
1624
+ if (targetType) params.set("targetType", targetType);
1625
+ if (targetId != null) params.set("targetId", String(targetId));
1626
+ if (trash) params.set("trash", "1");
1627
+ if (sort) params.set("sort", sort);
1628
+ const qs = params.toString();
1629
+ const data = await api("GET", `/api/ideas${qs ? `?${qs}` : ""}`);
1630
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1631
+ }
1632
+ );
1633
+ server2.tool(
1634
+ "get_idea",
1635
+ "Get one idea with its tags and media gallery. `body` is the plain text \u2014 read this one; `bodyJson` beside it is the TipTap document the body is stored as, and is null on a capture written before 4.2.0 that has not been edited since (`body` is the whole of it in that case). Each media entry's id is what get_idea_media_url takes (an idea's media IS a file row; that id is the file's), and envelopeVersion says whether the stored object is plaintext (0) or an encrypted envelope (1). Requires the tensor:ideas:read scope.",
1636
+ { id: z.number().describe("Idea ID") },
1637
+ async ({ id }) => {
1638
+ const data = await api("GET", `/api/ideas/${id}`);
1639
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1640
+ }
1641
+ );
1642
+ server2.tool(
1643
+ "create_idea",
1644
+ "Capture an idea into the inbox. At least one of url, body or media is required. `body` is PLAIN TEXT IN, DOCUMENT STORED: since 4.2.0 an idea's body is a rich document (like a memo's, and like its own comments), and the server wraps the text you send \u2014 one paragraph per line \u2014 then derives `body` back out of it for search and previews. Read `body`; `bodyJson` on the response is the document itself and is the editor's business. Max 256000 characters. NO INLINE IMAGES FROM HERE \u2014 this tool takes text only, and a URL or markdown image typed into `body` is stored as the literal text you typed, not as a picture. To give an idea a picture, upload it with create_idea_upload_url and confirm it in `media`: that is the idea's gallery, it is the same file row an inline image would point at, and it is visible on the idea. Placing one INSIDE the prose is a Tensor UI action. If the same URL was saved before, the idea is still created and the response carries `duplicateOf` naming the earlier capture, so you can offer to open that instead. Requires the tensor:ideas:write scope.",
1645
+ {
1646
+ kind: z.enum(IDEA_KINDS).describe("Card-shape hint: link, note, image or video"),
1647
+ title: z.string().optional().describe("Title (max 1024 chars)"),
1648
+ url: z.string().optional().describe("The captured link, if any"),
1649
+ body: z.string().optional().describe("Note text / captured selection. Plain text; the server stores it as a document and derives this text back (max 256000 chars)."),
1650
+ tags: z.array(z.string()).optional().describe("Free-text tags; normalized to trimmed lowercase"),
1651
+ siteName: z.string().optional().describe("Site display name (og:site_name)"),
1652
+ excerpt: z.string().optional().describe("Page excerpt (og:description)"),
1653
+ thumbnailUrl: z.string().optional().describe("Remote preview-image URL \u2014 kept remote, never mirrored into storage"),
1654
+ media: z.array(z.object({
1655
+ storageKey: z.string().describe("The storageKey echoed by create_idea_upload_url, after the bytes were PUT to its url"),
1656
+ filename: z.string().nullable().optional().describe("Original filename, for display"),
1657
+ checksumSha256: z.string().nullable().optional().describe("SHA-256 of the plaintext bytes"),
1658
+ mimeType: z.string().optional().describe("Required for an encrypted (TDE1) upload, where the stored object is opaque; ignored for plaintext"),
1659
+ envelopeVersion: z.union([z.literal(0), z.literal(1)]).optional().describe("The terms the bytes were uploaded under: 1 = TDE1 envelope. Must match what the presign dictated."),
1660
+ chunkSize: z.number().optional().describe("TDE1 frame size used. Required when envelopeVersion is 1."),
1661
+ dek: z.string().optional().describe("Base64 AES-256 key the envelope was encrypted with. Required when envelopeVersion is 1; the server wraps it and never stores it raw.")
1662
+ })).optional().describe("Uploads to confirm into the gallery \u2014 see create_idea_upload_url for the flow")
1663
+ },
1664
+ async (params) => {
1665
+ const data = await api("POST", "/api/ideas", params);
1666
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1667
+ }
1668
+ );
1669
+ server2.tool(
1670
+ "update_idea",
1671
+ "Update an idea (partial). `tags` replaces the whole tag set when provided; `media` APPENDS newly-uploaded objects to the gallery (existing media stay). An edit that would leave no url, no body and no media is refused \u2014 an idea has to be about something. SENDING `body` REPLACES THE WHOLE BODY DOCUMENT, inline images included: an idea's body is a rich document since 4.2.0, your plain text is wrapped into a new one, and anything the old one held that is not text is gone. Read the idea first if you did not write it. The image itself survives in the idea's gallery \u2014 an inline image IS a file row \u2014 so nothing is destroyed, but it stops appearing in the prose. You cannot put one back from here (see create_idea); use `media` to keep it in the gallery. Requires the tensor:ideas:write scope.",
1672
+ {
1673
+ id: z.number().describe("Idea ID"),
1674
+ kind: z.enum(IDEA_KINDS).optional(),
1675
+ title: z.string().nullable().optional(),
1676
+ url: z.string().nullable().optional(),
1677
+ body: z.string().nullable().optional().describe("Plain text; REPLACES the whole body document (inline images included). null clears it. Max 256000 chars."),
1678
+ tags: z.array(z.string()).optional().describe("REPLACES the whole tag set"),
1679
+ siteName: z.string().nullable().optional(),
1680
+ excerpt: z.string().nullable().optional(),
1681
+ thumbnailUrl: z.string().nullable().optional(),
1682
+ media: z.array(z.object({
1683
+ storageKey: z.string().describe("The storageKey echoed by create_idea_upload_url, after the bytes were PUT to its url"),
1684
+ filename: z.string().nullable().optional(),
1685
+ checksumSha256: z.string().nullable().optional(),
1686
+ mimeType: z.string().optional().describe("Required for an encrypted (TDE1) upload"),
1687
+ envelopeVersion: z.union([z.literal(0), z.literal(1)]).optional(),
1688
+ chunkSize: z.number().optional().describe("Required when envelopeVersion is 1"),
1689
+ dek: z.string().optional().describe("Required when envelopeVersion is 1")
1690
+ })).optional().describe("Uploads to APPEND to the gallery")
1691
+ },
1692
+ async ({ id, ...body }) => {
1693
+ const data = await api("PATCH", `/api/ideas/${id}`, body);
1694
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1695
+ }
1696
+ );
1697
+ server2.tool(
1698
+ "delete_idea",
1699
+ "Move an idea to the Trash (soft delete). Restorable with restore_idea; the permanent purge that destroys media bytes is deliberately not reachable with an API key \u2014 it is UI-only, so a key cannot unrecoverably delete an idea. Requires the tensor:ideas:write scope.",
1700
+ { id: z.number().describe("Idea ID") },
1701
+ async ({ id }) => {
1702
+ const data = await api("DELETE", `/api/ideas/${id}`);
1703
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1704
+ }
1705
+ );
1706
+ server2.tool(
1707
+ "restore_idea",
1708
+ "Restore an idea from the Trash back into the live stream. 404 when it is not in the Trash. Requires the tensor:ideas:write scope.",
1709
+ { id: z.number().describe("Idea ID") },
1710
+ async ({ id }) => {
1711
+ const data = await api("POST", `/api/ideas/${id}/restore`);
1712
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1713
+ }
1714
+ );
1715
+ server2.tool(
1716
+ "list_idea_comments",
1717
+ "List an idea's comment thread. Each comment carries bodyJson (the TipTap document) and bodyText (server-derived plain text \u2014 read this one). Requires the tensor:ideas:read scope.",
1718
+ { id: z.number().describe("Idea ID") },
1719
+ async ({ id }) => {
1720
+ const data = await api("GET", `/api/ideas/${id}/comments`);
1721
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1722
+ }
1723
+ );
1724
+ server2.tool(
1725
+ "create_idea_comment",
1726
+ "Comment on an idea. `body` is PLAIN TEXT \u2014 the tool wraps it into the TipTap JSON document Tensor stores (never HTML), one paragraph per line. Empty comments are rejected. Requires the tensor:ideas:write scope.",
1727
+ {
1728
+ id: z.number().describe("Idea ID"),
1729
+ body: z.string().describe("Comment text (plain text; each line becomes a paragraph)")
1730
+ },
1731
+ async ({ id, body }) => {
1732
+ const data = await api("POST", `/api/ideas/${id}/comments`, { bodyJson: tiptapDocJson(body) });
1733
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1734
+ }
1735
+ );
1736
+ server2.tool(
1737
+ "update_idea_comment",
1738
+ "Edit an idea comment YOU wrote \u2014 the server answers 404 for anyone else's, indistinguishable from a missing comment. `body` is plain text and replaces the whole comment; comments cannot be deleted through the API, only edited. Requires the tensor:ideas:write scope.",
1739
+ {
1740
+ id: z.number().describe("Idea ID"),
1741
+ commentId: z.number().describe("Comment ID"),
1742
+ body: z.string().describe("Replacement comment text (plain text)")
1743
+ },
1744
+ async ({ id, commentId, body }) => {
1745
+ const data = await api("PATCH", `/api/ideas/${id}/comments/${commentId}`, { bodyJson: tiptapDocJson(body) });
1746
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1747
+ }
1748
+ );
1749
+ server2.tool(
1750
+ "list_idea_tags",
1751
+ "Every tag in use across live ideas, with counts \u2014 the stream's tag rail. Feed a row's tag into list_ideas' `tag` filter. Requires the tensor:ideas:read scope.",
1752
+ {},
1753
+ async () => {
1754
+ const data = await api("GET", "/api/ideas/tags");
1755
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1756
+ }
1757
+ );
1758
+ server2.tool(
1759
+ "list_idea_sites",
1760
+ "Every source site across live ideas \u2014 bare hosts with counts. Feed a row's site into list_ideas' `site` filter. Requires the tensor:ideas:read scope.",
1761
+ {},
1762
+ async () => {
1763
+ const data = await api("GET", "/api/ideas/sites");
1764
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1765
+ }
1766
+ );
1767
+ server2.tool(
1768
+ "get_idea_media_url",
1769
+ "Mint a short-lived presigned URL for one media object in an idea's gallery. A presigned URL is unauthenticated bearer access to the bytes and it stays in this conversation after the call \u2014 request one only when actually about to fetch, and never re-post it. Every issuance is recorded in Tensor's file access log. The TTL is the Ideas playback one (longer than the files default, so video scrubbing survives). For ENCRYPTED media (envelopeVersion 1) the URL points at ciphertext and the response also carries the raw `dek` \u2014 a permanent, access-logged key release \u2014 with which the client must decrypt the TDE1 envelope itself. Requires the tensor:ideas:read scope AND tensor:files:read: an idea's media IS a file row, the key release is permanent and unrevocable, and no key may grant itself decryption capability over the file library through a side door.",
1770
+ {
1771
+ id: z.number().describe("Idea ID"),
1772
+ mediaId: z.number().describe("Media entry id from get_idea (an idea's media IS a file row; this is that row's id)")
1773
+ },
1774
+ async ({ id, mediaId }) => {
1775
+ const data = await api("GET", `/api/ideas/${id}/media/${mediaId}/url`);
1776
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1777
+ }
1778
+ );
1779
+ server2.tool(
1780
+ "create_idea_upload_url",
1781
+ "Step 1 of attaching media to an idea (presign \u2192 PUT \u2192 confirm): approve filename/type/size and mint a presigned PUT URL plus a storage key. HTTP PUT the raw bytes to `url`, then CONFIRM by passing {storageKey, \u2026} in the `media` array of create_idea or update_idea \u2014 nothing is persisted until that confirm. Same allow-list, same size ceiling and same encryption rule as the files upload: a response with envelopeVersion 1 means the PUT body must be a TDE1 envelope and a plaintext confirm will be rejected. Quota is charged per byte per hour, separately from the files surface. Requires the tensor:ideas:write scope.",
1782
+ {
1783
+ filename: z.string().describe("Original filename. Display data only."),
1784
+ mimeType: z.string().describe("The file's MIME type. Must be on Tensor's upload allow-list."),
1785
+ sizeBytes: z.number().describe("PLAINTEXT byte size of the file"),
1786
+ envelopeVersion: z.union([z.literal(0), z.literal(1)]).optional().describe("Capability announcement: 1 = this client can build a TDE1 envelope. The server decides and echoes the terms."),
1787
+ chunkSize: z.number().optional().describe("Requested TDE1 frame size. Omit for the default; upload under whatever the response echoes.")
1788
+ },
1789
+ async (params) => {
1790
+ const data = await api("POST", "/api/ideas/upload-url", params);
1791
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1792
+ }
1793
+ );
1794
+ server2.tool(
1795
+ "list_idea_links",
1796
+ "List the records an idea is linked to \u2014 rows in the one `links` table, so a row may name any of the six ledger records (entity, institution, account, position, asset, transaction), a todo, another idea, a memo, or a file if a 'related' edge to one was made through the generic links API. NOT the idea's media gallery: those are 'attachment' edges and come back on get_idea as `media`. Each row carries `kind` \u2014 'related' is a link a person made and stays removed when you detach it, 'mention' was written by Tensor's reconciler from another record's prose and comes back the next time that prose is saved. Each row's id is the linkId that detach_idea_link takes, not the target record's id. Requires the tensor:ideas:read scope, and each ROW additionally requires that record type's own read scope \u2014 tensor:portfolio:read for entity/account/position/asset/transaction, tensor:reference:read for institution, tensor:todos:read for a todo, tensor:ideas:read for an idea, tensor:files:read for a file. Rows your key cannot read are omitted silently, so an empty answer means \"none you can read\", not \"none\" \u2014 and a memo row is omitted for EVERY key, because memos are session-only.",
1797
+ { id: z.number().describe("Idea ID") },
1798
+ async ({ id }) => {
1799
+ const data = await api("GET", `/api/ideas/${id}/links`);
1800
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1801
+ }
1802
+ );
1803
+ server2.tool(
1804
+ "attach_idea_link",
1805
+ "Link an idea to another record: one of the six ledger records (entity, institution, account, position, asset, transaction), a todo, another idea, or a memo. The edge is always 'related' \u2014 a link a person meant. Idempotent. Requires the tensor:ideas:write scope AND the target record type's read scope (tensor:portfolio:read, tensor:reference:read for an institution, tensor:todos:read for a todo) \u2014 asserting that an idea is about a record means being allowed to know that record exists, and a denied target is refused out loud rather than dropped. A memo target is therefore refused whatever the key carries, since no scope grants a memo. Files are not in this set: an idea's files are its gallery, uploaded with create_idea_upload_url and confirmed through create_idea / update_idea `media`.",
1806
+ {
1807
+ id: z.number().describe("Idea ID"),
1808
+ targetType: z.enum(IDEA_LINK_TARGET_TYPES).describe("Record kind to link to. Not 'file' \u2014 an idea's files are its gallery."),
1809
+ targetId: z.number().describe("The record's ID")
1810
+ },
1811
+ async ({ id, ...body }) => {
1812
+ const data = await api("POST", `/api/ideas/${id}/links`, body);
1813
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1814
+ }
1815
+ );
1816
+ server2.tool(
1817
+ "detach_idea_link",
1818
+ "Remove one of an idea's links. Only the edge goes; the idea and the record it named are untouched. A linkId naming one of the idea's GALLERY attachments is refused with a 409 rather than removed \u2014 that would take a file out of the gallery through the wrong door. Requires the tensor:ideas:write scope AND the linked record type's read scope (tensor:portfolio:read, tensor:reference:read for an institution, tensor:todos:read for a todo, tensor:files:read for a file) \u2014 the route reads the edge before removing it, so a key cannot unfile a record it is not allowed to see. A linkId naming a 'mention' edge is refused with a 409 too, and for the same shape of reason: that edge is DERIVED from stored prose, Tensor's reconciler re-creates it the next time the text naming the other end is saved, so removing it here would report a detach that undoes itself. Remove the @mention from the text instead. Branch on each row's `kind` from list_idea_links rather than trying the call.",
1819
+ {
1820
+ id: z.number().describe("Idea ID"),
1821
+ linkId: z.number().describe("The link's id from list_idea_links \u2014 not the target record's id")
1822
+ },
1823
+ async ({ id, linkId }) => {
1824
+ const data = await api("DELETE", `/api/ideas/${id}/links/${linkId}`);
714
1825
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
715
1826
  }
716
1827
  );
@@ -743,6 +1854,52 @@ function createApiClient(opts) {
743
1854
  };
744
1855
  }
745
1856
 
1857
+ // package.json
1858
+ var package_default = {
1859
+ name: "@levitating/tensor-mcp",
1860
+ version: "4.4.0",
1861
+ description: "Tensor MCP \u2014 Model Context Protocol server for the Tensor wealth management API. Exposes the Tensor API as tools for Claude, Cursor, Codex, and any MCP-aware client.",
1862
+ type: "module",
1863
+ main: "./dist/index.js",
1864
+ bin: {
1865
+ "tensor-mcp": "dist/index.js"
1866
+ },
1867
+ files: [
1868
+ "dist",
1869
+ "README.md"
1870
+ ],
1871
+ scripts: {
1872
+ build: 'esbuild index.ts --bundle --platform=node --target=node20 --format=esm --outfile=dist/index.js --banner:js="#!/usr/bin/env node" --packages=external && chmod +x dist/index.js',
1873
+ prepublishOnly: "npm run build"
1874
+ },
1875
+ engines: {
1876
+ node: ">=20"
1877
+ },
1878
+ keywords: [
1879
+ "mcp",
1880
+ "model-context-protocol",
1881
+ "tensor",
1882
+ "wealth-management",
1883
+ "claude",
1884
+ "ai-tools"
1885
+ ],
1886
+ homepage: "https://tensor.levitating.org/docs/mcp",
1887
+ repository: {
1888
+ type: "git",
1889
+ url: "git+https://github.com/charleswayn/tensor.git",
1890
+ directory: "mcp-server"
1891
+ },
1892
+ license: "UNLICENSED",
1893
+ dependencies: {
1894
+ "@modelcontextprotocol/sdk": "^1.29.0",
1895
+ zod: "^3.24.2"
1896
+ },
1897
+ devDependencies: {
1898
+ esbuild: "^0.24.0",
1899
+ typescript: "^5.6.0"
1900
+ }
1901
+ };
1902
+
746
1903
  // index.ts
747
1904
  var BASE_URL = (process.env.TENSOR_BASE_URL || "http://localhost:5000").trim();
748
1905
  var API_KEY = (process.env.TENSOR_API_KEY || "").trim();
@@ -752,7 +1909,19 @@ if (!API_KEY) {
752
1909
  }
753
1910
  var server = new McpServer({
754
1911
  name: "tensor",
755
- version: "1.0.0"
1912
+ // READ FROM package.json, NOT TYPED HERE. This is the version the client sees
1913
+ // in the `initialize` response, and a hand-kept copy of a number that lives
1914
+ // somewhere else drifts — twice now. It was 1.0.0 while the package was
1915
+ // 1.4.0, that was fixed by typing a new literal, and by 2026-08-19 it said
1916
+ // 3.0.0 while the package said 4.4.0 and the README documented up to 4.4.0.
1917
+ // The comment above it read "Keep in step with package.json" the whole time,
1918
+ // which is the shape of instruction that does not survive contact with a
1919
+ // release: nothing fails when it is ignored.
1920
+ //
1921
+ // esbuild inlines this at bundle time, so `dist/index.js` carries the literal
1922
+ // and never looks for a file at runtime. smoke:clerk-api-keys asserts the two
1923
+ // cannot disagree again.
1924
+ version: package_default.version
756
1925
  });
757
1926
  registerAllTools(server, createApiClient({ apiKey: API_KEY, baseUrl: BASE_URL }));
758
1927
  async function main() {