@levitating/tensor-mcp 5.3.1 → 6.0.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.
package/dist/index.js CHANGED
@@ -5,7 +5,278 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
6
 
7
7
  // tools.ts
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { toJsonSchemaCompat } from "@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";
10
+ import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
11
+ import { z as z2 } from "zod";
12
+
13
+ // guide.ts
8
14
  import { z } from "zod";
15
+ var SERVER_INSTRUCTIONS = `Tensor is a private family-office workbench. Two halves share one graph:
16
+ - The ledger: entities (people, trusts, companies), accounts, an asset catalog, positions, an append-only transaction ledger, valuations, loans and fund LP capital accounts.
17
+ - The work: todos, ideas (a capture inbox), files, bookmarks and parked tab groups, linked to ledger records and to each other.
18
+
19
+ How to work well here:
20
+ 1. Orient first. search_records finds any record by name or by its reference id (E007 entity, A012 account, P031 position, AS021 asset, T042 transaction, TSK-12 todo, IDEA-7, FILE-12, BMK-3, TAB-5); the other tools take the numeric id it returns, get_entity, get_account, get_position and get_transaction read one record by that id, and get_entity_overview and get_position_overview answer "everything about this one" in a single call. For net worth, cost basis or P/L call get_portfolio_summary and check its coverage field; never add up list_positions yourself.
21
+ 2. The ledger is append-only. A transaction can never be edited or deleted; a mistake is fixed with a compensating entry. Confirm types, amounts and dates with the user before posting, post oldest first, and pass an idempotencyKey on every create_transaction (and any other write that takes one) so a retry cannot write twice.
22
+ 3. More than a handful of ledger writes go through data_dry_run, then the user reviews the preview, then data_apply.
23
+ 4. Todos, ideas, files, bookmarks and tab groups delete into a 60-day Trash and have restore_ tools. An idea the user is done with but wants to keep is archived (archive_idea), not deleted: Archive never expires. list_trash shows what is waiting in every Trash you can read. Ledger and reference deletes (delete_position, delete_entity, delete_account, delete_asset and the catalog deletes), delete_entity_group, delete_bookmark_folder and delete_todo_tag are permanent and take two calls: the first deletes nothing and returns a preview and a confirmToken; show the user, and only after they agree call again with the token. Closing a holding is sell_all_position, not a delete. Only a person can empty a Trash.
24
+ 5. You see what this connection's scopes allow, and only the tools it can use are listed. whoami says who you are connected as (its user id is the assigneeId behind "my todos") and which scopes it holds. A 403 names the missing scope: tell the user instead of working around it. Answers that mix record types (search, links, list_changes) leave out the types you cannot read, so an empty answer can mean "none you can see". Linking or attaching a record also needs that record type's read scope. No connection can reach memos or browsing history, and FX rates, loan terms and fund terms are read-only.
25
+ 6. Lists answer {items, hasMore, nextOffset}: 100 rows unless you pass limit (at most 1000); pass nextOffset as offset for the next page. Filter on the server (filters combine with AND; a value Tensor cannot parse is ignored, which widens the answer) and catch up with list_changes(since) instead of re-reading everything. Times are epoch milliseconds.
26
+ 7. A body you send (todos, ideas, comments) is plain text, one paragraph per line; Tensor stores a document and returns the text as body or bodyText. Sending body replaces the whole body. You can edit only your own comments, and none can be deleted.
27
+ 8. A download or media URL is a bearer link to a private file and stays in this conversation: mint one only right before fetching, and never repost it. Each one is logged.
28
+
29
+ Before an unfamiliar job, call get_guide with a topic: ledger, imports, work, files or safety.`;
30
+ var GUIDE_TOPICS = {
31
+ ledger: {
32
+ title: "The ledger: recording what you own and owe",
33
+ summary: "Entities, accounts, positions and transactions; trades, income, funds, loans, prices and corrections.",
34
+ body: `# The ledger
35
+
36
+ ## The shape
37
+ An **entity** (person, trust, company) owns **accounts** at institutions. A **position** is one holding: an entity's interest in an **asset**, usually inside an account. Every position has a **transaction ledger**, and the position's quantity, average cost, cost basis and realized gain are FOLDED from that ledger in insert order. Valuations (prices and dated marks) are a separate append-only history.
38
+
39
+ Find things before creating them. search_records answers names and reference ids at once; get_entity, get_account, get_position and get_transaction read one by id. Entity groups (list_entity_groups) are named sets of entities, such as a family branch. list_positions filters by entityId, accountId, assetId, assetClass and status; list_assets by symbol, assetClass, linked and q.
40
+
41
+ ## Two kinds of position, chosen at create time
42
+ - **Unitized**: shares, units, coins, a cash balance. Send quantity and averageCost.
43
+ - **Capital account**: a fund LP interest, where the GP reports a balance and there are no units. Send costBasis; that is the only switch. A capital account accepts only the fund transaction types, and fund performance (paid-in, DPI/TVPI, IRR) exists only for one.
44
+ Getting this wrong cannot be fixed by editing later. If you are unsure which a holding is, ask.
45
+
46
+ ## Cost basis and the mark are two numbers
47
+ Cost basis is what was paid; the mark (currentPrice, currentValue) is what it is worth now. Never set a cost field from a market price, and never treat one as the other when reporting.
48
+
49
+ ## Recording activity
50
+ - A trade, income, a fee, a capital call: create_transaction on the position it belongs to. The transactionType sets the direction; quantity and amount are positive magnitudes. Its transactionType and settlement inputs describe every type and the rule for dividends, interest and coupons. Read them before your first post.
51
+ - Entries must go in date order per position. When backfilling, post the oldest first; an entry dated before the position's latest activity is refused.
52
+ - Check for duplicates first: list_transactions with positionId and since, and compare with what you are about to post.
53
+ - An exit is sell_all_position, which keeps the history and books the realized gain. delete_position destroys the position and its whole ledger and is only for a position that should never have existed.
54
+ - Restating totals (the statement says 120 shares and Tensor says 100) is update_position: it appends one adjustment row recording the difference, so history still explains the figure. Prefer a real transaction when you know what happened.
55
+
56
+ ## Correcting a mistake
57
+ There is no edit and no delete for a transaction. Post a compensating entry of the opposite type (a wrong buy is offset by a sell, a wrong capital_call by a return_of_capital) and tell the user both rows will stay visible.
58
+
59
+ ## Prices
60
+ - To make an asset price itself, find the symbol with search_market_quotes (never guess a ticker), then create_asset or update_asset with tickerSymbol, verifyQuote and syncPrice. verify_market_quote checks a symbol without writing.
61
+ - sync_prices and sync_asset_price fetch quotes and WRITE a price row for each asset, repricing its positions. Ask before running them on the whole catalog.
62
+ - update_asset_price records a manual mark for an asset with no feed.
63
+
64
+ ## Reading the totals
65
+ get_portfolio_summary computes net worth, assets, liabilities, cost basis and unrealized P/L in USD, the same way the Tensor dashboard does, optionally grouped by entity, account, assetClass or currency. Its coverage field says how much of the portfolio the figures cover; say so when it is not complete. Liabilities (loans you owe) are positions with liability set.
66
+
67
+ For a fund LP interest, get_fund_performance (or list_fund_performance for every fund) returns paid-in, distributions, unfunded commitment, DPI/TVPI and IRR or time-weighted return, folded the same way as Tensor's fund card. Quote those; do not compute IRR from transactions. They are in the position's currency: convert with list_fx_rates (multiply by rateToUsd). A stale NAV (freshness.stale) and reconciliation.matches false are worth saying.`
68
+ },
69
+ imports: {
70
+ title: "Importing a batch: statements, spreadsheets, backfills",
71
+ summary: "When and how to use data_dry_run and data_apply, and how to avoid double-recording.",
72
+ body: `# Importing a batch
73
+
74
+ Use the batch pipeline when there are more than about ten ledger writes, or whenever the user should see the whole change before anything is written.
75
+
76
+ ## The flow
77
+ 1. Gather the source (a statement, a CSV the user pasted, a list they dictated). Resolve every account, position and asset it names with search_records and the list_ tools. Note what is missing.
78
+ 2. Remove what is already in Tensor: list_transactions per position with since set just before the source's first date.
79
+ 3. Build operations. Each op is one of asset.upsert, asset_price.record, position.open, transaction.record, account.upsert, entity.upsert; data_dry_run's op input lists each one's fields. Up to 500 per batch. Records can be named rather than numbered (accountName, assetSymbol), and the preview tells you when a name is ambiguous.
80
+ 4. Call data_dry_run with a new batchId (for example "stmt-2026-10-schwab-a") and source "mcp". Nothing is written.
81
+ 5. Show the user the preview: what will be created, what will change, every error and needsClarification. Fix problems by running a NEW dry run under a NEW batchId; a batchId is bound to its payload.
82
+ 6. Only after the user says yes, call data_apply with the batchId and the requestHash the dry run returned. It replays exactly the previewed batch and nothing else. Replaying a finished apply returns the stored result, so a retry is safe. If the connection dropped, get_data_batch(batchId) reads the stored preview or result back; do not dry-run again under the same batchId.
83
+ 7. Confirm the result with get_portfolio_summary or list_positions for the accounts touched.
84
+
85
+ ## Small jobs
86
+ A few entries can go straight through create_transaction, oldest first, each with its own idempotencyKey (a stable string such as the statement line's id). Still show the user the list before posting.
87
+
88
+ ## Things that go wrong
89
+ - Signs: amounts and quantities are positive; the type says which way money moved.
90
+ - Dates: epoch milliseconds, and per position in ascending order.
91
+ - Income: say whether it was paid in cash or in units (settlement).
92
+ - Funds: capital accounts take quantity 0 and the money in amount.`
93
+ },
94
+ work: {
95
+ title: "The work surfaces: todos, ideas, bookmarks, tab groups, links and search",
96
+ summary: "How to read and change todos, ideas, bookmarks and tab groups, and how links and search behave.",
97
+ body: `# The work surfaces
98
+
99
+ ## Todos
100
+ - Call list_todo_states first: a todo's stateId must name an existing state, and the state's category (backlog, unstarted, started, completed, canceled) is what "open" and "done" mean. Filter with category, not with a state's name, which each organisation can rename.
101
+ - body is plain text in and is stored as a document; sending body on update_todo replaces the whole body. Read the todo before rewriting a body you did not write.
102
+ - Todos nest (a checklist is sub-todos). Move with set_todo_parent and reorder with reorder_todo. Before deleting a todo with children, call get_todo_subtree and tell the user how many sub-tasks go with it. delete_todo moves the whole branch to Trash; restore_todo brings it back.
103
+ - Tags come from the Todo tag catalog (list_todo_tags); set_todo_tags replaces the whole set.
104
+ - Comments can be edited but not deleted through the API, so write them as you mean them.
105
+
106
+ ## Ideas
107
+ The capture inbox: links, notes and media. create_idea needs at least one of url, body or media. A URL saved before is still created and the answer names the earlier capture in duplicateOf; offer that to the user. Pictures go in the gallery through create_idea_upload_url and the media field, never as an image link typed into body. Sending body on update_idea replaces the whole document.
108
+ An idea that has been handled but is worth keeping is archived with archive_idea, not moved to Trash: it leaves list_ideas (and the tag and site counts), stays readable with get_idea and findable with search_records, keeps its tags, links and media, and never expires. list_ideas with archived true reads the archived ones; unarchive_idea puts one back. Both are idempotent, and an idea in Trash must be restored first. Archiving is its own tool, never an update_idea field.
109
+
110
+ ## Bookmarks
111
+ Leaving folderId off files a bookmark as Unfiled, which is a normal resting place; do not invent a folder for it. Keep the order list_bookmarks and list_bookmark_folders return; the owner arranged it by hand. move_bookmark and move_bookmark_folder change a folder and a place in that order in one call. delete_bookmark is soft, delete_bookmark_folder is not (the bookmarks inside survive, the folder does not).
112
+
113
+ ## Tab groups
114
+ Tab groups are personal: a connection sees only its own person's groups. Park a whole set of tabs in one create_tab_group call, and add more to the end with add_tabs_to_group. Only name, locked and starred are editable. delete_tab removes one tab for good; delete_tab_group is soft.
115
+
116
+ ## Links between records
117
+ attach_todo_link, attach_idea_link and attach_file_link join a record to any ledger record or to another work record; each list_ call returns linkIds for the matching detach_. A link to a record type your connection cannot read is refused when you write it and left out when you read, so an empty list means "none you can see". Links of kind "mention" come from @mentions in prose; remove the mention from the text rather than detaching the link.
118
+
119
+ ## Search
120
+ search_records is one ranked search over every type you can read. It resolves reference ids directly (TSK-12, IDEA-7, AS021). Types your scopes do not cover are left out silently. For market tickers use search_market_quotes instead.
121
+
122
+ ## Keeping up to date
123
+ list_changes(since) returns creates, updates and deletes across everything your scopes can read, kept for 90 days. Resume from the until it returns. When coverage.complete is false, do a full read instead.`
124
+ },
125
+ files: {
126
+ title: "Files: finding, uploading, attaching and downloading",
127
+ summary: "browse_files versus list_files, the three-step upload, encryption, and handling download links safely.",
128
+ body: `# Files
129
+
130
+ ## Finding
131
+ browse_files is the Files page: folders, search by title, files attached to a record (targetType + targetId, and with withDescendants the records beneath it, each row marked with via), or the Trash. list_files is the flat export manifest for backup and mirroring, with checksums. get_file returns one file's metadata and its links. None of these return bytes.
132
+
133
+ ## Uploading (three steps)
134
+ 1. create_file_upload_url with filename, mimeType and sizeBytes. It answers with a presigned PUT URL, a storageKey and the encryption terms.
135
+ 2. PUT the raw bytes to that URL with exactly the approved size.
136
+ 3. confirm_file_upload with the storageKey, plus title, folderId and links to records if wanted. Nothing exists until this step.
137
+ If the presign answers envelopeVersion 1, this server stores files encrypted and the PUT body must be an encrypted envelope built on the client with your own key. If you cannot build one, stop and ask the user to upload the file in the Tensor app, then attach it by id.
138
+
139
+ ## Attaching
140
+ attach_file_link files an existing file against a ledger record, a todo or an idea. attach_todo_file is the todo's own Files pane. An upload can carry links at confirm time.
141
+
142
+ ## Downloading
143
+ get_file_download_url mints a short-lived link that anyone holding it can use, and every one is recorded in the file access log. Request one only when you are about to fetch the bytes, never paste it back to the user unasked, and never request links for a whole library to "check" it. For an encrypted file the answer also releases its decryption key permanently, so the same care applies twice.
144
+
145
+ ## Deleting
146
+ delete_file moves a file to Trash; restore_file brings it back for 60 days. Folders: delete_file_folder refuses a non-empty folder.`
147
+ },
148
+ safety: {
149
+ title: "Safety, permissions and errors",
150
+ summary: "What is permanent, what needs the user's yes, retries, scopes, rate limits and what each error means.",
151
+ body: `# Safety, permissions and errors
152
+
153
+ ## Ask the user before
154
+ - any create_transaction or sell_all_position (the ledger cannot be edited afterwards);
155
+ - data_apply (show the dry-run preview first);
156
+ - every permanent delete: delete_position (takes its whole ledger), delete_entity, delete_account, delete_asset, delete_institution and the other catalog deletes, delete_entity_group, delete_bookmark_folder, delete_tab, delete_todo_tag, delete_todo_state;
157
+ - sync_prices over the whole catalog;
158
+ - minting download links for more than the file the user asked about.
159
+ Tensor enforces the first list's deletes itself: the call answers NOT DELETED with what would go and a confirmToken. Show the user that preview in plain words and pass the token back only after they say yes; never confirm on your own. A refused delete names what still uses the record: tell the user, do not work around it.
160
+ Soft deletes (todos, ideas, files, bookmarks, tab groups) are recoverable for 60 days with the restore_ tools (list_trash finds them), but still say what you are moving to Trash, including a todo's sub-tasks. Trash empties itself after those 60 days; for an idea the user wants to keep but no longer see, archive_idea is the right verb, because Archive never expires.
161
+
162
+ ## Retrying
163
+ Every write a retry could duplicate takes an optional idempotencyKey. Use a fresh unique value per intended write and the SAME value when you retry that write after a timeout or a network error; Tensor then returns the first result instead of writing again. Never reuse a key for a different write.
164
+
165
+ ## What this connection can do
166
+ Each connection carries scopes (portfolio, reference, files, todos, ideas, bookmarks, tabs, each read or write, plus the data pipeline). Only the tools its scopes reach are listed, and a 403 names a missing scope. Some things no connection can do, by design: read memos or browsing history; change FX rates, loan terms or fund terms (they are read-only); empty a Trash or permanently purge; create API keys or change its own access. When you cannot do something, tell the user which scope or which part of the Tensor app it needs.
167
+
168
+ ## Errors
169
+ - 400: the input was refused; the message says which field and why. Fix it rather than retrying as is.
170
+ - 401: the credential is revoked, expired or wrong. The user must reconnect Tensor.
171
+ - 403: a missing scope (named in the message) or something no connection may do. Do not retry.
172
+ - 404: no such record for this connection. Check the id with search_records or a list_ call.
173
+ - 409: a conflict with the record's current state (a cycle, a state still in use, a stale update), an idempotencyKey problem, or delete_blocked (other records still use this one). The message says which.
174
+ - 428: not an error. A permanent delete is waiting for the user's yes; see "Ask the user before".
175
+ - 429: rate limited (an API key allows 120 requests a minute). Wait as told, then continue. Batch work instead of looping single calls.
176
+ - 5xx: Tensor failed. One retry is fine; then report it with the errorId.
177
+
178
+ ## Being a good guest
179
+ Results are compact JSON. Ask for what you need: filter server-side, page with limit and nextOffset, and prefer get_portfolio_summary and list_changes over pulling whole tables.`
180
+ }
181
+ };
182
+ var GUIDE_TOPIC_KEYS = Object.keys(GUIDE_TOPICS);
183
+ function guideText(topic) {
184
+ if (topic) return GUIDE_TOPICS[topic].body;
185
+ const index = GUIDE_TOPIC_KEYS.map((k) => `- ${k}: ${GUIDE_TOPICS[k].summary}`).join("\n");
186
+ return `${SERVER_INSTRUCTIONS}
187
+
188
+ Topics (call get_guide with one):
189
+ ${index}`;
190
+ }
191
+ var guideResourceUri = (topic) => `tensor://guide/${topic}`;
192
+ var GUIDE_PROMPTS = {
193
+ record_statement: {
194
+ title: "Record a statement",
195
+ description: "Turn a brokerage, bank or fund statement into ledger entries, checked against what is already recorded and confirmed before anything is written.",
196
+ args: {
197
+ statement: { description: "The statement text, or a description of the activity to record.", required: true },
198
+ account: { description: "Which account it belongs to, if you know.", required: false }
199
+ },
200
+ text: ({ statement, account }) => `Record the activity in this statement in Tensor's ledger.
201
+
202
+ <statement>
203
+ ${statement ?? ""}
204
+ </statement>
205
+ ${account ? `
206
+ The user says it belongs to: ${account}
207
+ ` : ""}
208
+ Work in this order and do not skip the confirmation:
209
+ 1. If you have not read it in this conversation, call get_guide with topic "ledger".
210
+ 2. Find the account and its positions (search_records, list_accounts, list_positions with accountId). For a holding with no position yet, plan a create_position and decide deliberately between a unitized position and a fund capital account.
211
+ 3. For each position, call list_transactions with positionId and since just before the statement's first date, and drop every entry that is already recorded.
212
+ 4. Show the remaining entries as a table: date, position, type, quantity, amount, price, fees, and settlement for income. Flag anything ambiguous and ask.
213
+ 5. After the user confirms: for more than about ten entries use data_dry_run with transaction.record operations, show the preview, then data_apply. Otherwise post with create_transaction, oldest first, each with its own idempotencyKey.
214
+ 6. Finish with get_portfolio_summary filtered to the account and say what changed.`
215
+ },
216
+ portfolio_review: {
217
+ title: "Review the portfolio",
218
+ description: "A read-only review: totals, concentrations, recent changes and stale or unpriced holdings.",
219
+ args: {
220
+ period: { description: "The period to look back over, for example 'last 30 days' or 'October 2026'. Default: the last 30 days.", required: false }
221
+ },
222
+ text: ({ period }) => `Review the portfolio${period ? ` for ${period}` : " over the last 30 days"}. This is read-only: do not write anything without asking.
223
+
224
+ 1. get_portfolio_summary for the headline, then with groupBy "entity,assetClass,currency". Read coverage before calling any total exact.
225
+ 2. list_changes since the start of the period to see what was recorded. If coverage.complete is false, say the change list is partial.
226
+ 3. Look for stale or missing marks: list_assets with linked false (assets with no price feed) and, for the largest holdings, list_asset_prices to see when they were last priced. If linked assets look stale, offer sync_prices and explain that it writes. For fund interests, list_fund_performance gives each fund's TVPI and IRR or TWR and how old its NAV is.
227
+ 4. Report: net worth, assets and liabilities; the largest positions and concentrations by entity, asset class and currency; what changed in the period; and every holding whose value is old or unpriced.`
228
+ },
229
+ triage_inbox: {
230
+ title: "Triage the inbox",
231
+ description: "Go through recent ideas and open todos and propose what to file, link, turn into a todo, archive or move to Trash.",
232
+ args: {
233
+ limit: { description: "How many recent ideas to look at. Default 20.", required: false }
234
+ },
235
+ text: ({ limit }) => `Triage the user's inbox. Propose first and change nothing until the user agrees.
236
+
237
+ 1. list_ideas with limit ${limit && /^\d+$/.test(limit) ? limit : "20"} for the newest captures, then list_todos once with category "unstarted" and once with "started" for open work.
238
+ 2. For each idea, suggest one of: keep as is, add tags, link it to a record (search_records to find the record), turn it into a todo (create_todo, then attach_todo_link to the idea, then offer to archive the idea), archive it (archive_idea) when it has been handled but is worth keeping, or move it to Trash (delete_idea) only when nobody wants it: Trash is destroyed after 60 days, Archive never expires.
239
+ 3. Point out open todos that look done, duplicated or stale, and todos that should be linked to a ledger record.
240
+ 4. Present the proposals as one list the user can answer item by item, then carry out only what they approve.`
241
+ }
242
+ };
243
+ var GUIDE_PROMPT_NAMES = Object.keys(GUIDE_PROMPTS);
244
+ function registerGuide(server2) {
245
+ for (const key of GUIDE_TOPIC_KEYS) {
246
+ const topic = GUIDE_TOPICS[key];
247
+ const uri = guideResourceUri(key);
248
+ server2.registerResource(
249
+ `guide-${key}`,
250
+ uri,
251
+ { title: topic.title, description: topic.summary, mimeType: "text/markdown" },
252
+ async () => ({ contents: [{ uri, mimeType: "text/markdown", text: topic.body }] })
253
+ );
254
+ }
255
+ for (const [name, prompt] of Object.entries(GUIDE_PROMPTS)) {
256
+ const argsSchema = {};
257
+ for (const [arg, spec] of Object.entries(prompt.args)) {
258
+ argsSchema[arg] = spec.required ? z.string().describe(spec.description) : z.string().optional().describe(spec.description);
259
+ }
260
+ server2.registerPrompt.call(
261
+ server2,
262
+ name,
263
+ { title: prompt.title, description: prompt.description, argsSchema },
264
+ (args) => ({
265
+ messages: [{ role: "user", content: { type: "text", text: prompt.text(args ?? {}) } }]
266
+ })
267
+ );
268
+ }
269
+ }
270
+
271
+ // tools.ts
272
+ var ApiError = class extends Error {
273
+ constructor(message, status, body) {
274
+ super(message);
275
+ this.status = status;
276
+ this.body = body;
277
+ this.name = "ApiError";
278
+ }
279
+ };
9
280
  var RECORD_TARGET_TYPES = [
10
281
  "entity",
11
282
  "institution",
@@ -87,319 +358,638 @@ function numListParam(value) {
87
358
  const list = Array.isArray(value) ? value : [value];
88
359
  return list.length ? list.join(",") : void 0;
89
360
  }
90
- function registerAllTools(server2, api) {
361
+ var OPEN_WORLD_TOOLS = new Set("search_market_quotes verify_market_quote sync_prices sync_asset_price".split(" "));
362
+ var EXTRA_READ_ONLY_TOOLS = new Set("browse_files search_records search_market_quotes verify_market_quote whoami".split(" "));
363
+ var IDEMPOTENT_WRITE_PREFIXES = ["update_", "delete_", "restore_", "archive_", "unarchive_", "set_", "detach_", "reorder_", "move_"];
364
+ var NOT_IDEMPOTENT_TOOLS = new Set("update_asset_price".split(" "));
365
+ var NO_KEY_TOOLS = new Set("create_file_upload_url create_idea_upload_url".split(" "));
366
+ var DESTRUCTIVE_WRITE_PREFIXES = ["delete_", "update_", "set_", "detach_", "reorder_", "move_"];
367
+ var EXTRA_DESTRUCTIVE_TOOLS = new Set("data_apply sell_all_position".split(" "));
368
+ var TOOL_SCOPE_LISTS = {
369
+ none: "get_guide whoami search_records list_trash",
370
+ "tensor:portfolio:read": "get_entity_overview get_position_overview list_entities list_entity_relationships list_accounts list_assets get_asset list_asset_prices list_positions list_position_events list_events list_position_relations list_transactions get_portfolio_summary list_fund_performance get_fund_performance list_fund_terms get_fund_terms list_loan_terms get_loan_terms list_fx_rates search_market_quotes verify_market_quote list_changes get_entity get_account get_position get_transaction list_entity_groups",
371
+ "tensor:portfolio:write": "create_entity update_entity delete_entity create_entity_relationship update_entity_relationship delete_entity_relationship create_account update_account delete_account create_asset update_asset delete_asset update_asset_price create_position update_position delete_position sell_all_position create_position_relation delete_position_relation create_transaction sync_prices sync_asset_price create_entity_group update_entity_group delete_entity_group",
372
+ "tensor:reference:read": "list_institutions list_entity_types list_role_types list_account_types list_asset_classes",
373
+ "tensor:reference:write": "create_institution update_institution delete_institution create_entity_type update_entity_type delete_entity_type create_role_type update_role_type delete_role_type create_account_type update_account_type delete_account_type create_asset_class update_asset_class delete_asset_class",
374
+ "tensor:data:read": "get_data_batch",
375
+ "tensor:data:dry_run": "data_dry_run",
376
+ "tensor:data:apply": "data_apply",
377
+ "tensor:files:read": "list_files browse_files get_file get_file_download_url list_file_links list_file_folders",
378
+ "tensor:files:write": "create_file_upload_url confirm_file_upload update_file delete_file restore_file attach_file_link detach_file_link create_file_folder update_file_folder delete_file_folder",
379
+ "tensor:todos:read": "list_todos get_todo get_todo_subtree get_todo_activity list_todo_comments list_todo_states list_todo_tags list_todo_files list_todo_links",
380
+ "tensor:todos:write": "create_todo update_todo delete_todo restore_todo set_todo_parent reorder_todo set_todo_tags create_todo_comment update_todo_comment create_todo_state update_todo_state delete_todo_state create_todo_tag update_todo_tag delete_todo_tag attach_todo_file detach_todo_file attach_todo_link detach_todo_link",
381
+ "tensor:ideas:read": "list_ideas get_idea list_idea_comments list_idea_tags list_idea_sites get_idea_media_url list_idea_links list_idea_kinds",
382
+ "tensor:ideas:write": "create_idea update_idea delete_idea restore_idea archive_idea unarchive_idea create_idea_comment update_idea_comment create_idea_upload_url attach_idea_link detach_idea_link",
383
+ "tensor:bookmarks:read": "list_bookmarks get_bookmark list_bookmark_folders",
384
+ "tensor:bookmarks:write": "create_bookmark update_bookmark delete_bookmark restore_bookmark create_bookmark_folder update_bookmark_folder delete_bookmark_folder move_bookmark move_bookmark_folder",
385
+ "tensor:tabs:read": "list_tab_groups get_tab_group",
386
+ "tensor:tabs:write": "create_tab_group update_tab_group delete_tab delete_tab_group restore_tab_group add_tabs_to_group"
387
+ };
388
+ var TOOL_SCOPE = new Map(
389
+ Object.entries(TOOL_SCOPE_LISTS).flatMap(([scope, names]) => names.split(" ").map((name) => [name, scope === "none" ? null : scope]))
390
+ );
391
+ var TOOLSETS = ["ledger", "work", "files", "web"];
392
+ var TOOLSET_OF_DOMAIN = {
393
+ portfolio: "ledger",
394
+ reference: "ledger",
395
+ data: "ledger",
396
+ todos: "work",
397
+ ideas: "work",
398
+ files: "files",
399
+ bookmarks: "web",
400
+ tabs: "web"
401
+ };
402
+ function toolsetOf(scope) {
403
+ if (scope === null) return null;
404
+ const toolset = TOOLSET_OF_DOMAIN[scope.split(":")[1] ?? ""];
405
+ if (!toolset) throw new Error(`MCP scope ${scope} has no toolset (TOOLSET_OF_DOMAIN, mcp-server/tools.ts).`);
406
+ return toolset;
407
+ }
408
+ function parseToolsets(raw) {
409
+ if (!raw || !raw.trim()) return null;
410
+ const picked = raw.split(",").map((s) => s.trim().toLowerCase()).filter((s) => TOOLSETS.includes(s));
411
+ return picked.length ? picked.filter((t, i) => picked.indexOf(t) === i) : null;
412
+ }
413
+ function parseFlag(raw) {
414
+ return typeof raw === "string" && /^(1|true|yes)$/i.test(raw.trim());
415
+ }
416
+ function titleOf(name) {
417
+ const words = name.split("_");
418
+ return [words[0].charAt(0).toUpperCase() + words[0].slice(1), ...words.slice(1)].join(" ");
419
+ }
420
+ function toolAnnotations(name) {
421
+ const readOnly = name.startsWith("list_") || name.startsWith("get_") || EXTRA_READ_ONLY_TOOLS.has(name);
422
+ const openWorldHint = OPEN_WORLD_TOOLS.has(name);
423
+ if (readOnly) return { title: titleOf(name), readOnlyHint: true, openWorldHint };
424
+ const destructive = DESTRUCTIVE_WRITE_PREFIXES.some((p) => name.startsWith(p)) || EXTRA_DESTRUCTIVE_TOOLS.has(name);
425
+ const idempotent = IDEMPOTENT_WRITE_PREFIXES.some((p) => name.startsWith(p)) && !NOT_IDEMPOTENT_TOOLS.has(name);
426
+ return {
427
+ title: titleOf(name),
428
+ readOnlyHint: false,
429
+ ...destructive ? {} : { destructiveHint: false },
430
+ ...idempotent ? { idempotentHint: true } : {},
431
+ openWorldHint
432
+ };
433
+ }
434
+ function isIdempotentTool(name) {
435
+ const a = toolAnnotations(name);
436
+ return a.readOnlyHint || a.idempotentHint === true;
437
+ }
438
+ function toolTakesIdempotencyKey(name) {
439
+ return !isIdempotentTool(name) && !name.startsWith("data_") && !NO_KEY_TOOLS.has(name);
440
+ }
441
+ var CONFIRM_TOKEN_INPUT = z2.string().min(1).max(200).optional().describe("Omit on the first call. Then the token it returned, only after the user agreed.");
442
+ function confirmationResult(body) {
443
+ const b = body ?? {};
444
+ const until = typeof b.expiresAt === "number" ? ` before ${new Date(b.expiresAt).toISOString()}` : "";
445
+ const why = b.code === "confirmation_stale" ? "What it would remove changed since the last preview, so nothing was deleted. " : b.code === "confirmation_invalid" ? "That confirmToken was not accepted (expired, used, or for another record), so nothing was deleted. " : "";
446
+ return {
447
+ content: [{
448
+ type: "text",
449
+ text: `NOT DELETED. ${why}This delete is permanent, so Tensor wants the user's confirmation first. Show the user the preview below and ask. Only if they agree, call this tool again with the same id and confirmToken ${JSON.stringify(b.confirmToken ?? null)}${until}. Do not confirm on the user's behalf.
450
+ ` + JSON.stringify({ preview: b.preview ?? null, confirmToken: b.confirmToken ?? null, expiresAt: b.expiresAt ?? null })
451
+ }]
452
+ };
453
+ }
454
+ async function confirmable(call) {
455
+ try {
456
+ return { content: [{ type: "text", text: JSON.stringify(await call()) }] };
457
+ } catch (e) {
458
+ if (e?.status === 428) return confirmationResult(e.body);
459
+ throw e;
460
+ }
461
+ }
462
+ var LIST_DEFAULT_LIMIT = 100;
463
+ var LIST_MAX_LIMIT = 1e3;
464
+ var LIMIT_INPUT = z2.number().int().min(1).max(LIST_MAX_LIMIT).optional().describe("Default 100, max 1000.");
465
+ var OFFSET_INPUT = z2.number().int().min(0).optional().describe("nextOffset from the previous page.");
466
+ async function listPage(params, limit, offset, fetchPage) {
467
+ const take = limit ?? LIST_DEFAULT_LIMIT;
468
+ const from = offset ?? 0;
469
+ params.set("limit", String(take + 1));
470
+ if (from > 0) params.set("offset", String(from));
471
+ const data = await fetchPage(params.toString());
472
+ if (!Array.isArray(data)) return { content: [{ type: "text", text: JSON.stringify(data) }] };
473
+ const inherited = (row) => typeof row === "object" && row !== null && row.via != null;
474
+ const own = data.filter((row) => !inherited(row));
475
+ const hasMore = own.length > take;
476
+ const items = [...own.slice(0, take), ...data.filter(inherited)];
477
+ return { content: [{ type: "text", text: JSON.stringify({ items, hasMore, nextOffset: hasMore ? from + take : null }) }] };
478
+ }
479
+ var OVERVIEW_ROWS = 200;
480
+ function capped(rows) {
481
+ if (!Array.isArray(rows) || rows.length <= OVERVIEW_ROWS) return rows;
482
+ return { items: rows.slice(0, OVERVIEW_ROWS), hasMore: true, note: "More than 200; page through the list tool." };
483
+ }
484
+ async function unlessMissing(call) {
485
+ try {
486
+ return await call;
487
+ } catch (e) {
488
+ if (e?.status === 404) return null;
489
+ throw e;
490
+ }
491
+ }
492
+ var IDEMPOTENCY_KEY_INPUT = z2.string().min(1).max(200).optional().describe("Send the same value on a retry and it is written once.");
493
+ var CALL_CLIENT = new AsyncLocalStorage();
494
+ var CALL_KEY = new AsyncLocalStorage();
495
+ var DEFINITIONS = null;
496
+ function toolDefinitions() {
497
+ if (DEFINITIONS) return DEFINITIONS;
498
+ const definitions = [];
499
+ const collector = {
500
+ tool: (name, description, shape, handler) => {
501
+ const scope = TOOL_SCOPE.get(name);
502
+ if (scope === void 0) {
503
+ throw new Error(`MCP tool ${name} has no entry in TOOL_SCOPE_LISTS (mcp-server/tools.ts).`);
504
+ }
505
+ const takesKey = toolTakesIdempotencyKey(name);
506
+ definitions.push({
507
+ name,
508
+ scope,
509
+ description,
510
+ shape: takesKey ? { ...shape, idempotencyKey: IDEMPOTENCY_KEY_INPUT } : shape,
511
+ annotations: toolAnnotations(name),
512
+ handler: takesKey ? (args, extra) => {
513
+ const { idempotencyKey, ...rest } = args ?? {};
514
+ if (typeof idempotencyKey !== "string" || !idempotencyKey) return handler(rest, extra);
515
+ return CALL_KEY.run({ base: idempotencyKey, writes: 0 }, () => handler(rest, extra));
516
+ } : handler
517
+ });
518
+ }
519
+ };
520
+ const api2 = (method, path, body, options) => {
521
+ const client = CALL_CLIENT.getStore();
522
+ if (!client) throw new Error("A Tensor MCP tool ran without a client bound (registerAllTools binds one per call).");
523
+ return client(method, path, body, { ...options, idempotencyKey: idempotencyKeyFor(CALL_KEY, method) });
524
+ };
525
+ defineTools(collector, api2);
526
+ for (const d of definitions) toolsetOf(d.scope);
527
+ DEFINITIONS = definitions;
528
+ return definitions;
529
+ }
530
+ function selected(definition, filter, usable) {
531
+ if (usable && definition.scope !== null && !usable.has(definition.scope)) return false;
532
+ if (filter.readOnly && !definition.annotations.readOnlyHint) return false;
533
+ const toolset = toolsetOf(definition.scope);
534
+ if (filter.toolsets && toolset !== null && !filter.toolsets.includes(toolset)) return false;
535
+ return true;
536
+ }
537
+ var LISTED = /* @__PURE__ */ new WeakMap();
538
+ function listedTool(definition) {
539
+ let listed = LISTED.get(definition);
540
+ if (!listed) {
541
+ const inputSchema = toJsonSchemaCompat(z2.object(definition.shape), { strictUnions: true, pipeStrategy: "input" });
542
+ delete inputSchema.$schema;
543
+ listed = { name: definition.name, description: definition.description, inputSchema, annotations: definition.annotations };
544
+ LISTED.set(definition, listed);
545
+ }
546
+ return listed;
547
+ }
548
+ function idempotencyKeyFor(keyStore, method) {
549
+ if (method === "GET") return void 0;
550
+ const state = keyStore.getStore();
551
+ if (!state) return void 0;
552
+ state.writes += 1;
553
+ return state.writes === 1 ? state.base : `${state.base}#${state.writes}`;
554
+ }
555
+ function describeApiFailure(method, path, status, text, retryAfter) {
556
+ let parsed = null;
557
+ try {
558
+ parsed = JSON.parse(text);
559
+ } catch {
560
+ }
561
+ const required = parsed?.requiredScope ?? parsed?.details?.requiredScope;
562
+ let advice = "";
563
+ if (status === 401) {
564
+ advice = "The credential was not accepted (revoked, expired or mistyped). Ask the user to reconnect Tensor.";
565
+ } else if (status === 403 && /rate limited/i.test(typeof parsed?.error === "string" ? parsed.error : text)) {
566
+ advice = "Rate limited. Wait a minute before calling Tensor again, and batch work instead of looping single calls.";
567
+ } else if (status === 403 && typeof required === "string") {
568
+ advice = `This connection lacks the ${required} scope. Ask the user to add it to this connection in Tensor \u2192 Developer \u2192 Access, or do without this tool.`;
569
+ } else if (status === 403) {
570
+ advice = "Tensor refused this for this credential. Do not retry; tell the user what was refused.";
571
+ } else if (status === 404) {
572
+ advice = "No such record for this credential \u2014 check the id with a list_ or search_records call.";
573
+ } else if (status === 409 && parsed?.code === "idempotency_in_flight") {
574
+ advice = "The first attempt is still running. Retry in a few seconds with the same idempotencyKey.";
575
+ } else if (status === 409 && parsed?.code === "idempotency_key_conflict") {
576
+ advice = "That idempotencyKey was already used with different arguments. Use a new key for a new write.";
577
+ } else if (status === 409 && parsed?.code === "delete_blocked") {
578
+ advice = "Other records still use this one (preview.blockedBy). Tell the user what they are; it can be deleted only after those are moved or deleted.";
579
+ } else if (status === 428) {
580
+ advice = "Not deleted: Tensor wants the user's confirmation. Show them the preview; only if they agree, repeat the call with the confirmToken.";
581
+ } else if (status === 409) {
582
+ advice = "Conflict with the record's current state; read it again before deciding what to do.";
583
+ } else if (status === 413) {
584
+ advice = "The request is too large; split it into smaller calls.";
585
+ } else if (status === 429) {
586
+ advice = `Rate limited. Wait${retryAfter ? ` ${retryAfter} seconds` : " a minute"} before calling Tensor again.`;
587
+ } else if (status >= 500) {
588
+ advice = "Tensor failed on its side. One retry is reasonable; if it fails again, tell the user and quote the errorId.";
589
+ }
590
+ const message = typeof parsed?.error === "string" ? parsed.error : text;
591
+ return `Tensor API ${method} ${path} \u2192 ${status}: ${message}${advice ? `
592
+ ${advice}` : ""}${typeof parsed?.error === "string" ? `
593
+ ${text}` : ""}`;
594
+ }
595
+ function registerAllTools(target, client, filter = {}) {
596
+ const usable = filter.scopes ? new Set(filter.scopes) : null;
597
+ const chosen = toolDefinitions().filter((d) => selected(d, filter, usable));
598
+ for (const d of chosen) {
599
+ target.tool(
600
+ d.name,
601
+ d.description,
602
+ d.shape,
603
+ d.annotations,
604
+ (args, extra) => CALL_CLIENT.run(client, () => d.handler(args, extra))
605
+ );
606
+ }
607
+ const protocol = target.server;
608
+ if (chosen.length > 0 && typeof protocol?.setRequestHandler === "function") {
609
+ const tools = chosen.map(listedTool);
610
+ protocol.setRequestHandler(ListToolsRequestSchema, () => ({ tools }));
611
+ }
612
+ }
613
+ function defineTools(server2, api2) {
614
+ server2.tool(
615
+ "get_guide",
616
+ // Topic keys only: the summaries are in the no-topic answer, which an
617
+ // agent reads when it needs them, rather than in every tools/list.
618
+ "How to use Tensor well: which tool first, the order a job goes in, what needs the user's yes. No topic: the overview. Read a topic before an unfamiliar job: " + GUIDE_TOPIC_KEYS.join(", ") + ".",
619
+ { topic: z2.enum(GUIDE_TOPIC_KEYS).optional().describe("The topic to read. Omit for the overview and the list of topics.") },
620
+ async ({ topic }) => ({ content: [{ type: "text", text: guideText(topic) }] })
621
+ );
622
+ server2.tool(
623
+ "whoami",
624
+ 'Who this connection is: user (id, role), organization (base currency, timezone), credential and its name, scopes held and `effectiveScopes` (after the person\'s role), rate limit. Your user id is the assigneeId for "my todos". Only tools effectiveScopes reach are listed.',
625
+ {},
626
+ async () => {
627
+ const data = await api2("GET", "/api/v1/whoami");
628
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
629
+ }
630
+ );
91
631
  server2.tool(
92
632
  "list_entities",
93
- "List all entities (people, trusts, companies) in the organization. Requires the tensor:portfolio:read scope.",
94
- { limit: z.number().optional().describe("Max results to return"), offset: z.number().optional().describe("Pagination offset") },
633
+ "List entities (people, trusts, companies).",
634
+ { limit: LIMIT_INPUT, offset: OFFSET_INPUT },
95
635
  async ({ limit, offset }) => {
96
636
  const params = new URLSearchParams();
97
- if (limit) params.set("limit", String(limit));
98
- if (offset) params.set("offset", String(offset));
99
- const qs = params.toString();
100
- const data = await api("GET", `/api/entities${qs ? `?${qs}` : ""}`);
101
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
637
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/entities?${qs}`));
638
+ }
639
+ );
640
+ server2.tool(
641
+ "get_entity",
642
+ "One entity by id.",
643
+ { id: z2.number().describe("Entity ID") },
644
+ async ({ id }) => {
645
+ const data = await api2("GET", `/api/entities/${id}`);
646
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
647
+ }
648
+ );
649
+ server2.tool(
650
+ "get_entity_overview",
651
+ "Everything about one entity in one call: the entity, its accounts, its active positions, and its totals by asset class (net worth, cost basis, unrealized P/L) from get_portfolio_summary's fold. Start here for a question about one person, trust or company.",
652
+ { id: z2.number().describe("Entity ID") },
653
+ async ({ id }) => {
654
+ const [entity, accounts, positions, summary] = await Promise.all([
655
+ api2("GET", `/api/entities/${id}`),
656
+ api2("GET", `/api/accounts?entityId=${id}&limit=${OVERVIEW_ROWS + 1}`),
657
+ api2("GET", `/api/positions?entityId=${id}&status=active&limit=${OVERVIEW_ROWS + 1}`),
658
+ api2("GET", `/api/v1/portfolio/summary?entityId=${id}&scope=all&groupBy=assetClass`)
659
+ ]);
660
+ return {
661
+ content: [{
662
+ type: "text",
663
+ text: JSON.stringify({ entity, accounts: capped(accounts), positions: capped(positions), summary })
664
+ }]
665
+ };
102
666
  }
103
667
  );
104
668
  server2.tool(
105
669
  "create_entity",
106
- "Create a new entity (person, trust, or company). Requires the tensor:portfolio:write scope.",
670
+ "Create an entity (person, trust or company).",
107
671
  {
108
- name: z.string().describe("Entity name"),
109
- type: z.string().describe("Entity type key (e.g. 'Individual', 'Trust', 'LLC'). Must match an existing entity-types row."),
110
- jurisdiction: z.string().optional().describe("Legal jurisdiction (e.g. 'Delaware', 'California')"),
111
- formedDate: z.string().optional().describe("Formation/birth date in ISO format YYYY-MM-DD"),
112
- tags: z.array(z.string()).optional().describe("Array of tag strings (max 32 tags, each max 64 chars)"),
113
- showInPortfolio: z.boolean().optional().describe("Whether to include in portfolio views. Default: true"),
114
- notes: z.string().optional().describe("Free-form notes")
672
+ name: z2.string().describe("Entity name"),
673
+ type: z2.string().describe("Entity type key from list_entity_types (Individual, Trust, LLC)."),
674
+ jurisdiction: z2.string().optional().describe("Legal jurisdiction (e.g. 'Delaware', 'California')"),
675
+ formedDate: z2.string().optional().describe("Formation/birth date in ISO format YYYY-MM-DD"),
676
+ tags: z2.array(z2.string()).optional().describe("Array of tag strings (max 32 tags, each max 64 chars)"),
677
+ showInPortfolio: z2.boolean().optional().describe("Whether to include in portfolio views. Default: true"),
678
+ notes: z2.string().optional().describe("Free-form notes")
115
679
  },
116
680
  async (params) => {
117
- const data = await api("POST", "/api/entities", params);
118
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
681
+ const data = await api2("POST", "/api/entities", params);
682
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
119
683
  }
120
684
  );
121
685
  server2.tool(
122
686
  "update_entity",
123
- "Update an existing entity (partial update). Requires the tensor:portfolio:write scope.",
687
+ "Edit an entity. Only the fields sent change.",
124
688
  {
125
- id: z.number().describe("Entity ID to update"),
126
- name: z.string().optional().describe("New entity name"),
127
- type: z.string().optional().describe("New entity type key"),
128
- jurisdiction: z.string().optional().describe("Legal jurisdiction"),
129
- formedDate: z.string().optional().describe("Formation/birth date YYYY-MM-DD"),
130
- tags: z.array(z.string()).optional(),
131
- showInPortfolio: z.boolean().optional(),
132
- notes: z.string().optional()
689
+ id: z2.number().describe("Entity ID to update"),
690
+ name: z2.string().optional().describe("New entity name"),
691
+ type: z2.string().optional().describe("New entity type key"),
692
+ jurisdiction: z2.string().optional().describe("Legal jurisdiction"),
693
+ formedDate: z2.string().optional().describe("Formation/birth date YYYY-MM-DD"),
694
+ tags: z2.array(z2.string()).optional(),
695
+ showInPortfolio: z2.boolean().optional(),
696
+ notes: z2.string().optional()
133
697
  },
134
698
  async ({ id, ...body }) => {
135
- const data = await api("PATCH", `/api/entities/${id}`, body);
136
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
699
+ const data = await api2("PATCH", `/api/entities/${id}`, body);
700
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
137
701
  }
138
702
  );
139
703
  server2.tool(
140
704
  "delete_entity",
141
- "Delete an entity by ID. Requires the tensor:portfolio:write scope.",
142
- { id: z.number().describe("Entity ID to delete") },
143
- async ({ id }) => {
144
- const data = await api("DELETE", `/api/entities/${id}`);
145
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
146
- }
705
+ "Delete an entity. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
706
+ { id: z2.number().describe("Entity ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
707
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/entities/${id}`, void 0, { confirmToken }))
147
708
  );
148
709
  server2.tool(
149
710
  "list_entity_relationships",
150
- "List all entity relationships (ownership, beneficiary, etc.). Requires the tensor:portfolio:read scope.",
151
- { limit: z.number().optional(), offset: z.number().optional() },
711
+ "List relationships between entities (ownership, beneficiary, trustee).",
712
+ { limit: LIMIT_INPUT, offset: OFFSET_INPUT },
152
713
  async ({ limit, offset }) => {
153
714
  const params = new URLSearchParams();
154
- if (limit) params.set("limit", String(limit));
155
- if (offset) params.set("offset", String(offset));
156
- const qs = params.toString();
157
- const data = await api("GET", `/api/entity-relationships${qs ? `?${qs}` : ""}`);
158
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
715
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/entity-relationships?${qs}`));
159
716
  }
160
717
  );
161
718
  server2.tool(
162
719
  "create_entity_relationship",
163
- "Create a relationship between two entities (ownership, beneficiary, trustee, etc.). Requires the tensor:portfolio:write scope.",
164
- {
165
- sourceEntityId: z.number().describe("Source entity ID (the parent/owner)"),
166
- targetEntityId: z.number().describe("Target entity ID (the child/owned)"),
167
- relationshipType: z.string().optional().describe("Relationship type. Default: 'ownership'"),
168
- roleType: z.string().optional().describe("Role type key (e.g. 'Trustee', 'Beneficiary'). Free-form string keyed against role-types catalog."),
169
- ownershipPercent: z.number().optional().describe("Ownership percentage as a number (e.g. 51.5 for 51.5%)"),
170
- title: z.string().optional().describe("Display title for this relationship"),
171
- label: z.string().optional().describe("Short label"),
172
- effectiveDate: z.string().optional().describe("Effective date YYYY-MM-DD"),
173
- notes: z.string().optional()
720
+ "Relate two entities (ownership, beneficiary, trustee).",
721
+ {
722
+ sourceEntityId: z2.number().describe("Source entity ID (the parent/owner)"),
723
+ targetEntityId: z2.number().describe("Target entity ID (the child/owned)"),
724
+ relationshipType: z2.string().optional().describe("Relationship type. Default: 'ownership'"),
725
+ roleType: z2.string().optional().describe("Role type key from list_role_types (Trustee, Beneficiary)."),
726
+ ownershipPercent: z2.number().optional().describe("Ownership percentage as a number (e.g. 51.5 for 51.5%)"),
727
+ title: z2.string().optional().describe("Display title for this relationship"),
728
+ label: z2.string().optional().describe("Short label"),
729
+ effectiveDate: z2.string().optional().describe("Effective date YYYY-MM-DD"),
730
+ notes: z2.string().optional()
174
731
  },
175
732
  async (params) => {
176
- const data = await api("POST", "/api/entity-relationships", params);
177
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
733
+ const data = await api2("POST", "/api/entity-relationships", params);
734
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
178
735
  }
179
736
  );
180
737
  server2.tool(
181
738
  "update_entity_relationship",
182
- "Update an entity relationship (partial update). Requires the tensor:portfolio:write scope.",
183
- {
184
- id: z.number().describe("Relationship ID"),
185
- sourceEntityId: z.number().optional(),
186
- targetEntityId: z.number().optional(),
187
- relationshipType: z.string().optional(),
188
- roleType: z.string().optional(),
189
- ownershipPercent: z.number().optional(),
190
- title: z.string().optional(),
191
- label: z.string().optional(),
192
- effectiveDate: z.string().optional(),
193
- notes: z.string().optional()
739
+ "Edit an entity relationship. Only the fields sent change.",
740
+ {
741
+ id: z2.number().describe("Relationship ID"),
742
+ sourceEntityId: z2.number().optional(),
743
+ targetEntityId: z2.number().optional(),
744
+ relationshipType: z2.string().optional(),
745
+ roleType: z2.string().optional(),
746
+ ownershipPercent: z2.number().optional(),
747
+ title: z2.string().optional(),
748
+ label: z2.string().optional(),
749
+ effectiveDate: z2.string().optional(),
750
+ notes: z2.string().optional()
194
751
  },
195
752
  async ({ id, ...body }) => {
196
- const data = await api("PATCH", `/api/entity-relationships/${id}`, body);
197
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
753
+ const data = await api2("PATCH", `/api/entity-relationships/${id}`, body);
754
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
198
755
  }
199
756
  );
200
757
  server2.tool(
201
758
  "delete_entity_relationship",
202
- "Delete an entity relationship. Requires the tensor:portfolio:write scope.",
203
- { id: z.number().describe("Relationship ID to delete") },
759
+ "Delete an entity relationship.",
760
+ { id: z2.number().describe("Relationship ID to delete") },
204
761
  async ({ id }) => {
205
- const data = await api("DELETE", `/api/entity-relationships/${id}`);
206
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
762
+ const data = await api2("DELETE", `/api/entity-relationships/${id}`);
763
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
764
+ }
765
+ );
766
+ server2.tool(
767
+ "list_entity_groups",
768
+ "List entity groups (a family branch, one deal's vehicles), each with its member entityIds.",
769
+ {},
770
+ async () => {
771
+ const data = await api2("GET", "/api/entity-groups");
772
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
207
773
  }
208
774
  );
775
+ server2.tool(
776
+ "create_entity_group",
777
+ "Create an entity group.",
778
+ {
779
+ name: z2.string().describe("Group name"),
780
+ entityIds: z2.array(z2.number()).optional().describe("Member entity ids. Ids not in this organization are dropped, not refused."),
781
+ showOnDashboard: z2.boolean().optional().describe("Show the group on the Overview. Default true."),
782
+ notes: z2.string().nullable().optional().describe("Free-text notes")
783
+ },
784
+ async (params) => {
785
+ const data = await api2("POST", "/api/entity-groups", params);
786
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
787
+ }
788
+ );
789
+ server2.tool(
790
+ "update_entity_group",
791
+ "Edit an entity group. entityIds REPLACES the member list: to add one, send the current ids plus the new one; omit it to keep membership.",
792
+ {
793
+ id: z2.number().describe("Entity group ID"),
794
+ name: z2.string().optional().describe("New name"),
795
+ entityIds: z2.array(z2.number()).optional().describe("The complete member list after the edit. Ids not in this organization are dropped."),
796
+ showOnDashboard: z2.boolean().optional(),
797
+ notes: z2.string().nullable().optional()
798
+ },
799
+ async ({ id, ...body }) => {
800
+ const data = await api2("PATCH", `/api/entity-groups/${id}`, body);
801
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
802
+ }
803
+ );
804
+ server2.tool(
805
+ "delete_entity_group",
806
+ "Delete an entity group; its entities stay. No Trash. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
807
+ { id: z2.number().describe("Entity group ID"), confirmToken: CONFIRM_TOKEN_INPUT },
808
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/entity-groups/${id}`, void 0, { confirmToken }))
809
+ );
209
810
  server2.tool(
210
811
  "list_accounts",
211
- "List all accounts (brokerage, bank, retirement, etc.) in the organization. Requires the tensor:portfolio:read scope.",
212
- { limit: z.number().optional(), offset: z.number().optional() },
812
+ "List accounts (brokerage, bank, retirement).",
813
+ { limit: LIMIT_INPUT, offset: OFFSET_INPUT },
213
814
  async ({ limit, offset }) => {
214
815
  const params = new URLSearchParams();
215
- if (limit) params.set("limit", String(limit));
216
- if (offset) params.set("offset", String(offset));
217
- const qs = params.toString();
218
- const data = await api("GET", `/api/accounts${qs ? `?${qs}` : ""}`);
219
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
816
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/accounts?${qs}`));
817
+ }
818
+ );
819
+ server2.tool(
820
+ "get_account",
821
+ "One account by id.",
822
+ { id: z2.number().describe("Account ID") },
823
+ async ({ id }) => {
824
+ const data = await api2("GET", `/api/accounts/${id}`);
825
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
220
826
  }
221
827
  );
222
828
  server2.tool(
223
829
  "create_account",
224
- "Create a new account (brokerage, bank, retirement, etc.). Requires the tensor:portfolio:write scope.",
830
+ "Create an account owned by an entity.",
225
831
  {
226
- name: z.string().describe("Account name"),
227
- entityId: z.number().describe("Owner entity ID"),
228
- accountType: z.string().describe("Account type key (e.g. 'Brokerage', 'Bank', 'Retirement'). Must match an existing account-types row."),
229
- institution: z.string().optional().describe("Institution name as free-form text (e.g. 'Charles Schwab', 'Fidelity'). Not an ID."),
230
- currency: z.string().optional().describe("Currency code (e.g. USD, EUR). Default: USD"),
231
- notes: z.string().optional()
832
+ name: z2.string().describe("Account name"),
833
+ entityId: z2.number().describe("Owner entity ID"),
834
+ accountType: z2.string().describe("Account type key from list_account_types (Brokerage, Bank, Retirement)."),
835
+ institution: z2.string().optional().describe("Institution name as text (Charles Schwab), not an id."),
836
+ currency: z2.string().optional().describe("Currency code (e.g. USD, EUR). Default: USD"),
837
+ notes: z2.string().optional()
232
838
  },
233
839
  async (params) => {
234
- const data = await api("POST", "/api/accounts", params);
235
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
840
+ const data = await api2("POST", "/api/accounts", params);
841
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
236
842
  }
237
843
  );
238
844
  server2.tool(
239
845
  "update_account",
240
- "Update an existing account (partial update). Requires the tensor:portfolio:write scope.",
846
+ "Edit an account. Only the fields sent change.",
241
847
  {
242
- id: z.number().describe("Account ID to update"),
243
- name: z.string().optional(),
244
- entityId: z.number().optional(),
245
- accountType: z.string().optional().describe("Account type key"),
246
- institution: z.string().optional().describe("Institution name as free-form text"),
247
- currency: z.string().optional(),
248
- notes: z.string().optional()
848
+ id: z2.number().describe("Account ID to update"),
849
+ name: z2.string().optional(),
850
+ entityId: z2.number().optional(),
851
+ accountType: z2.string().optional().describe("Account type key"),
852
+ institution: z2.string().optional().describe("Institution name as free-form text"),
853
+ currency: z2.string().optional(),
854
+ notes: z2.string().optional()
249
855
  },
250
856
  async ({ id, ...body }) => {
251
- const data = await api("PATCH", `/api/accounts/${id}`, body);
252
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
857
+ const data = await api2("PATCH", `/api/accounts/${id}`, body);
858
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
253
859
  }
254
860
  );
255
861
  server2.tool(
256
862
  "delete_account",
257
- "Delete an account by ID. Requires the tensor:portfolio:write scope.",
258
- { id: z.number().describe("Account ID to delete") },
259
- async ({ id }) => {
260
- const data = await api("DELETE", `/api/accounts/${id}`);
261
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
262
- }
863
+ "Delete an account. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
864
+ { id: z2.number().describe("Account ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
865
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/accounts/${id}`, void 0, { confirmToken }))
263
866
  );
264
867
  server2.tool(
265
868
  "list_assets",
266
- "List assets (stocks, bonds, crypto, real estate, etc.). Filter server-side rather than pulling the whole catalog. Requires the tensor:portfolio:read scope.",
869
+ "List the asset catalog (stocks, bonds, crypto, real estate), filtered server-side.",
267
870
  {
268
- limit: z.number().optional(),
269
- offset: z.number().optional(),
270
- assetClass: z.string().optional().describe("Only assets in this asset class"),
271
- symbol: z.string().optional().describe("Exact display symbol match (case-insensitive)"),
272
- linked: z.boolean().optional().describe("true = only assets linked to a price provider; false = only unlinked ones"),
273
- q: z.string().optional().describe("Case-insensitive substring across name and symbol")
871
+ limit: LIMIT_INPUT,
872
+ offset: OFFSET_INPUT,
873
+ assetClass: z2.string().optional().describe("Only assets in this asset class"),
874
+ symbol: z2.string().optional().describe("Exact display symbol match (case-insensitive)"),
875
+ linked: z2.boolean().optional().describe("true = only assets linked to a price provider; false = only unlinked ones"),
876
+ q: z2.string().optional().describe("Case-insensitive substring across name and symbol")
274
877
  },
275
878
  async ({ limit, offset, assetClass, symbol, linked, q }) => {
276
879
  const params = new URLSearchParams();
277
- if (limit) params.set("limit", String(limit));
278
- if (offset) params.set("offset", String(offset));
279
880
  if (assetClass) params.set("assetClass", assetClass);
280
881
  if (symbol) params.set("symbol", symbol);
281
882
  if (linked !== void 0) params.set("linked", String(linked));
282
883
  if (q) params.set("q", q);
283
- const qs = params.toString();
284
- const data = await api("GET", `/api/assets${qs ? `?${qs}` : ""}`);
285
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
884
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/assets?${qs}`));
286
885
  }
287
886
  );
288
887
  server2.tool(
289
888
  "get_asset",
290
- "Get a single asset by ID. Requires the tensor:portfolio:read scope.",
291
- { id: z.number().describe("Asset ID") },
889
+ "One asset by id.",
890
+ { id: z2.number().describe("Asset ID") },
292
891
  async ({ id }) => {
293
- const data = await api("GET", `/api/assets/${id}`);
294
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
892
+ const data = await api2("GET", `/api/assets/${id}`);
893
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
295
894
  }
296
895
  );
297
896
  server2.tool(
298
897
  "create_asset",
299
- "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. Requires the tensor:portfolio:write scope.",
300
- {
301
- name: z.string().describe("Asset name"),
302
- assetClass: z.string().describe("Asset class key (e.g. 'Equity', 'Bond', 'Crypto', 'Real Estate'). Must match an existing asset-classes row."),
303
- symbol: z.string().optional().describe("Display ticker shown to humans (e.g. 'AAPL', 'BRK.B'). Cosmetic \u2014 this is NOT what prices the asset."),
304
- 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."),
305
- defaultCurrency: z.string().optional().describe("Default currency code. Default: USD"),
306
- currentPrice: z.number().optional().describe("Current price per unit as a number"),
307
- notes: z.string().optional(),
308
- 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."),
309
- syncPrice: z.boolean().optional().describe("Immediately pull the current quote after creating, so the asset arrives already priced. The outcome is returned under `priceSync`.")
898
+ "Create an asset. To make it price itself, set tickerSymbol from search_market_quotes and pass verifyQuote and syncPrice, so a bad symbol fails here instead of never pricing.",
899
+ {
900
+ name: z2.string().describe("Asset name"),
901
+ assetClass: z2.string().describe("Asset class key from list_asset_classes (Equity, Bond, Crypto, Real Estate)."),
902
+ symbol: z2.string().optional().describe("Display ticker for people (AAPL, BRK.B). Does NOT price the asset."),
903
+ tickerSymbol: z2.string().optional().describe("Price-provider symbol that prices the asset: a Yahoo ticker (AAPL, BRK-B, BTC-USD) or CG:<coingecko-id>. From search_market_quotes, never guessed. Also accepted and returned as fmpSymbol."),
904
+ defaultCurrency: z2.string().optional().describe("Default currency code. Default: USD"),
905
+ currentPrice: z2.number().optional().describe("Current price per unit as a number"),
906
+ notes: z2.string().optional(),
907
+ verifyQuote: z2.boolean().optional().describe("Refuse the create unless tickerSymbol resolves. Recommended with tickerSymbol."),
908
+ syncPrice: z2.boolean().optional().describe("Pull the quote right after creating; the outcome is in `priceSync`.")
310
909
  },
311
910
  async ({ verifyQuote, syncPrice, ...body }) => {
312
911
  const params = new URLSearchParams();
313
912
  if (verifyQuote) params.set("verifyQuote", "true");
314
913
  if (syncPrice) params.set("syncPrice", "true");
315
914
  const qs = params.toString();
316
- const data = await api("POST", `/api/assets${qs ? `?${qs}` : ""}`, body);
317
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
915
+ const data = await api2("POST", `/api/assets${qs ? `?${qs}` : ""}`, body);
916
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
318
917
  }
319
918
  );
320
919
  server2.tool(
321
920
  "update_asset",
322
- "Update an existing asset (partial update). Set tickerSymbol to link or relink the asset to a market quote. Requires the tensor:portfolio:write scope.",
323
- {
324
- id: z.number().describe("Asset ID to update"),
325
- name: z.string().optional(),
326
- assetClass: z.string().optional(),
327
- symbol: z.string().optional().describe("Display ticker. Cosmetic \u2014 use tickerSymbol to control pricing."),
328
- 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."),
329
- defaultCurrency: z.string().optional(),
330
- currentPrice: z.number().optional(),
331
- notes: z.string().optional(),
332
- verifyQuote: z.boolean().optional().describe("Resolve tickerSymbol with the provider before saving; rejects the update if it does not resolve."),
333
- syncPrice: z.boolean().optional().describe("Pull the current quote right after saving. Outcome returned under `priceSync`.")
921
+ "Edit an asset. Set tickerSymbol to link or relink it to a market quote.",
922
+ {
923
+ id: z2.number().describe("Asset ID to update"),
924
+ name: z2.string().optional(),
925
+ assetClass: z2.string().optional(),
926
+ symbol: z2.string().optional().describe("Display ticker. Does not price the asset."),
927
+ tickerSymbol: z2.string().optional().describe("Price-provider symbol (Yahoo ticker or CG:<coingecko-id>) from search_market_quotes. Omit to keep the current link. Alias: fmpSymbol."),
928
+ defaultCurrency: z2.string().optional(),
929
+ currentPrice: z2.number().optional(),
930
+ notes: z2.string().optional(),
931
+ verifyQuote: z2.boolean().optional().describe("Refuse the update unless tickerSymbol resolves."),
932
+ syncPrice: z2.boolean().optional().describe("Pull the quote right after saving; outcome in `priceSync`.")
334
933
  },
335
934
  async ({ id, verifyQuote, syncPrice, ...body }) => {
336
935
  const params = new URLSearchParams();
337
936
  if (verifyQuote) params.set("verifyQuote", "true");
338
937
  if (syncPrice) params.set("syncPrice", "true");
339
938
  const qs = params.toString();
340
- const data = await api("PATCH", `/api/assets/${id}${qs ? `?${qs}` : ""}`, body);
341
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
939
+ const data = await api2("PATCH", `/api/assets/${id}${qs ? `?${qs}` : ""}`, body);
940
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
342
941
  }
343
942
  );
344
943
  server2.tool(
345
944
  "delete_asset",
346
- "Delete an asset by ID. Requires the tensor:portfolio:write scope.",
347
- { id: z.number().describe("Asset ID to delete") },
348
- async ({ id }) => {
349
- const data = await api("DELETE", `/api/assets/${id}`);
350
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
351
- }
945
+ "Delete an asset. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
946
+ { id: z2.number().describe("Asset ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
947
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/assets/${id}`, void 0, { confirmToken }))
352
948
  );
353
949
  server2.tool(
354
950
  "list_asset_prices",
355
- "List historical prices for an asset. Requires the tensor:portfolio:read scope.",
951
+ "An asset's price history.",
356
952
  {
357
- id: z.number().describe("Asset ID"),
358
- limit: z.number().optional(),
359
- offset: z.number().optional()
953
+ id: z2.number().describe("Asset ID"),
954
+ limit: LIMIT_INPUT,
955
+ offset: OFFSET_INPUT
360
956
  },
361
957
  async ({ id, limit, offset }) => {
362
958
  const params = new URLSearchParams();
363
- if (limit) params.set("limit", String(limit));
364
- if (offset) params.set("offset", String(offset));
365
- const qs = params.toString();
366
- const data = await api("GET", `/api/assets/${id}/prices${qs ? `?${qs}` : ""}`);
367
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
959
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/assets/${id}/prices?${qs}`));
368
960
  }
369
961
  );
370
962
  server2.tool(
371
963
  "update_asset_price",
372
- "Record a new price for an asset. Requires the tensor:portfolio:write scope.",
964
+ "Record a manual price for an asset, repricing its positions.",
373
965
  {
374
- id: z.number().describe("Asset ID"),
375
- price: z.number().describe("New price value"),
376
- memo: z.string().optional().describe("Price update memo"),
377
- source: z.string().optional().describe("Price source (e.g. manual, bloomberg)"),
378
- confirm: z.boolean().optional().describe("true = value verified unchanged; writes 'confirm' valuation events instead of 'reprice' so routine check-ins don't flood history")
966
+ id: z2.number().describe("Asset ID"),
967
+ price: z2.number().describe("New price value"),
968
+ memo: z2.string().optional().describe("Price update memo"),
969
+ source: z2.string().optional().describe("Price source (e.g. manual, bloomberg)"),
970
+ confirm: z2.boolean().optional().describe("true = the value was checked and is unchanged: records a 'confirm' event, not a reprice.")
379
971
  },
380
972
  async ({ id, ...body }) => {
381
- const data = await api("POST", `/api/assets/${id}/prices`, body);
382
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
973
+ const data = await api2("POST", `/api/assets/${id}/prices`, body);
974
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
383
975
  }
384
976
  );
385
977
  server2.tool(
386
978
  "list_positions",
387
- "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. Requires the tensor:portfolio:read scope.",
388
- {
389
- limit: z.number().optional(),
390
- offset: z.number().optional(),
391
- entityId: z.number().optional().describe("Only positions held by this entity"),
392
- accountId: z.number().optional().describe("Only positions in this custody account"),
393
- assetId: z.number().optional().describe("Only positions in this asset"),
394
- assetClass: z.string().optional().describe("Only positions in this asset class"),
395
- status: z.string().optional().describe("'active' or 'closed'. Omit for both."),
396
- liability: z.boolean().optional().describe("true = only liabilities, false = only assets"),
397
- updatedSince: z.number().optional().describe("Only positions updated at/after this epoch-ms timestamp")
979
+ "List positions (holdings), filtered server-side. For totals use get_portfolio_summary, never a sum of these.",
980
+ {
981
+ limit: LIMIT_INPUT,
982
+ offset: OFFSET_INPUT,
983
+ entityId: z2.number().optional().describe("Only positions held by this entity"),
984
+ accountId: z2.number().optional().describe("Only positions in this custody account"),
985
+ assetId: z2.number().optional().describe("Only positions in this asset"),
986
+ assetClass: z2.string().optional().describe("Only positions in this asset class"),
987
+ status: z2.string().optional().describe("'active' or 'closed'. Omit for both."),
988
+ liability: z2.boolean().optional().describe("true = only liabilities, false = only assets"),
989
+ updatedSince: z2.number().optional().describe("Only positions updated at/after this epoch-ms timestamp")
398
990
  },
399
991
  async ({ limit, offset, entityId, accountId, assetId, assetClass, status, liability, updatedSince }) => {
400
992
  const params = new URLSearchParams();
401
- if (limit) params.set("limit", String(limit));
402
- if (offset) params.set("offset", String(offset));
403
993
  if (entityId) params.set("entityId", String(entityId));
404
994
  if (accountId) params.set("accountId", String(accountId));
405
995
  if (assetId) params.set("assetId", String(assetId));
@@ -407,182 +997,203 @@ function registerAllTools(server2, api) {
407
997
  if (status) params.set("status", status);
408
998
  if (liability !== void 0) params.set("liability", String(liability));
409
999
  if (updatedSince) params.set("updatedSince", String(updatedSince));
410
- const qs = params.toString();
411
- const data = await api("GET", `/api/positions${qs ? `?${qs}` : ""}`);
412
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1000
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/positions?${qs}`));
1001
+ }
1002
+ );
1003
+ server2.tool(
1004
+ "get_position",
1005
+ "One position by id.",
1006
+ { id: z2.number().describe("Position ID") },
1007
+ async ({ id }) => {
1008
+ const data = await api2("GET", `/api/positions/${id}`);
1009
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1010
+ }
1011
+ );
1012
+ server2.tool(
1013
+ "get_position_overview",
1014
+ "Everything about one position in one call: the position, its 20 newest transactions and 10 newest valuations, a loan's terms and a fund's terms and performance (null when it is not that kind).",
1015
+ { id: z2.number().describe("Position ID") },
1016
+ async ({ id }) => {
1017
+ const [position, recentTransactions, recentValuations, loanTerms, fund] = await Promise.all([
1018
+ api2("GET", `/api/positions/${id}`),
1019
+ api2("GET", `/api/transactions?positionId=${id}&limit=20`),
1020
+ api2("GET", `/api/positions/${id}/events?limit=10`),
1021
+ unlessMissing(api2("GET", `/api/loan-terms/${id}`)),
1022
+ unlessMissing(api2("GET", `/api/v1/portfolio/funds/${id}`))
1023
+ ]);
1024
+ return {
1025
+ content: [{
1026
+ type: "text",
1027
+ text: JSON.stringify({ position, recentTransactions, recentValuations, loanTerms, fund })
1028
+ }]
1029
+ };
413
1030
  }
414
1031
  );
415
1032
  server2.tool(
416
1033
  "create_position",
417
- "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. Requires the tensor:portfolio:write scope.",
418
- {
419
- entityId: z.number().describe("Owner entity ID"),
420
- label: z.string().describe("Display label for this position (e.g. 'AAPL @ Schwab', 'Brooklyn rental')"),
421
- assetClass: z.string().describe("Asset class key (e.g. 'Equity', 'Real Estate', 'Cash')"),
422
- 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."),
423
- accountId: z.number().optional().describe("Optional account ID this position lives in"),
424
- 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."),
425
- liability: z.boolean().optional().describe("True if this is a liability (mortgage, loan). Default: false"),
426
- 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."),
427
- currentPrice: z.number().optional().describe("Current price per unit. Same rule as quantity: omit it when costBasis is set."),
428
- 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."),
429
- costBasis: z.number().optional().describe(
430
- "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."
431
- ),
432
- realizedGain: z.number().optional().describe("Realized gain to date. Default: 0"),
433
- status: z.string().optional().describe("'active' or 'closed'. Default: 'active'"),
434
- currency: z.string().optional().describe("Currency code. Default: USD"),
435
- notes: z.string().optional()
1034
+ "Open a position: an entity's holding of an asset, optionally in an account. UNITIZED (shares, units, cash): send quantity and averageCost. Fund CAPITAL ACCOUNT (an LP interest; the GP reports a balance, no units): send costBasis, the only switch. The shape cannot be changed later; ask if unsure.",
1035
+ {
1036
+ entityId: z2.number().describe("Owner entity ID"),
1037
+ label: z2.string().describe("Display label (AAPL @ Schwab, Brooklyn rental)."),
1038
+ assetClass: z2.string().describe("Asset class key (e.g. 'Equity', 'Real Estate', 'Cash')"),
1039
+ currentValue: z2.number().describe("Value now in `currency`; negative for a liability. On a capital account, the GP's latest NAV."),
1040
+ accountId: z2.number().optional().describe("Optional account ID this position lives in"),
1041
+ assetId: z2.number().optional().describe("The asset held. Not on a capital account."),
1042
+ liability: z2.boolean().optional().describe("True if this is a liability (mortgage, loan). Default: false"),
1043
+ quantity: z2.number().optional().describe("Units held. Not with costBasis."),
1044
+ currentPrice: z2.number().optional().describe("Price per unit. Not with costBasis."),
1045
+ averageCost: z2.number().optional().describe("Cost per unit. Not with costBasis."),
1046
+ costBasis: z2.number().optional().describe("Capital-account cost basis: paid-in capital less capital returned (0 for a commitment not yet drawn). Setting it makes a fund LP interest: leave quantity, prices and assetId unset. Afterwards the ledger moves it. Omit for a unitized holding."),
1047
+ realizedGain: z2.number().optional().describe("Realized gain to date. Default: 0"),
1048
+ status: z2.string().optional().describe("'active' or 'closed'. Default: 'active'"),
1049
+ currency: z2.string().optional().describe("Currency code. Default: USD"),
1050
+ notes: z2.string().optional()
436
1051
  },
437
1052
  async (params) => {
438
- const data = await api("POST", "/api/positions", params);
439
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1053
+ const data = await api2("POST", "/api/positions", params);
1054
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
440
1055
  }
441
1056
  );
442
1057
  server2.tool(
443
1058
  "update_position",
444
- "Update an existing position (partial update). Changing what the ledger measures \u2014 quantity, averageCost, a cash balance via currentValue, a capital account's costBasis \u2014 also appends one ledger row recording the difference, an `adjustment` with signed quantity and amount, so the transaction history still explains the position. Prefer create_transaction when you know the trade itself; use this to restate totals. Requires the tensor:portfolio:write scope.",
445
- {
446
- id: z.number().describe("Position ID to update"),
447
- entityId: z.number().optional(),
448
- accountId: z.number().optional(),
449
- assetId: z.number().optional(),
450
- label: z.string().optional(),
451
- assetClass: z.string().optional(),
452
- liability: z.boolean().optional(),
453
- quantity: z.number().optional(),
454
- currentPrice: z.number().optional(),
455
- currentValue: z.number().optional(),
456
- averageCost: z.number().optional(),
457
- realizedGain: z.number().optional(),
458
- status: z.string().optional(),
459
- currency: z.string().optional(),
460
- notes: z.string().optional()
1059
+ "Edit a position. Changing quantity, averageCost, a cash balance (currentValue) or a capital account's costBasis also appends one `adjustment` ledger row recording the difference. Use it to restate totals; record a known trade with create_transaction.",
1060
+ {
1061
+ id: z2.number().describe("Position ID to update"),
1062
+ entityId: z2.number().optional(),
1063
+ accountId: z2.number().optional(),
1064
+ assetId: z2.number().optional(),
1065
+ label: z2.string().optional(),
1066
+ assetClass: z2.string().optional(),
1067
+ liability: z2.boolean().optional(),
1068
+ quantity: z2.number().optional(),
1069
+ currentPrice: z2.number().optional(),
1070
+ currentValue: z2.number().optional(),
1071
+ averageCost: z2.number().optional(),
1072
+ realizedGain: z2.number().optional(),
1073
+ status: z2.string().optional(),
1074
+ currency: z2.string().optional(),
1075
+ notes: z2.string().optional()
461
1076
  },
462
1077
  async ({ id, ...body }) => {
463
- const data = await api("PATCH", `/api/positions/${id}`, body);
464
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1078
+ const data = await api2("PATCH", `/api/positions/${id}`, body);
1079
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
465
1080
  }
466
1081
  );
467
1082
  server2.tool(
468
1083
  "delete_position",
469
- "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. Requires the tensor:portfolio:write scope.",
470
- { id: z.number().describe("Position ID to delete") },
471
- async ({ id }) => {
472
- const data = await api("DELETE", `/api/positions/${id}`);
473
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
474
- }
1084
+ "Destroy a position with its whole ledger, valuations, terms, relations and attachments. Not how to record an exit (that is sell_all_position); only for a position that should never have existed. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
1085
+ { id: z2.number().describe("Position ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
1086
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/positions/${id}`, void 0, { confirmToken }))
475
1087
  );
476
1088
  server2.tool(
477
1089
  "sell_all_position",
478
- "Close/sell all of a position (creates a sell transaction). Requires the tensor:portfolio:write scope.",
1090
+ "Close a position by selling all of it: a sell transaction that keeps the history and books the realized gain.",
479
1091
  {
480
- id: z.number().describe("Position ID to sell"),
481
- price: z.number().optional().describe("Sale price per unit"),
482
- amount: z.number().optional().describe("Total sale amount"),
483
- fees: z.number().optional().describe("Transaction fees"),
484
- memo: z.string().optional().describe("Sale memo"),
485
- quantity: z.number().optional().describe("Quantity to sell (defaults to all)"),
486
- timestamp: z.number().optional().describe("Epoch ms backdate for the close; defaults to now")
1092
+ id: z2.number().describe("Position ID to sell"),
1093
+ price: z2.number().optional().describe("Sale price per unit"),
1094
+ amount: z2.number().optional().describe("Total sale amount"),
1095
+ fees: z2.number().optional().describe("Transaction fees"),
1096
+ memo: z2.string().optional().describe("Sale memo"),
1097
+ quantity: z2.number().optional().describe("Quantity to sell (defaults to all)"),
1098
+ timestamp: z2.number().optional().describe("Epoch ms backdate for the close; defaults to now")
487
1099
  },
488
1100
  async ({ id, ...body }) => {
489
- const data = await api("POST", `/api/positions/${id}/sell-all`, body);
490
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1101
+ const data = await api2("POST", `/api/positions/${id}/sell-all`, body);
1102
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
491
1103
  }
492
1104
  );
493
1105
  server2.tool(
494
1106
  "list_position_events",
495
- "List valuation events for a specific position (append-only history). Requires the tensor:portfolio:read scope.",
1107
+ "One position's valuation history.",
496
1108
  {
497
- id: z.number().describe("Position ID"),
498
- limit: z.number().optional(),
499
- offset: z.number().optional()
1109
+ id: z2.number().describe("Position ID"),
1110
+ limit: LIMIT_INPUT,
1111
+ offset: OFFSET_INPUT
500
1112
  },
501
1113
  async ({ id, limit, offset }) => {
502
1114
  const params = new URLSearchParams();
503
- if (limit) params.set("limit", String(limit));
504
- if (offset) params.set("offset", String(offset));
505
- const qs = params.toString();
506
- const data = await api("GET", `/api/positions/${id}/events${qs ? `?${qs}` : ""}`);
507
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1115
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/positions/${id}/events?${qs}`));
508
1116
  }
509
1117
  );
510
1118
  server2.tool(
511
1119
  "list_events",
512
- "List valuation events across all positions in the organization. Requires the tensor:portfolio:read scope.",
513
- { limit: z.number().optional(), offset: z.number().optional() },
1120
+ "Valuation events across every position.",
1121
+ { limit: LIMIT_INPUT, offset: OFFSET_INPUT },
514
1122
  async ({ limit, offset }) => {
515
1123
  const params = new URLSearchParams();
516
- if (limit) params.set("limit", String(limit));
517
- if (offset) params.set("offset", String(offset));
518
- const qs = params.toString();
519
- const data = await api("GET", `/api/events${qs ? `?${qs}` : ""}`);
520
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1124
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/events?${qs}`));
521
1125
  }
522
1126
  );
523
1127
  server2.tool(
524
1128
  "list_position_relations",
525
- "List all position relations (linked/related positions). Requires the tensor:portfolio:read scope.",
526
- { limit: z.number().optional(), offset: z.number().optional() },
1129
+ "List links between positions.",
1130
+ { limit: LIMIT_INPUT, offset: OFFSET_INPUT },
527
1131
  async ({ limit, offset }) => {
528
1132
  const params = new URLSearchParams();
529
- if (limit) params.set("limit", String(limit));
530
- if (offset) params.set("offset", String(offset));
531
- const qs = params.toString();
532
- const data = await api("GET", `/api/position-relations${qs ? `?${qs}` : ""}`);
533
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1133
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/position-relations?${qs}`));
534
1134
  }
535
1135
  );
536
1136
  server2.tool(
537
1137
  "create_position_relation",
538
- "Link two positions together. Requires the tensor:portfolio:write scope.",
1138
+ "Link two positions.",
539
1139
  {
540
- positionId: z.number().describe("First position ID"),
541
- relatedPositionId: z.number().describe("Related position ID")
1140
+ positionId: z2.number().describe("First position ID"),
1141
+ relatedPositionId: z2.number().describe("Related position ID")
542
1142
  },
543
1143
  async (params) => {
544
- const data = await api("POST", "/api/position-relations", params);
545
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1144
+ const data = await api2("POST", "/api/position-relations", params);
1145
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
546
1146
  }
547
1147
  );
548
1148
  server2.tool(
549
1149
  "delete_position_relation",
550
- "Remove a position relation. Requires the tensor:portfolio:write scope.",
551
- { id: z.number().describe("Position relation ID to delete") },
1150
+ "Remove a link between positions.",
1151
+ { id: z2.number().describe("Position relation ID to delete") },
552
1152
  async ({ id }) => {
553
- const data = await api("DELETE", `/api/position-relations/${id}`);
554
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1153
+ const data = await api2("DELETE", `/api/position-relations/${id}`);
1154
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
555
1155
  }
556
1156
  );
557
1157
  server2.tool(
558
1158
  "list_transactions",
559
- "List transactions (buys, sells, dividends, fees, etc.). Filter by position or date range server-side. Requires the tensor:portfolio:read scope.",
1159
+ "List ledger transactions, filtered by position or date range.",
560
1160
  {
561
- limit: z.number().optional(),
562
- offset: z.number().optional(),
563
- positionId: z.number().optional().describe("Only transactions against this position"),
564
- transactionType: z.string().optional().describe("Only this transaction type (buy, sell, dividend, ...)"),
565
- since: z.number().optional().describe("Only transactions at/after this epoch-ms timestamp"),
566
- until: z.number().optional().describe("Only transactions at/before this epoch-ms timestamp")
1161
+ limit: LIMIT_INPUT,
1162
+ offset: OFFSET_INPUT,
1163
+ positionId: z2.number().optional().describe("Only transactions against this position"),
1164
+ transactionType: z2.string().optional().describe("Only this transaction type (buy, sell, dividend, ...)"),
1165
+ since: z2.number().optional().describe("Only transactions at/after this epoch-ms timestamp"),
1166
+ until: z2.number().optional().describe("Only transactions at/before this epoch-ms timestamp")
567
1167
  },
568
1168
  async ({ limit, offset, positionId, transactionType, since, until }) => {
569
1169
  const params = new URLSearchParams();
570
- if (limit) params.set("limit", String(limit));
571
- if (offset) params.set("offset", String(offset));
572
1170
  if (positionId) params.set("positionId", String(positionId));
573
1171
  if (transactionType) params.set("transactionType", transactionType);
574
1172
  if (since) params.set("since", String(since));
575
1173
  if (until) params.set("until", String(until));
576
- const qs = params.toString();
577
- const data = await api("GET", `/api/transactions${qs ? `?${qs}` : ""}`);
578
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1174
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/transactions?${qs}`));
1175
+ }
1176
+ );
1177
+ server2.tool(
1178
+ "get_transaction",
1179
+ "One ledger transaction by id.",
1180
+ { id: z2.number().describe("Ledger transaction ID") },
1181
+ async ({ id }) => {
1182
+ const data = await api2("GET", `/api/transactions/${id}`);
1183
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
579
1184
  }
580
1185
  );
581
1186
  server2.tool(
582
1187
  "create_transaction",
583
- "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. Requires the tensor:portfolio:write scope.",
584
- {
585
- positionId: z.number().describe("Position ID this transaction belongs to"),
1188
+ // The single most consequential thing an agent can get wrong here. There
1189
+ // is no update_transaction and no delete_transaction anywhere in this
1190
+ // API, by design: position state (quantity, average cost, cost basis,
1191
+ // realized gain) is a non-invertible fold over the ledger in insert
1192
+ // order, so there is no stored prior state to roll back to. An agent that
1193
+ // assumes it can "fix it later" writes a wrong entry it cannot take back.
1194
+ "Append a transaction to a position's ledger. PERMANENT: there is no edit or delete. A mistake is fixed with a compensating entry of the opposite type (a wrong buy by a sell), and both rows stay. Confirm anything uncertain with the user first, post oldest first, and pass an idempotencyKey.",
1195
+ {
1196
+ positionId: z2.number().describe("Position ID this transaction belongs to"),
586
1197
  // This string is what an LLM reads to pick a type. When the loan types
587
1198
  // were missing from it, agents reached for `sell` to record a repayment
588
1199
  // and booked a phantom gain. mcp-server is a standalone npm package and
@@ -592,253 +1203,238 @@ function registerAllTools(server2, api) {
592
1203
  // script/smoke-clerk-api-keys.ts so it can never silently drift again.
593
1204
  // Recordable, not every key: `adjustment` is written by Tensor when a
594
1205
  // position is edited, and the server refuses it from any caller.
595
- transactionType: z.string().describe("Ledger type. One of: buy, sell, deposit, withdrawal, interest, dividend, coupon, 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; fee is logged with no P/L impact. INCOME \u2014 dividend, interest and coupon are one rule under three names: post them with `settlement` (see that field) and on the position that PAID the income. For loans YOU made: loan_accrual adds PIK interest to the balance (post amount 0), repayment_received records the borrower paying you back, interest first: the part that pays off accrued interest is booked as realized income and the rest is a return of capital with 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."),
596
- 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: income with settlement "cash", fees, and every capital-account entry. Income with settlement "in_kind" posts the units received.'),
1206
+ transactionType: z2.string().describe("Ledger type. One of: buy, sell, deposit, withdrawal, interest, dividend, coupon, transfer_in, transfer_out, contribution, capital_call, distribution, return_of_capital, recallable_distribution, management_fee, write_off, borrow, repay, fee, loan_accrual, repayment_received. The type, never a sign, sets direction. buy/contribution/capital_call add cost basis; sell/distribution realize gain; fee has no P/L. Income (dividend, interest, coupon) needs `settlement` and goes on the position that paid it. A loan you made: loan_accrual adds PIK interest (amount 0); repayment_received pays accrued interest first (booked as income), the rest returns capital; never sell or withdrawal. A capital account takes ONLY the fund types, quantity 0 and the money in amount: capital_call/contribution add paid-in; return_of_capital lowers cost basis with no gain (a GP returning capital is this, not distribution, which books profit); recallable_distribution also restores unfunded; management_fee only for fees billed outside the NAV; write_off (amount 0, derived) closes a finished, under-water fund after its last return_of_capital, booking the unreturned basis as a loss and zeroing the NAV."),
1207
+ quantity: z2.number().describe("Units moved, POSITIVE. 0 for cash income, fees and every capital-account entry; in_kind income posts the units received."),
597
1208
  // Was documented as "positive for inflows, negative for outflows", which
598
1209
  // is not what the server does with it: both the unitized and the
599
1210
  // capital-account folds take Math.abs(amount). A negative amount was
600
1211
  // silently absorbed, so an agent following that instruction believed it
601
1212
  // had recorded an outflow and had in fact recorded an inflow.
602
- 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). On income with settlement "in_kind" it is stored as sent and never read: the cost comes from price alone.'),
603
- price: z.number().optional().describe("Price per unit (for buys/sells). On in-kind income it is the COST per unit received (0 when omitted), never the market price \u2014 the position keeps its existing mark. Omit on a capital account, which has no unit price."),
604
- 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."),
605
- 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."),
1213
+ amount: z2.number().describe("Cash that changed hands, POSITIVE: a negative is read as positive, never as an outflow. 0 for loan_accrual. Not read on in_kind income."),
1214
+ price: z2.number().optional().describe("Price per unit. On in_kind income, the COST per unit (default 0), never the market price. Omit on a capital account."),
1215
+ fees: z2.number().optional().describe("Positive. On capital_call/contribution it is added to cost basis; on sell, distribution, return_of_capital or management_fee it reduces realized gain."),
1216
+ timestamp: z2.number().optional().describe("Epoch ms, default now. Never earlier than the position's latest activity (a capital account's NAV marks included), or 400: backfill oldest first."),
606
1217
  // Optional so every pre-5.2 call keeps its meaning. Without it a
607
1218
  // dividend still books income and moves nothing and an interest row
608
1219
  // still adds units and books nothing (the legacy rules), which is why the
609
1220
  // description asks for it explicitly rather than defaulting it here.
610
- settlement: z.enum(["cash", "in_kind"]).optional().describe(`INCOME ONLY (dividend, interest, coupon); rejected with a 400 on any other type. "cash": the income was paid as money \u2014 it is booked to realized gain (amount \u2212 fees) on this position and no units move; post quantity 0. Where the money landed is NOT recorded by this row: if you track that cash balance, post a separate deposit on the cash position. "in_kind": the income was paid in units of THIS instrument (a USDC coupon into a USDC note, staking rewards, a scrip dividend): quantity is the units received and price is the COST PER UNIT, 0 when omitted (never derived from amount, which is stored as sent and not read) \u2014 free units leave total cost unchanged, lower the average cost, and show as unrealized gain until sold. A non-zero price books quantity \xD7 price as realized income now and carries it as the units' cost. Omit only to reproduce the pre-5.2 behaviour \u2014 on a loan that capitalises the interest at a cost, so it is never booked as income; record loan interest as loan_accrual instead.`),
611
- memo: z.string().optional()
1221
+ settlement: z2.enum(["cash", "in_kind"]).optional().describe('Income only. "cash": paid as money; books amount minus fees as realized gain, quantity 0 (where the cash landed is a separate deposit). "in_kind": paid in units of this instrument; quantity = units, price = cost per unit (0 = free units at a lower average cost; non-zero books quantity x price as income now). Omitted keeps the pre-5.2 rule; for loan interest use loan_accrual.'),
1222
+ memo: z2.string().optional()
612
1223
  },
613
1224
  async (params) => {
614
- const data = await api("POST", "/api/transactions", params);
615
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1225
+ const data = await api2("POST", "/api/transactions", params);
1226
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
616
1227
  }
617
1228
  );
618
1229
  server2.tool(
619
1230
  "list_institutions",
620
- "List all institutions (banks, brokers, custodians). Requires the tensor:reference:read scope.",
1231
+ "List institutions (banks, brokers, custodians).",
621
1232
  {},
622
1233
  async () => {
623
- const data = await api("GET", "/api/institutions");
624
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1234
+ const data = await api2("GET", "/api/institutions");
1235
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
625
1236
  }
626
1237
  );
627
1238
  server2.tool(
628
1239
  "create_institution",
629
- "Create a new institution. Requires the tensor:reference:write scope.",
1240
+ "Create an institution.",
630
1241
  {
631
- name: z.string().describe("Institution name"),
632
- notes: z.string().optional()
1242
+ name: z2.string().describe("Institution name"),
1243
+ notes: z2.string().optional()
633
1244
  },
634
1245
  async (params) => {
635
- const data = await api("POST", "/api/institutions", params);
636
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1246
+ const data = await api2("POST", "/api/institutions", params);
1247
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
637
1248
  }
638
1249
  );
639
1250
  server2.tool(
640
1251
  "update_institution",
641
- "Update an institution. Requires the tensor:reference:write scope.",
1252
+ "Edit an institution.",
642
1253
  {
643
- id: z.number().describe("Institution ID"),
644
- name: z.string().optional(),
645
- notes: z.string().optional()
1254
+ id: z2.number().describe("Institution ID"),
1255
+ name: z2.string().optional(),
1256
+ notes: z2.string().optional()
646
1257
  },
647
1258
  async ({ id, ...body }) => {
648
- const data = await api("PATCH", `/api/institutions/${id}`, body);
649
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1259
+ const data = await api2("PATCH", `/api/institutions/${id}`, body);
1260
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
650
1261
  }
651
1262
  );
652
1263
  server2.tool(
653
1264
  "delete_institution",
654
- "Delete an institution. Requires the tensor:reference:write scope.",
655
- { id: z.number().describe("Institution ID to delete") },
656
- async ({ id }) => {
657
- const data = await api("DELETE", `/api/institutions/${id}`);
658
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
659
- }
1265
+ "Delete an institution. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
1266
+ { id: z2.number().describe("Institution ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
1267
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/institutions/${id}`, void 0, { confirmToken }))
660
1268
  );
661
1269
  server2.tool(
662
1270
  "list_entity_types",
663
- "List all entity types (Individual, Trust, Corporation, etc.). Requires the tensor:reference:read scope.",
1271
+ "List entity types (Individual, Trust, LLC).",
664
1272
  {},
665
1273
  async () => {
666
- const data = await api("GET", "/api/entity-types");
667
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1274
+ const data = await api2("GET", "/api/entity-types");
1275
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
668
1276
  }
669
1277
  );
670
1278
  server2.tool(
671
1279
  "create_entity_type",
672
- "Create a new entity type catalog entry. Requires the tensor:reference:write scope.",
1280
+ "Add an entity type.",
673
1281
  {
674
- key: z.string().describe("Stable key referenced by entities.type (e.g. 'Individual', 'Trust')"),
675
- label: z.string().describe("Human-readable display label"),
676
- notes: z.string().optional()
1282
+ key: z2.string().describe("Stable key referenced by entities.type (e.g. 'Individual', 'Trust')"),
1283
+ label: z2.string().describe("Human-readable display label"),
1284
+ notes: z2.string().optional()
677
1285
  },
678
1286
  async (params) => {
679
- const data = await api("POST", "/api/entity-types", params);
680
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1287
+ const data = await api2("POST", "/api/entity-types", params);
1288
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
681
1289
  }
682
1290
  );
683
1291
  server2.tool(
684
1292
  "update_entity_type",
685
- "Update an entity type catalog entry (partial update). Requires the tensor:reference:write scope.",
1293
+ "Edit an entity type.",
686
1294
  {
687
- id: z.number().describe("Entity type ID"),
688
- key: z.string().optional(),
689
- label: z.string().optional(),
690
- notes: z.string().optional()
1295
+ id: z2.number().describe("Entity type ID"),
1296
+ key: z2.string().optional(),
1297
+ label: z2.string().optional(),
1298
+ notes: z2.string().optional()
691
1299
  },
692
1300
  async ({ id, ...body }) => {
693
- const data = await api("PATCH", `/api/entity-types/${id}`, body);
694
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1301
+ const data = await api2("PATCH", `/api/entity-types/${id}`, body);
1302
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
695
1303
  }
696
1304
  );
697
1305
  server2.tool(
698
1306
  "delete_entity_type",
699
- "Delete an entity type. Requires the tensor:reference:write scope.",
700
- { id: z.number().describe("Entity type ID to delete") },
701
- async ({ id }) => {
702
- const data = await api("DELETE", `/api/entity-types/${id}`);
703
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
704
- }
1307
+ "Delete an entity type. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
1308
+ { id: z2.number().describe("Entity type ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
1309
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/entity-types/${id}`, void 0, { confirmToken }))
705
1310
  );
706
1311
  server2.tool(
707
1312
  "list_role_types",
708
- "List all role types (Owner, Beneficiary, Trustee, etc.). Requires the tensor:reference:read scope.",
1313
+ "List role types (Owner, Beneficiary, Trustee).",
709
1314
  {},
710
1315
  async () => {
711
- const data = await api("GET", "/api/role-types");
712
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1316
+ const data = await api2("GET", "/api/role-types");
1317
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
713
1318
  }
714
1319
  );
715
1320
  server2.tool(
716
1321
  "create_role_type",
717
- "Create a new role type catalog entry. Requires the tensor:reference:write scope.",
1322
+ "Add a role type.",
718
1323
  {
719
- key: z.string().describe("Stable key (e.g. 'Owner', 'Trustee', 'Beneficiary')"),
720
- label: z.string().describe("Human-readable display label"),
721
- notes: z.string().optional()
1324
+ key: z2.string().describe("Stable key (e.g. 'Owner', 'Trustee', 'Beneficiary')"),
1325
+ label: z2.string().describe("Human-readable display label"),
1326
+ notes: z2.string().optional()
722
1327
  },
723
1328
  async (params) => {
724
- const data = await api("POST", "/api/role-types", params);
725
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1329
+ const data = await api2("POST", "/api/role-types", params);
1330
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
726
1331
  }
727
1332
  );
728
1333
  server2.tool(
729
1334
  "update_role_type",
730
- "Update a role type catalog entry (partial update). Requires the tensor:reference:write scope.",
1335
+ "Edit a role type.",
731
1336
  {
732
- id: z.number().describe("Role type ID"),
733
- key: z.string().optional(),
734
- label: z.string().optional(),
735
- notes: z.string().optional()
1337
+ id: z2.number().describe("Role type ID"),
1338
+ key: z2.string().optional(),
1339
+ label: z2.string().optional(),
1340
+ notes: z2.string().optional()
736
1341
  },
737
1342
  async ({ id, ...body }) => {
738
- const data = await api("PATCH", `/api/role-types/${id}`, body);
739
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1343
+ const data = await api2("PATCH", `/api/role-types/${id}`, body);
1344
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
740
1345
  }
741
1346
  );
742
1347
  server2.tool(
743
1348
  "delete_role_type",
744
- "Delete a role type. Requires the tensor:reference:write scope.",
745
- { id: z.number().describe("Role type ID to delete") },
746
- async ({ id }) => {
747
- const data = await api("DELETE", `/api/role-types/${id}`);
748
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
749
- }
1349
+ "Delete a role type. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
1350
+ { id: z2.number().describe("Role type ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
1351
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/role-types/${id}`, void 0, { confirmToken }))
750
1352
  );
751
1353
  server2.tool(
752
1354
  "list_account_types",
753
- "List all account types (Brokerage, Checking, IRA, 401k, etc.). Requires the tensor:reference:read scope.",
1355
+ "List account types (Brokerage, Checking, IRA).",
754
1356
  {},
755
1357
  async () => {
756
- const data = await api("GET", "/api/account-types");
757
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1358
+ const data = await api2("GET", "/api/account-types");
1359
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
758
1360
  }
759
1361
  );
760
1362
  server2.tool(
761
1363
  "create_account_type",
762
- "Create a new account type catalog entry. Requires the tensor:reference:write scope.",
1364
+ "Add an account type.",
763
1365
  {
764
- key: z.string().describe("Stable key referenced by accounts.accountType (e.g. 'Brokerage', 'Bank')"),
765
- label: z.string().describe("Human-readable display label"),
766
- notes: z.string().optional()
1366
+ key: z2.string().describe("Stable key referenced by accounts.accountType (e.g. 'Brokerage', 'Bank')"),
1367
+ label: z2.string().describe("Human-readable display label"),
1368
+ notes: z2.string().optional()
767
1369
  },
768
1370
  async (params) => {
769
- const data = await api("POST", "/api/account-types", params);
770
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1371
+ const data = await api2("POST", "/api/account-types", params);
1372
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
771
1373
  }
772
1374
  );
773
1375
  server2.tool(
774
1376
  "update_account_type",
775
- "Update an account type catalog entry (partial update). Requires the tensor:reference:write scope.",
1377
+ "Edit an account type.",
776
1378
  {
777
- id: z.number().describe("Account type ID"),
778
- key: z.string().optional(),
779
- label: z.string().optional(),
780
- notes: z.string().optional()
1379
+ id: z2.number().describe("Account type ID"),
1380
+ key: z2.string().optional(),
1381
+ label: z2.string().optional(),
1382
+ notes: z2.string().optional()
781
1383
  },
782
1384
  async ({ id, ...body }) => {
783
- const data = await api("PATCH", `/api/account-types/${id}`, body);
784
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1385
+ const data = await api2("PATCH", `/api/account-types/${id}`, body);
1386
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
785
1387
  }
786
1388
  );
787
1389
  server2.tool(
788
1390
  "delete_account_type",
789
- "Delete an account type. Requires the tensor:reference:write scope.",
790
- { id: z.number().describe("Account type ID to delete") },
791
- async ({ id }) => {
792
- const data = await api("DELETE", `/api/account-types/${id}`);
793
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
794
- }
1391
+ "Delete an account type. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
1392
+ { id: z2.number().describe("Account type ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
1393
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/account-types/${id}`, void 0, { confirmToken }))
795
1394
  );
796
1395
  server2.tool(
797
1396
  "list_asset_classes",
798
- "List all asset classes (Equities, Fixed Income, Real Estate, etc.). Requires the tensor:reference:read scope.",
1397
+ "List asset classes (Equities, Fixed Income, Real Estate).",
799
1398
  {},
800
1399
  async () => {
801
- const data = await api("GET", "/api/asset-classes");
802
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1400
+ const data = await api2("GET", "/api/asset-classes");
1401
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
803
1402
  }
804
1403
  );
805
1404
  server2.tool(
806
1405
  "create_asset_class",
807
- "Create a new asset class catalog entry. Requires the tensor:reference:write scope.",
1406
+ "Add an asset class.",
808
1407
  {
809
- key: z.string().describe("Stable key referenced by assets.assetClass (e.g. 'Equity', 'Real Estate')"),
810
- label: z.string().describe("Human-readable display label"),
811
- treatment: z.string().optional().describe("Accounting treatment. Default: 'asset'. Use 'liability' for debt classes."),
812
- notes: z.string().optional()
1408
+ key: z2.string().describe("Stable key referenced by assets.assetClass (e.g. 'Equity', 'Real Estate')"),
1409
+ label: z2.string().describe("Human-readable display label"),
1410
+ treatment: z2.string().optional().describe("Accounting treatment. Default: 'asset'. Use 'liability' for debt classes."),
1411
+ notes: z2.string().optional()
813
1412
  },
814
1413
  async (params) => {
815
- const data = await api("POST", "/api/asset-classes", params);
816
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1414
+ const data = await api2("POST", "/api/asset-classes", params);
1415
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
817
1416
  }
818
1417
  );
819
1418
  server2.tool(
820
1419
  "update_asset_class",
821
- "Update an asset class catalog entry (partial update). Requires the tensor:reference:write scope.",
1420
+ "Edit an asset class.",
822
1421
  {
823
- id: z.number().describe("Asset class ID"),
824
- key: z.string().optional(),
825
- label: z.string().optional(),
826
- treatment: z.string().optional(),
827
- notes: z.string().optional()
1422
+ id: z2.number().describe("Asset class ID"),
1423
+ key: z2.string().optional(),
1424
+ label: z2.string().optional(),
1425
+ treatment: z2.string().optional(),
1426
+ notes: z2.string().optional()
828
1427
  },
829
1428
  async ({ id, ...body }) => {
830
- const data = await api("PATCH", `/api/asset-classes/${id}`, body);
831
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1429
+ const data = await api2("PATCH", `/api/asset-classes/${id}`, body);
1430
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
832
1431
  }
833
1432
  );
834
1433
  server2.tool(
835
1434
  "delete_asset_class",
836
- "Delete an asset class. Requires the tensor:reference:write scope.",
837
- { id: z.number().describe("Asset class ID to delete") },
838
- async ({ id }) => {
839
- const data = await api("DELETE", `/api/asset-classes/${id}`);
840
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
841
- }
1435
+ "Delete an asset class. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
1436
+ { id: z2.number().describe("Asset class ID to delete"), confirmToken: CONFIRM_TOKEN_INPUT },
1437
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/asset-classes/${id}`, void 0, { confirmToken }))
842
1438
  );
843
1439
  const DATA_UPDATER_OP_TYPES = [
844
1440
  "asset.upsert",
@@ -851,56 +1447,61 @@ function registerAllTools(server2, api) {
851
1447
  const DATA_APPLY_CONFIRMATION = "APPLY-DATA-UPDATER";
852
1448
  server2.tool(
853
1449
  "data_dry_run",
854
- "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.",
855
- {
856
- batchId: z.string().describe(
857
- "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."
858
- ),
859
- source: z.string().optional().describe(
860
- "Optional provenance tag stored in the audit log (e.g. 'mcp', 'csv-import'). Max 64 chars."
861
- ),
862
- operations: z.array(z.object({
863
- op: z.enum(DATA_UPDATER_OP_TYPES).describe(
864
- "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?}"
865
- ),
866
- 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."),
867
- clientRef: z.string().optional().describe("Optional caller correlation ID echoed back per-operation in the preview. Max 128 chars.")
1450
+ "Batch import, step 1: validate up to 500 operations and preview the change WITHOUT writing. Returns a requestHash for data_apply. The same batchId with the same payload returns the stored preview; with a different payload, 409 (use a new batchId).",
1451
+ {
1452
+ batchId: z2.string().describe("Your batch id, e.g. 'stmt-2026-10-schwab-a' ([a-zA-Z0-9_-:.], max 128). data_apply takes the same one."),
1453
+ source: z2.string().optional().describe("Provenance tag for the audit log, e.g. 'mcp'. Max 64."),
1454
+ operations: z2.array(z2.object({
1455
+ op: z2.enum(DATA_UPDATER_OP_TYPES).describe("Operation type. `data` fields per op: asset.upsert: {name, assetClass, symbol?, fmpSymbol?, defaultCurrency?, currentPrice?, notes?} (fmpSymbol is the price symbol, a Yahoo ticker or CG:<coingecko-id>; omit on an update to keep the link, 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 (create_transaction's types), 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?}"),
1456
+ data: z2.record(z2.string(), z2.unknown()).describe("The op's fields (see op)."),
1457
+ clientRef: z2.string().optional().describe("Your id for this op, echoed in the preview. Max 128.")
868
1458
  })).min(1).max(500).describe("1-500 typed operations to preview.")
869
1459
  },
870
1460
  async ({ batchId, source, operations }) => {
871
- const data = await api("POST", "/api/v1/data/dry-run", {
1461
+ const data = await api2("POST", "/api/v1/data/dry-run", {
872
1462
  batchId,
873
1463
  ...source !== void 0 ? { source } : {},
874
1464
  operations
875
1465
  });
876
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1466
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
877
1467
  }
878
1468
  );
879
1469
  server2.tool(
880
1470
  "data_apply",
881
- "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.",
1471
+ "Batch import, step 2, after the user approved the preview: replays the stored dry run named by batchId and requestHash, nothing else. A repeat returns the stored result.",
882
1472
  {
883
- batchId: z.string().describe("The batchId of a previously persisted data_dry_run batch."),
884
- 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."),
885
- confirm: z.literal(DATA_APPLY_CONFIRMATION).describe(
1473
+ batchId: z2.string().describe("The batchId of a previously persisted data_dry_run batch."),
1474
+ requestHash: z2.string().describe("The requestHash data_dry_run returned for this batch."),
1475
+ confirm: z2.literal(DATA_APPLY_CONFIRMATION).describe(
886
1476
  `Deliberate-intent sentinel. Must be exactly "${DATA_APPLY_CONFIRMATION}".`
887
1477
  )
888
1478
  },
889
1479
  async ({ batchId, requestHash, confirm }) => {
890
- const data = await api("POST", "/api/v1/data/apply", { batchId, requestHash, confirm });
891
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1480
+ const data = await api2("POST", "/api/v1/data/apply", { batchId, requestHash, confirm });
1481
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1482
+ }
1483
+ );
1484
+ server2.tool(
1485
+ "get_data_batch",
1486
+ "Read a batch back by batchId (status, stored preview or result, requestHash), e.g. after a dropped connection. Only this person's batches.",
1487
+ {
1488
+ batchId: z2.string().describe("The batchId passed to data_dry_run")
1489
+ },
1490
+ async ({ batchId }) => {
1491
+ const data = await api2("GET", `/api/v1/data/batches/${encodeURIComponent(batchId)}`);
1492
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
892
1493
  }
893
1494
  );
894
1495
  server2.tool(
895
1496
  "get_portfolio_summary",
896
- "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. Requires the tensor:portfolio:read scope.",
1497
+ "Net worth, assets, liabilities, cost basis and unrealized P/L in USD, optionally grouped by entity, account, asset class or currency: the Tensor dashboard's own fold. Use it instead of adding up positions. Check `coverage` before calling a total exact.",
897
1498
  {
898
- groupBy: z.string().optional().describe("Comma-separated breakdowns: entity, account, assetClass, currency. Omit for headline totals only."),
899
- scope: z.enum(["dashboard", "all"]).optional().describe("'dashboard' (default) counts only entities marked for portfolio display, matching the Tensor dashboard. 'all' counts every entity."),
900
- includeClosed: z.boolean().optional().describe("Include closed positions. Default false."),
901
- entityId: z.number().optional().describe("Restrict to one entity"),
902
- accountId: z.number().optional().describe("Restrict to one custody account"),
903
- assetClass: z.string().optional().describe("Restrict to one asset class")
1499
+ groupBy: z2.string().optional().describe("Comma-separated breakdowns: entity, account, assetClass, currency. Omit for headline totals only."),
1500
+ scope: z2.enum(["dashboard", "all"]).optional().describe("'dashboard' (default): entities shown on the dashboard. 'all': every entity."),
1501
+ includeClosed: z2.boolean().optional().describe("Include closed positions. Default false."),
1502
+ entityId: z2.number().optional().describe("Restrict to one entity"),
1503
+ accountId: z2.number().optional().describe("Restrict to one custody account"),
1504
+ assetClass: z2.string().optional().describe("Restrict to one asset class")
904
1505
  },
905
1506
  async ({ groupBy, scope, includeClosed, entityId, accountId, assetClass }) => {
906
1507
  const params = new URLSearchParams();
@@ -911,60 +1512,125 @@ function registerAllTools(server2, api) {
911
1512
  if (accountId) params.set("accountId", String(accountId));
912
1513
  if (assetClass) params.set("assetClass", assetClass);
913
1514
  const qs = params.toString();
914
- const data = await api("GET", `/api/v1/portfolio/summary${qs ? `?${qs}` : ""}`);
915
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1515
+ const data = await api2("GET", `/api/v1/portfolio/summary${qs ? `?${qs}` : ""}`);
1516
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1517
+ }
1518
+ );
1519
+ server2.tool(
1520
+ "list_fund_performance",
1521
+ "Every fund LP position's performance: paid-in, distributions, unfunded, DPI/RVPI/TVPI, IRR or time-weighted return, NAV and its staleness, with the fund's terms. Quote these; never compute them from transactions. Figures are in each position's currency. `reconciliation.matches: false` means stored cost disagrees with the ledger: say so.",
1522
+ {
1523
+ includeClosed: z2.boolean().optional().describe("Include closed fund positions. Default false.")
1524
+ },
1525
+ async ({ includeClosed }) => {
1526
+ const data = await api2("GET", `/api/v1/portfolio/funds${includeClosed ? "?includeClosed=true" : ""}`);
1527
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1528
+ }
1529
+ );
1530
+ server2.tool(
1531
+ "get_fund_performance",
1532
+ "One fund position's performance and terms (one entry of list_fund_performance).",
1533
+ { positionId: z2.number().describe("Position ID of the fund interest") },
1534
+ async ({ positionId }) => {
1535
+ const data = await api2("GET", `/api/v1/portfolio/funds/${positionId}`);
1536
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1537
+ }
1538
+ );
1539
+ server2.tool(
1540
+ "list_fund_terms",
1541
+ "Every fund position's descriptive terms (structure, manager, vintage, commitment, fees, liquidity), no figures.",
1542
+ {},
1543
+ async () => {
1544
+ const data = await api2("GET", `/api/fund-terms`);
1545
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1546
+ }
1547
+ );
1548
+ server2.tool(
1549
+ "get_fund_terms",
1550
+ "One fund position's terms.",
1551
+ { positionId: z2.number().describe("Position ID of the fund interest") },
1552
+ async ({ positionId }) => {
1553
+ const data = await api2("GET", `/api/fund-terms/${positionId}`);
1554
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1555
+ }
1556
+ );
1557
+ server2.tool(
1558
+ "list_loan_terms",
1559
+ "Every private loan's terms: borrower, institution, rate (0.08 = 8%), start and maturity. The balance is on the position; advances and repayments are its transactions.",
1560
+ {},
1561
+ async () => {
1562
+ const data = await api2("GET", `/api/loan-terms`);
1563
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1564
+ }
1565
+ );
1566
+ server2.tool(
1567
+ "get_loan_terms",
1568
+ "One loan position's terms.",
1569
+ { positionId: z2.number().describe("Position ID of the loan") },
1570
+ async ({ positionId }) => {
1571
+ const data = await api2("GET", `/api/loan-terms/${positionId}`);
1572
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1573
+ }
1574
+ );
1575
+ server2.tool(
1576
+ "list_fx_rates",
1577
+ "Exchange rates as `rateToUsd` (amount x rate = USD), with source and updatedAt. A currency with no rate is shown 1:1 by Tensor.",
1578
+ {},
1579
+ async () => {
1580
+ const data = await api2("GET", `/api/fx`);
1581
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
916
1582
  }
917
1583
  );
918
1584
  server2.tool(
919
1585
  "search_market_quotes",
920
- "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. Requires the tensor:portfolio:read scope.",
1586
+ "Search Yahoo Finance and CoinGecko for a quote symbol to put in an asset's tickerSymbol. Always search; never guess a ticker.",
921
1587
  {
922
- q: z.string().describe("Free-text query \u2014 a company name, ticker, or coin name"),
923
- limit: z.number().optional().describe("Max candidates to return. Default 10, max 25.")
1588
+ q: z2.string().describe("Free-text query \u2014 a company name, ticker, or coin name"),
1589
+ limit: z2.number().optional().describe("Max candidates to return. Default 10, max 25.")
924
1590
  },
925
1591
  async ({ q, limit }) => {
926
1592
  const params = new URLSearchParams({ q });
927
1593
  if (limit) params.set("limit", String(limit));
928
- const data = await api("GET", `/api/v1/prices/search?${params.toString()}`);
929
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1594
+ const data = await api2("GET", `/api/v1/prices/search?${params.toString()}`);
1595
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
930
1596
  }
931
1597
  );
932
1598
  server2.tool(
933
1599
  "verify_market_quote",
934
- "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. Requires the tensor:portfolio:read scope.",
935
- { symbol: z.string().describe("Provider symbol to check, e.g. 'BRK-B', 'BTC-USD', or 'CG:official-trump'") },
1600
+ "Check a quote symbol resolves to a live price, writing nothing. When `corrected` is true, store the returned symbol.",
1601
+ { symbol: z2.string().describe("Provider symbol to check, e.g. 'BRK-B', 'BTC-USD', or 'CG:official-trump'") },
936
1602
  async ({ symbol }) => {
937
- const data = await api("GET", `/api/v1/prices/quote?symbol=${encodeURIComponent(symbol)}`);
938
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1603
+ const data = await api2("GET", `/api/v1/prices/quote?symbol=${encodeURIComponent(symbol)}`);
1604
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
939
1605
  }
940
1606
  );
941
1607
  server2.tool(
942
1608
  "sync_prices",
943
- "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. Requires the tensor:portfolio:write scope.",
1609
+ "Fetch quotes for linked assets and WRITE a price row for each, repricing their positions. Omit assetIds for the whole catalog (ask first). Reports synced, skipped and failed symbols.",
944
1610
  {
945
- assetIds: z.array(z.number()).optional().describe("Only sync these asset IDs. Omit to sync every linked asset in the organization.")
1611
+ assetIds: z2.array(z2.number()).optional().describe("Only sync these asset IDs. Omit to sync every linked asset in the organization.")
946
1612
  },
947
1613
  async ({ assetIds }) => {
948
- const data = await api("POST", "/api/v1/prices/sync", assetIds ? { assetIds } : {});
949
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1614
+ const data = await api2("POST", "/api/v1/prices/sync", assetIds ? { assetIds } : {});
1615
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
950
1616
  }
951
1617
  );
952
1618
  server2.tool(
953
1619
  "sync_asset_price",
954
- "Trigger a price sync for one asset by ID. Fails if the asset has no price-provider symbol linked. Use sync_prices for bulk. Requires the tensor:portfolio:write scope.",
955
- { id: z.number().describe("Asset ID to reprice") },
1620
+ "Fetch and record one asset's quote. Fails when it has no tickerSymbol.",
1621
+ { id: z2.number().describe("Asset ID to reprice") },
956
1622
  async ({ id }) => {
957
- const data = await api("POST", `/api/v1/prices/sync/${id}`);
958
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1623
+ const data = await api2("POST", `/api/v1/prices/sync/${id}`);
1624
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
959
1625
  }
960
1626
  );
961
1627
  server2.tool(
962
1628
  "list_changes",
963
- "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`. The history is kept 90 days. Requires the tensor:portfolio:read scope, and you see only the changes your scopes can read: the ledger under portfolio:read, and each other surface only with its own read scope (reference, files, todos, ideas, bookmarks, tabs). Memos, links, tags, loan and fund terms, FX and organisation settings appear to no key, and another person's tab groups and browsing history never appear. A missing type means 'not yours to see', not 'unchanged'.",
1629
+ "Creates, updates and deletes since a time, to catch up instead of re-reading. Resume from the returned `until`. If `coverage.complete` is false the delta is untrustworthy: do a full read. Kept 90 days. Only types your scopes read appear; memos, links, tags, terms, FX and settings never do.",
964
1630
  {
965
- since: z.number().optional().describe("Epoch-ms lower bound (exclusive). Omit or 0 for everything on record."),
966
- limit: z.number().optional().describe("Max changes per page. Default 500."),
967
- resourceType: z.string().optional().describe("Only changes to this resource type, e.g. 'position', 'asset', 'entity'")
1631
+ since: z2.number().optional().describe("Epoch-ms lower bound (exclusive). Omit or 0 for everything on record."),
1632
+ limit: z2.number().optional().describe("Max changes per page. Default 500."),
1633
+ resourceType: z2.string().optional().describe("Only changes to this resource type, e.g. 'position', 'asset', 'entity'")
968
1634
  },
969
1635
  async ({ since, limit, resourceType }) => {
970
1636
  const params = new URLSearchParams();
@@ -972,39 +1638,50 @@ function registerAllTools(server2, api) {
972
1638
  if (limit) params.set("limit", String(limit));
973
1639
  if (resourceType) params.set("resourceType", resourceType);
974
1640
  const qs = params.toString();
975
- const data = await api("GET", `/api/v1/changes${qs ? `?${qs}` : ""}`);
976
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1641
+ const data = await api2("GET", `/api/v1/changes${qs ? `?${qs}` : ""}`);
1642
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1643
+ }
1644
+ );
1645
+ server2.tool(
1646
+ "list_trash",
1647
+ "Every Trash this connection can read (todos, ideas, files, bookmarks, tab groups): what was deleted, when, and when it is purged. Restore with that surface's restore_ tool. Only a person can empty Trash.",
1648
+ {},
1649
+ async () => {
1650
+ const data = await api2("GET", "/api/trash");
1651
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
977
1652
  }
978
1653
  );
979
1654
  server2.tool(
980
1655
  "search_records",
981
- "Site-wide ranked search across every record type at once \u2014 entities, institutions, accounts, positions, assets, transactions, files, todos, ideas, bookmarks and parked tabs. Reference ids resolve directly: 'TSK-12' (todo), 'AS002' (asset), 'T042' (transaction), 'BMK-9' (bookmark). 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/bookmarks/tabs:read for theirs). THE TAB LANE'S UNIT IS A TAB, NOT A GROUP \u2014 you search a title and get the parked page, though the thing you can restore or delete is its group. Memos and browsing history are the two record types NO key reaches: memos because they are session-only, history (pages a person visited, 'HIS-12') because it answers only Tensor's own web app and Chrome extension \u2014 no scope opens either lane. 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.",
1656
+ "Ranked search across entities, institutions, accounts, positions, assets, transactions, files, todos, ideas, bookmarks and parked tabs, by name or reference id ('TSK-12', 'AS002', 'T042', 'BMK-9'). A tab hit is a page; its group is what you restore or delete. Memos and browsing history are never searchable by a connection. Lanes you cannot read are left out, so no hits is not proof of absence. Not for tickers: search_market_quotes.",
982
1657
  {
983
- q: z.string().describe("The query. Title, body and reference-id lanes, one ranking; short and literal works best."),
984
- 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' and 'history' are spelled here because they are Tensor's record types, not because a key can search them: naming either adds nothing, and naming only those is the no-lane 403."),
985
- limit: z.number().optional().describe("Max hits. Default 20, capped server-side."),
986
- 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.")
1658
+ q: z2.string().describe("The query. Title, body and reference-id lanes, one ranking; short and literal works best."),
1659
+ types: z2.array(z2.enum(SEARCH_RECORD_TYPES_MIRROR)).optional().describe("Only these record types. By default transactions are left out unless q is a T-ref. memo and history never match for a connection."),
1660
+ limit: z2.number().optional().describe("Max hits. Default 20, capped server-side."),
1661
+ includeArchived: z2.boolean().optional().describe("Include archived rows. Moves nothing for a connection (only memos have an archive).")
987
1662
  },
988
1663
  async ({ q, types, limit, includeArchived }) => {
989
1664
  const params = new URLSearchParams({ q });
990
1665
  if (types?.length) params.set("types", types.join(","));
991
1666
  if (limit) params.set("limit", String(limit));
992
1667
  if (includeArchived) params.set("includeArchived", "1");
993
- const data = await api("GET", `/api/search?${params.toString()}`);
994
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1668
+ const data = await api2("GET", `/api/search?${params.toString()}`);
1669
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
995
1670
  }
996
1671
  );
997
1672
  server2.tool(
998
1673
  "list_files",
999
- "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.",
1000
- {
1001
- limit: z.number().optional().describe("Page size. Default 200, max 1000."),
1002
- offset: z.number().optional().describe("Pagination offset. Default 0."),
1003
- urls: z.boolean().optional().describe("Mint short-lived presigned download URLs for this page. Default false \u2014 request only when actually downloading."),
1004
- 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."),
1005
- deviceId: z.number().optional().describe(
1006
- "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."
1007
- )
1674
+ // Previously claimed encrypted files "cannot be read or mirrored
1675
+ // through the API", which stopped being true when device key release
1676
+ // shipped: ?deviceId=N returns a per-file wrappedDek. Agents were
1677
+ // reporting an encrypted library as unmirrorable and giving up.
1678
+ "The flat export manifest for backup and mirroring: folder/filename path, checksum, size. To find or manage files use browse_files. urls=true mints download URLs: inventory first, then ask for urls with ids of just the files you will fetch. Encrypted rows return ciphertext; with deviceId each also carries a `wrappedDek` sealed to that registered device, otherwise say plainly nobody can open the bytes. Skip rows marked `unreadable`.",
1679
+ {
1680
+ limit: z2.number().optional().describe("Page size. Default 200, max 1000."),
1681
+ offset: z2.number().optional().describe("Pagination offset. Default 0."),
1682
+ urls: z2.boolean().optional().describe("Also mint download URLs for this page. Only when about to download."),
1683
+ ids: z2.array(z2.number()).optional().describe("Only these file ids (max 200), e.g. the ones that changed."),
1684
+ deviceId: z2.number().optional().describe("With urls=true: also each encrypted file's key, wrapped to this registered device's public key (devices are enrolled by a person in a browser; 404 if unknown or revoked). Omit unless you hold the device's private key.")
1008
1685
  },
1009
1686
  async ({ limit, offset, urls, ids, deviceId }) => {
1010
1687
  const params = new URLSearchParams();
@@ -1014,245 +1691,239 @@ function registerAllTools(server2, api) {
1014
1691
  if (ids?.length) params.set("ids", ids.join(","));
1015
1692
  if (deviceId != null) params.set("deviceId", String(deviceId));
1016
1693
  const qs = params.toString();
1017
- const data = await api("GET", `/api/files/manifest${qs ? `?${qs}` : ""}`);
1018
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1694
+ const data = await api2("GET", `/api/files/manifest${qs ? `?${qs}` : ""}`);
1695
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1019
1696
  }
1020
1697
  );
1021
1698
  server2.tool(
1022
1699
  "browse_files",
1023
- '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.',
1024
- {
1025
- limit: z.number().optional().describe("Max results. Default 500."),
1026
- offset: z.number().optional().describe("Pagination offset"),
1027
- folderId: z.number().optional().describe("Only files whose home is this folder (see list_file_folders). Omit for every folder."),
1028
- 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."),
1029
- targetId: z.number().optional().describe("The record id targetType points at. Send both or neither."),
1030
- q: z.string().optional().describe("Case-insensitive substring over title and filename"),
1031
- trash: z.boolean().optional().describe("true = list the Trash instead of live files. Default false."),
1700
+ "Find files the way the Files page does: by folder, by attached record, by title or filename, or the Trash. Metadata and links, never bytes (get_file_download_url).",
1701
+ {
1702
+ limit: LIMIT_INPUT,
1703
+ offset: OFFSET_INPUT,
1704
+ folderId: z2.number().optional().describe("Only files whose home is this folder (see list_file_folders). Omit for every folder."),
1705
+ targetType: z2.enum(FILE_ATTACH_TARGET_TYPES).optional().describe("With targetId: files attached to this record (any linkable type)."),
1706
+ targetId: z2.number().optional().describe("The record id targetType points at. Send both or neither."),
1707
+ withDescendants: z2.boolean().optional().describe("With a target: also files attached to records beneath it (an entity's accounts and positions, an account's positions, a position's transactions). Each such row carries `via`, the record it is attached to."),
1708
+ q: z2.string().optional().describe("Case-insensitive substring over title and filename"),
1709
+ trash: z2.boolean().optional().describe("true = list the Trash instead of live files. Default false."),
1032
1710
  // ORDERING, and the last thing the Files page could ask for that this
1033
1711
  // tool could not. It is a SERVER-side order, which is what makes it worth
1034
1712
  // having: the listing is capped, so re-sorting a page locally orders the
1035
1713
  // window and not the library — "the ten biggest files" computed that way
1036
1714
  // is the ten biggest of the most recent five hundred. Optional, so every
1037
1715
  // existing caller is unaffected; that is what makes it a MINOR bump.
1038
- sort: z.enum(FILE_LIST_SORTS).optional().describe(
1039
- "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'."
1040
- )
1716
+ sort: z2.enum(FILE_LIST_SORTS).optional().describe("Default added_desc (newest first). size is the plaintext size; name is not a natural sort ('Q10' before 'Q9').")
1041
1717
  },
1042
- async ({ limit, offset, folderId, targetType, targetId, q, trash, sort }) => {
1718
+ async ({ limit, offset, folderId, targetType, targetId, withDescendants, q, trash, sort }) => {
1043
1719
  const params = new URLSearchParams();
1044
- if (limit) params.set("limit", String(limit));
1045
- if (offset) params.set("offset", String(offset));
1046
1720
  if (folderId != null) params.set("folderId", String(folderId));
1047
1721
  if (targetType) params.set("targetType", targetType);
1048
1722
  if (targetId != null) params.set("targetId", String(targetId));
1723
+ if (withDescendants) params.set("withDescendants", "1");
1049
1724
  if (q) params.set("q", q);
1050
1725
  if (trash) params.set("trash", "1");
1051
1726
  if (sort) params.set("sort", sort);
1052
- const qs = params.toString();
1053
- const data = await api("GET", `/api/files${qs ? `?${qs}` : ""}`);
1054
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1727
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/files?${qs}`));
1055
1728
  }
1056
1729
  );
1057
1730
  server2.tool(
1058
1731
  "get_file",
1059
- '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.',
1060
- { id: z.number().describe("File ID") },
1732
+ "One file's metadata and links. Never bytes.",
1733
+ { id: z2.number().describe("File ID") },
1061
1734
  async ({ id }) => {
1062
- const data = await api("GET", `/api/files/${id}`);
1063
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1735
+ const data = await api2("GET", `/api/files/${id}`);
1736
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1064
1737
  }
1065
1738
  );
1066
1739
  server2.tool(
1067
1740
  "create_file_upload_url",
1068
- "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.",
1741
+ "Upload step 1 of 3 (presign, PUT, confirm): mint a PUT URL and storageKey. PUT the bytes to `url`, then confirm_file_upload. If the answer says envelopeVersion 1, the body must be a TDE1 envelope encrypted with your own key (sent as `dek` at confirm); plaintext is refused.",
1069
1742
  {
1070
- filename: z.string().describe("Original filename. Display data only \u2014 never used in storage paths."),
1071
- mimeType: z.string().describe("The file's MIME type. Must be on Tensor's upload allow-list; 'Unsupported file type.' means it is not."),
1072
- sizeBytes: z.number().describe("PLAINTEXT byte size of the file (the cap is on the file, not the envelope)"),
1073
- 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."),
1074
- chunkSize: z.number().optional().describe("Requested TDE1 frame size in bytes. Omit for the default; upload under whatever the response echoes.")
1743
+ filename: z2.string().describe("Original filename. Display data only \u2014 never used in storage paths."),
1744
+ mimeType: z2.string().describe("MIME type; must be on Tensor's upload allow-list."),
1745
+ sizeBytes: z2.number().describe("Plaintext size in bytes."),
1746
+ envelopeVersion: z2.union([z2.literal(0), z2.literal(1)]).optional().describe("1 if you can build a TDE1 envelope, else omit. The answer says which to upload."),
1747
+ chunkSize: z2.number().optional().describe("TDE1 frame size; omit for the default and use what the answer says.")
1075
1748
  },
1076
1749
  async (params) => {
1077
- const data = await api("POST", "/api/files/upload-url", params);
1078
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1750
+ const data = await api2("POST", "/api/files/upload-url", params);
1751
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1079
1752
  }
1080
1753
  );
1081
1754
  server2.tool(
1082
1755
  "confirm_file_upload",
1083
- "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.",
1084
- {
1085
- storageKey: z.string().describe("The storageKey minted by create_file_upload_url"),
1086
- title: z.string().describe("Display title"),
1087
- filename: z.string().describe("Original filename"),
1088
- folderId: z.number().optional().describe("Home folder id (see list_file_folders). Omit for the root."),
1089
- notes: z.string().optional(),
1090
- checksumSha256: z.string().optional().describe("SHA-256 of the plaintext bytes, stored so backup agents can verify mirrors"),
1091
- links: z.array(z.object({
1092
- targetType: z.enum(FILE_ATTACH_TARGET_TYPES),
1093
- targetId: z.number()
1094
- })).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."),
1095
- 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."),
1096
- chunkSize: z.number().optional().describe("TDE1 frame size used. Required when envelopeVersion is 1."),
1097
- 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."),
1098
- dek: z.string().optional().describe("Base64 AES-256 key the envelope was encrypted with. Required when envelopeVersion is 1.")
1756
+ "Upload step 3: create the file row from the uploaded object, optionally attached to records. For an encrypted upload pass envelopeVersion, chunkSize, mimeType and dek.",
1757
+ {
1758
+ storageKey: z2.string().describe("The storageKey minted by create_file_upload_url"),
1759
+ title: z2.string().describe("Display title"),
1760
+ filename: z2.string().describe("Original filename"),
1761
+ folderId: z2.number().optional().describe("Home folder id (see list_file_folders). Omit for the root."),
1762
+ notes: z2.string().optional(),
1763
+ checksumSha256: z2.string().optional().describe("SHA-256 of the plaintext bytes, stored so backup agents can verify mirrors"),
1764
+ links: z2.array(z2.object({
1765
+ targetType: z2.enum(FILE_ATTACH_TARGET_TYPES),
1766
+ targetId: z2.number()
1767
+ })).optional().describe("Attach to records now, as attach_file_link would."),
1768
+ envelopeVersion: z2.union([z2.literal(0), z2.literal(1)]).optional().describe("1 if the bytes are a TDE1 envelope; must match the presign's answer."),
1769
+ chunkSize: z2.number().optional().describe("TDE1 frame size used. Required when envelopeVersion is 1."),
1770
+ mimeType: z2.string().optional().describe("The real MIME type. Required for an encrypted upload."),
1771
+ dek: z2.string().optional().describe("Base64 AES-256 key of the envelope. Required for an encrypted upload; stored wrapped.")
1099
1772
  },
1100
1773
  async (params) => {
1101
- const data = await api("POST", "/api/files", params);
1102
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1774
+ const data = await api2("POST", "/api/files", params);
1775
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1103
1776
  }
1104
1777
  );
1105
1778
  server2.tool(
1106
1779
  "update_file",
1107
- "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.",
1780
+ "Rename, move or annotate a file (title, folderId, notes). Content is immutable; new content is a new upload.",
1108
1781
  {
1109
- id: z.number().describe("File ID"),
1110
- title: z.string().optional(),
1111
- folderId: z.number().nullable().optional().describe("New home folder id, or null for the root"),
1112
- notes: z.string().nullable().optional()
1782
+ id: z2.number().describe("File ID"),
1783
+ title: z2.string().optional(),
1784
+ folderId: z2.number().nullable().optional().describe("New home folder id, or null for the root"),
1785
+ notes: z2.string().nullable().optional()
1113
1786
  },
1114
1787
  async ({ id, ...body }) => {
1115
- const data = await api("PATCH", `/api/files/${id}`, body);
1116
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1788
+ const data = await api2("PATCH", `/api/files/${id}`, body);
1789
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1117
1790
  }
1118
1791
  );
1119
1792
  server2.tool(
1120
1793
  "delete_file",
1121
- "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.",
1122
- { id: z.number().describe("File ID") },
1794
+ "Move a file to Trash.",
1795
+ { id: z2.number().describe("File ID") },
1123
1796
  async ({ id }) => {
1124
- const data = await api("DELETE", `/api/files/${id}`);
1125
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1797
+ const data = await api2("DELETE", `/api/files/${id}`);
1798
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1126
1799
  }
1127
1800
  );
1128
1801
  server2.tool(
1129
1802
  "restore_file",
1130
- "Restore a file from the Trash. 404 when the file is not in the Trash. Requires the tensor:files:write scope.",
1131
- { id: z.number().describe("File ID") },
1803
+ "Take a file out of Trash.",
1804
+ { id: z2.number().describe("File ID") },
1132
1805
  async ({ id }) => {
1133
- const data = await api("POST", `/api/files/${id}/restore`);
1134
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1806
+ const data = await api2("POST", `/api/files/${id}/restore`);
1807
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1135
1808
  }
1136
1809
  );
1137
1810
  server2.tool(
1138
1811
  "get_file_download_url",
1139
- "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.",
1812
+ "Mint a short-lived download URL for one file (Trash too). For an encrypted file it points at ciphertext and also returns the `dek`, a permanent, logged key release.",
1140
1813
  {
1141
- id: z.number().describe("File ID"),
1142
- inline: z.boolean().optional().describe("Ask for preview (inline) disposition instead of download. Honored only for previewable plaintext types.")
1814
+ id: z2.number().describe("File ID"),
1815
+ inline: z2.boolean().optional().describe("Ask for preview (inline) disposition instead of download. Honored only for previewable plaintext types.")
1143
1816
  },
1144
1817
  async ({ id, inline }) => {
1145
- const data = await api("GET", `/api/files/${id}/download-url${inline ? "?inline=1" : ""}`);
1146
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1818
+ const data = await api2("GET", `/api/files/${id}/download-url${inline ? "?inline=1" : ""}`);
1819
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1147
1820
  }
1148
1821
  );
1149
1822
  server2.tool(
1150
1823
  "list_file_links",
1151
- `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".`,
1152
- { id: z.number().describe("File ID") },
1824
+ "A file's attachments. Each row's id is the linkId detach_file_link takes, not the record's id.",
1825
+ { id: z2.number().describe("File ID") },
1153
1826
  async ({ id }) => {
1154
- const data = await api("GET", `/api/files/${id}/links`);
1155
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1827
+ const data = await api2("GET", `/api/files/${id}/links`);
1828
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1156
1829
  }
1157
1830
  );
1158
1831
  server2.tool(
1159
1832
  "attach_file_link",
1160
- "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.",
1833
+ "Attach a file to a record (ledger record, todo, idea). Repeating it returns the same linkId.",
1161
1834
  {
1162
- id: z.number().describe("File ID"),
1163
- 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."),
1164
- targetId: z.number().describe("The record's ID")
1835
+ id: z2.number().describe("File ID"),
1836
+ targetType: z2.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."),
1837
+ targetId: z2.number().describe("The record's ID")
1165
1838
  },
1166
1839
  async ({ id, ...body }) => {
1167
- const data = await api("POST", `/api/files/${id}/links`, body);
1168
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1840
+ const data = await api2("POST", `/api/files/${id}/links`, body);
1841
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1169
1842
  }
1170
1843
  );
1171
1844
  server2.tool(
1172
1845
  "detach_file_link",
1173
- "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.",
1846
+ "Detach a file from a record by linkId. The file and the record stay.",
1174
1847
  {
1175
- id: z.number().describe("File ID"),
1176
- linkId: z.number().describe("The link's id from list_file_links \u2014 not the target record's id")
1848
+ id: z2.number().describe("File ID"),
1849
+ linkId: z2.number().describe("The link's id from list_file_links \u2014 not the target record's id")
1177
1850
  },
1178
1851
  async ({ id, linkId }) => {
1179
- const data = await api("DELETE", `/api/files/${id}/links/${linkId}`);
1180
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1852
+ const data = await api2("DELETE", `/api/files/${id}/links/${linkId}`);
1853
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1181
1854
  }
1182
1855
  );
1183
1856
  server2.tool(
1184
1857
  "list_file_folders",
1185
- "List every file folder: id, name, parentId nesting, and an optional pin to one ledger record. Requires the tensor:files:read scope.",
1858
+ "Every file folder: id, name, parentId, and an optional pin to one ledger record.",
1186
1859
  {},
1187
1860
  async () => {
1188
- const data = await api("GET", "/api/file-folders");
1189
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1861
+ const data = await api2("GET", "/api/file-folders");
1862
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1190
1863
  }
1191
1864
  );
1192
1865
  server2.tool(
1193
1866
  "create_file_folder",
1194
- "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.",
1867
+ "Create a file folder, nested by parentId, optionally pinned to one ledger record's Files tab.",
1195
1868
  {
1196
- name: z.string().describe("Folder name"),
1197
- parentId: z.number().nullable().optional().describe("Parent folder id, or null/omit for top level"),
1198
- notes: z.string().optional(),
1199
- 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."),
1200
- targetId: z.number().nullable().optional()
1869
+ name: z2.string().describe("Folder name"),
1870
+ parentId: z2.number().nullable().optional().describe("Parent folder id, or null/omit for top level"),
1871
+ notes: z2.string().optional(),
1872
+ targetType: z2.enum(RECORD_TARGET_TYPES).nullable().optional().describe("With targetId, pin the folder to one ledger record."),
1873
+ targetId: z2.number().nullable().optional()
1201
1874
  },
1202
1875
  async (params) => {
1203
- const data = await api("POST", "/api/file-folders", params);
1204
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1876
+ const data = await api2("POST", "/api/file-folders", params);
1877
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1205
1878
  }
1206
1879
  );
1207
1880
  server2.tool(
1208
1881
  "update_file_folder",
1209
- "Rename, move or re-pin a file folder (partial update). Requires the tensor:files:write scope.",
1882
+ "Rename, move or re-pin a file folder.",
1210
1883
  {
1211
- id: z.number().describe("Folder ID"),
1212
- name: z.string().optional(),
1213
- parentId: z.number().nullable().optional().describe("New parent folder id, or null for top level"),
1214
- notes: z.string().nullable().optional(),
1215
- targetType: z.enum(RECORD_TARGET_TYPES).nullable().optional(),
1216
- targetId: z.number().nullable().optional()
1884
+ id: z2.number().describe("Folder ID"),
1885
+ name: z2.string().optional(),
1886
+ parentId: z2.number().nullable().optional().describe("New parent folder id, or null for top level"),
1887
+ notes: z2.string().nullable().optional(),
1888
+ targetType: z2.enum(RECORD_TARGET_TYPES).nullable().optional(),
1889
+ targetId: z2.number().nullable().optional()
1217
1890
  },
1218
1891
  async ({ id, ...body }) => {
1219
- const data = await api("PATCH", `/api/file-folders/${id}`, body);
1220
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1892
+ const data = await api2("PATCH", `/api/file-folders/${id}`, body);
1893
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1221
1894
  }
1222
1895
  );
1223
1896
  server2.tool(
1224
1897
  "delete_file_folder",
1225
- "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.",
1226
- { id: z.number().describe("Folder ID") },
1898
+ "Delete an EMPTY file folder; 409 while it holds files or folders.",
1899
+ { id: z2.number().describe("Folder ID") },
1227
1900
  async ({ id }) => {
1228
- const data = await api("DELETE", `/api/file-folders/${id}`);
1229
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1901
+ const data = await api2("DELETE", `/api/file-folders/${id}`);
1902
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1230
1903
  }
1231
1904
  );
1232
1905
  server2.tool(
1233
1906
  "list_todos",
1234
- "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.",
1907
+ "List todos, filtered server-side. Default: the live list with sub-tasks; trash for the Trash, topLevelOnly for roots, parentId for one checklist.",
1235
1908
  {
1236
- limit: z.number().optional().describe("Max results. Default 500."),
1237
- offset: z.number().optional().describe("Pagination offset"),
1238
- stateId: z.number().optional().describe("Only todos in this workflow state (see list_todo_states)"),
1239
- category: z.enum(TODO_STATE_CATEGORIES).optional().describe("Only todos whose state has this category \u2014 the stable axis; states are org-renamable tags over it"),
1909
+ limit: LIMIT_INPUT,
1910
+ offset: OFFSET_INPUT,
1911
+ stateId: z2.number().optional().describe("Only todos in this workflow state (see list_todo_states)"),
1912
+ category: z2.enum(TODO_STATE_CATEGORIES).optional().describe("Only todos whose state has this category \u2014 the stable axis; states are org-renamable tags over it"),
1240
1913
  // One id or several, OR-combined server-side. See numListParam.
1241
- 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"),
1242
- priority: z.number().optional().describe("Exact priority: 0 = none, 1 = urgent, 2 = high, 3 = medium, 4 = low"),
1243
- tagId: z.union([z.number(), z.array(z.number())]).optional().describe("Only todos carrying this tag \u2014 or any of these tags; pass one id or an array (see list_todo_tags)"),
1244
- parentId: z.number().optional().describe("Only sub-tasks of this todo"),
1245
- topLevelOnly: z.boolean().optional().describe("Only top-level todos (no parent). Ignored when parentId is set."),
1246
- 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."),
1247
- targetId: z.number().optional().describe("The record id targetType points at"),
1248
- q: z.string().optional().describe("Case-insensitive substring over title and body text"),
1249
- trash: z.boolean().optional().describe("Only todos in Trash (deleted, still recoverable) instead of the live list"),
1250
- sort: z.enum(TODO_LIST_SORTS).optional().describe("Order: manual (the board's rank order, default), created, updated, due, or priority")
1914
+ assigneeId: z2.union([z2.number(), z2.array(z2.number())]).optional().describe("Only todos assigned to this user \u2014 or to any of these users; pass one id or an array"),
1915
+ priority: z2.number().optional().describe("Exact priority: 0 = none, 1 = urgent, 2 = high, 3 = medium, 4 = low"),
1916
+ tagId: z2.union([z2.number(), z2.array(z2.number())]).optional().describe("Only todos carrying this tag \u2014 or any of these tags; pass one id or an array (see list_todo_tags)"),
1917
+ parentId: z2.number().optional().describe("Only sub-tasks of this todo"),
1918
+ topLevelOnly: z2.boolean().optional().describe("Only top-level todos (no parent). Ignored when parentId is set."),
1919
+ targetType: z2.enum(TODO_LINK_TARGET_TYPES).optional().describe("With targetId: todos linked to this record."),
1920
+ targetId: z2.number().optional().describe("The record id targetType points at"),
1921
+ q: z2.string().optional().describe("Case-insensitive substring over title and body text"),
1922
+ trash: z2.boolean().optional().describe("Only todos in Trash (deleted, still recoverable) instead of the live list"),
1923
+ sort: z2.enum(TODO_LIST_SORTS).optional().describe("Order: manual (the board's rank order, default), created, updated, due, or priority")
1251
1924
  },
1252
1925
  async ({ limit, offset, stateId, category, assigneeId, priority, tagId, parentId, topLevelOnly, targetType, targetId, q, trash, sort }) => {
1253
1926
  const params = new URLSearchParams();
1254
- if (limit) params.set("limit", String(limit));
1255
- if (offset) params.set("offset", String(offset));
1256
1927
  if (stateId) params.set("stateId", String(stateId));
1257
1928
  if (category) params.set("category", category);
1258
1929
  const assignees = numListParam(assigneeId);
@@ -1267,80 +1938,78 @@ function registerAllTools(server2, api) {
1267
1938
  if (q) params.set("q", q);
1268
1939
  if (trash) params.set("trash", "1");
1269
1940
  if (sort) params.set("sort", sort);
1270
- const qs = params.toString();
1271
- const data = await api("GET", `/api/todos${qs ? `?${qs}` : ""}`);
1272
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1941
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/todos?${qs}`));
1273
1942
  }
1274
1943
  );
1275
1944
  server2.tool(
1276
1945
  "get_todo",
1277
- "Get one todo by ID: title, body (bodyJson is the TipTap document, bodyText the server-derived plain text), state, priority, tags, record links, and sub-task counts. Requires the tensor:todos:read scope.",
1278
- { id: z.number().describe("Todo ID") },
1946
+ "One todo with body, state, priority, tags, links and sub-task counts.",
1947
+ { id: z2.number().describe("Todo ID") },
1279
1948
  async ({ id }) => {
1280
- const data = await api("GET", `/api/todos/${id}`);
1281
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1949
+ const data = await api2("GET", `/api/todos/${id}`);
1950
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1282
1951
  }
1283
1952
  );
1284
1953
  server2.tool(
1285
1954
  "get_todo_subtree",
1286
- "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.",
1287
- { id: z.number().describe("Todo ID") },
1955
+ "Counts under a todo (children, descendants, trashed, depth). Read before deleting or moving a todo with sub-tasks, to tell the user what goes with it.",
1956
+ { id: z2.number().describe("Todo ID") },
1288
1957
  async ({ id }) => {
1289
- const data = await api("GET", `/api/todos/${id}/subtree`);
1290
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1958
+ const data = await api2("GET", `/api/todos/${id}/subtree`);
1959
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1291
1960
  }
1292
1961
  );
1293
1962
  server2.tool(
1294
1963
  "get_todo_activity",
1295
- "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.",
1296
- { id: z.number().describe("Todo ID") },
1964
+ "A todo's latest 50 activity entries. Kept only 90 days.",
1965
+ { id: z2.number().describe("Todo ID") },
1297
1966
  async ({ id }) => {
1298
- const data = await api("GET", `/api/todos/${id}/activity`);
1299
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1967
+ const data = await api2("GET", `/api/todos/${id}/activity`);
1968
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1300
1969
  }
1301
1970
  );
1302
1971
  server2.tool(
1303
1972
  "create_todo",
1304
- "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).",
1305
- {
1306
- title: z.string().describe("Todo title (max 512 chars)"),
1307
- stateId: z.number().describe("Workflow state ID from list_todo_states"),
1308
- body: z.string().optional().describe("Body as plain text; each line becomes a paragraph. Stored as TipTap JSON, never HTML."),
1309
- priority: z.number().optional().describe("0 = none (default), 1 = urgent, 2 = high, 3 = medium, 4 = low"),
1310
- assigneeId: z.number().optional().describe("User ID to assign"),
1311
- parentId: z.number().optional().describe("Create as a sub-task of this todo"),
1312
- dueDate: z.string().optional().describe("Due date in ISO format YYYY-MM-DD"),
1313
- tagIds: z.array(z.number()).optional().describe("Tag IDs to attach at create (see list_todo_tags)"),
1973
+ "Create a todo. stateId must name a state from list_todo_states.",
1974
+ {
1975
+ title: z2.string().describe("Todo title (max 512 chars)"),
1976
+ stateId: z2.number().describe("Workflow state ID from list_todo_states"),
1977
+ body: z2.string().optional().describe("Plain text, one paragraph per line."),
1978
+ priority: z2.number().optional().describe("0 = none (default), 1 = urgent, 2 = high, 3 = medium, 4 = low"),
1979
+ assigneeId: z2.number().optional().describe("User ID to assign"),
1980
+ parentId: z2.number().optional().describe("Create as a sub-task of this todo"),
1981
+ dueDate: z2.string().optional().describe("Due date in ISO format YYYY-MM-DD"),
1982
+ tagIds: z2.array(z2.number()).optional().describe("Tag IDs to attach at create (see list_todo_tags)"),
1314
1983
  // TODO_LINK_TARGET_TYPES, not RECORD_TARGET_TYPES. This enum was the six
1315
1984
  // ledger records while `insertTodoSchema` was, which was faithful then and
1316
1985
  // is not now: the server accepts all nine here, the same set
1317
1986
  // attach_todo_link takes, because both are the same write through
1318
1987
  // `createLink`. A narrow enum would make "create a todo already linked to
1319
1988
  // a memo" unaskable while "create it, then attach_todo_link" worked.
1320
- links: z.array(z.object({
1321
- targetType: z.enum(TODO_LINK_TARGET_TYPES),
1322
- targetId: z.number()
1323
- })).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.")
1989
+ links: z2.array(z2.object({
1990
+ targetType: z2.enum(TODO_LINK_TARGET_TYPES),
1991
+ targetId: z2.number()
1992
+ })).optional().describe("Records to link the todo to now, as attach_todo_link would.")
1324
1993
  },
1325
1994
  async ({ body, ...rest }) => {
1326
1995
  const payload = { ...rest };
1327
1996
  if (body !== void 0 && body.trim().length > 0) payload.bodyJson = tiptapDocJson(body);
1328
- const data = await api("POST", "/api/todos", payload);
1329
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1997
+ const data = await api2("POST", "/api/todos", payload);
1998
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1330
1999
  }
1331
2000
  );
1332
2001
  server2.tool(
1333
2002
  "update_todo",
1334
- "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.",
2003
+ "Edit a todo. Pass expectedUpdatedAt to get a 409 with the current row if someone changed it meanwhile. Moving it under another todo is set_todo_parent.",
1335
2004
  {
1336
- id: z.number().describe("Todo ID"),
1337
- title: z.string().optional(),
1338
- stateId: z.number().optional().describe("Move to this workflow state"),
1339
- body: z.string().optional().describe("New body as plain text \u2014 replaces the existing body; empty string clears it"),
1340
- priority: z.number().optional().describe("0 = none, 1 = urgent, 2 = high, 3 = medium, 4 = low"),
1341
- assigneeId: z.number().nullable().optional().describe("User ID, or null to unassign"),
1342
- dueDate: z.string().nullable().optional().describe("ISO YYYY-MM-DD, or null to clear"),
1343
- expectedUpdatedAt: z.number().optional().describe("The todo's updatedAt as you loaded it \u2014 enables the stale-write check")
2005
+ id: z2.number().describe("Todo ID"),
2006
+ title: z2.string().optional(),
2007
+ stateId: z2.number().optional().describe("Move to this workflow state"),
2008
+ body: z2.string().optional().describe("Plain text; replaces the whole body. Empty clears it."),
2009
+ priority: z2.number().optional().describe("0 = none, 1 = urgent, 2 = high, 3 = medium, 4 = low"),
2010
+ assigneeId: z2.number().nullable().optional().describe("User ID, or null to unassign"),
2011
+ dueDate: z2.string().nullable().optional().describe("ISO YYYY-MM-DD, or null to clear"),
2012
+ expectedUpdatedAt: z2.number().optional().describe("The todo's updatedAt as you loaded it \u2014 enables the stale-write check")
1344
2013
  },
1345
2014
  async ({ id, body, ...rest }) => {
1346
2015
  const payload = { ...rest };
@@ -1352,727 +2021,815 @@ function registerAllTools(server2, api) {
1352
2021
  payload.bodyText = null;
1353
2022
  }
1354
2023
  }
1355
- const data = await api("PATCH", `/api/todos/${id}`, payload);
1356
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2024
+ const data = await api2("PATCH", `/api/todos/${id}`, payload);
2025
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1357
2026
  }
1358
2027
  );
1359
2028
  server2.tool(
1360
2029
  "delete_todo",
1361
- "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.",
1362
- { id: z.number().describe("Todo ID") },
2030
+ "Move a todo and its whole branch of sub-tasks to Trash. Reports `trashedDescendants`.",
2031
+ { id: z2.number().describe("Todo ID") },
1363
2032
  async ({ id }) => {
1364
- const data = await api("DELETE", `/api/todos/${id}`);
1365
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2033
+ const data = await api2("DELETE", `/api/todos/${id}`);
2034
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1366
2035
  }
1367
2036
  );
1368
2037
  server2.tool(
1369
2038
  "restore_todo",
1370
- "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.",
2039
+ "Take a todo out of Trash. Sub-tasks stay deleted unless cascade: true. 409 while an ancestor is in Trash; withAncestors: true restores the chain.",
1371
2040
  {
1372
- id: z.number().describe("Todo ID"),
1373
- cascade: z.boolean().optional().describe("Also restore every deleted descendant. Default false."),
1374
- withAncestors: z.boolean().optional().describe("Also restore any ancestor still in Trash. Default false, which makes that case a 409.")
2041
+ id: z2.number().describe("Todo ID"),
2042
+ cascade: z2.boolean().optional().describe("Also restore every deleted descendant. Default false."),
2043
+ withAncestors: z2.boolean().optional().describe("Also restore any ancestor still in Trash. Default false, which makes that case a 409.")
1375
2044
  },
1376
2045
  async ({ id, cascade, withAncestors }) => {
1377
- const data = await api("POST", `/api/todos/${id}/restore`, { cascade, withAncestors });
1378
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2046
+ const data = await api2("POST", `/api/todos/${id}/restore`, { cascade, withAncestors });
2047
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1379
2048
  }
1380
2049
  );
1381
2050
  server2.tool(
1382
2051
  "set_todo_parent",
1383
- "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.",
2052
+ "Move a todo under another (parentId) or to the top level (null). 409 on a cycle or past the depth cap.",
1384
2053
  {
1385
- id: z.number().describe("Todo ID to move"),
1386
- parentId: z.number().nullable().describe("New parent todo ID, or null for top level")
2054
+ id: z2.number().describe("Todo ID to move"),
2055
+ parentId: z2.number().nullable().describe("New parent todo ID, or null for top level")
1387
2056
  },
1388
2057
  async ({ id, parentId }) => {
1389
- const data = await api("POST", `/api/todos/${id}/parent`, { parentId });
1390
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2058
+ const data = await api2("POST", `/api/todos/${id}/parent`, { parentId });
2059
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1391
2060
  }
1392
2061
  );
1393
2062
  server2.tool(
1394
2063
  "reorder_todo",
1395
- "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.",
2064
+ "Place a todo between siblings (beforeId above it, afterId below; null means that end), optionally into another state.",
1396
2065
  {
1397
- id: z.number().describe("Todo ID to move"),
1398
- stateId: z.number().optional().describe("Move into this workflow state as part of the reorder"),
1399
- beforeId: z.number().nullable().optional().describe("The sibling that should end up immediately ABOVE the moved todo"),
1400
- afterId: z.number().nullable().optional().describe("The sibling that should end up immediately BELOW the moved todo")
2066
+ id: z2.number().describe("Todo ID to move"),
2067
+ stateId: z2.number().optional().describe("Move into this workflow state as part of the reorder"),
2068
+ beforeId: z2.number().nullable().optional().describe("The sibling that should end up immediately ABOVE the moved todo"),
2069
+ afterId: z2.number().nullable().optional().describe("The sibling that should end up immediately BELOW the moved todo")
1401
2070
  },
1402
2071
  async ({ id, ...body }) => {
1403
- const data = await api("POST", `/api/todos/${id}/reorder`, body);
1404
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2072
+ const data = await api2("POST", `/api/todos/${id}/reorder`, body);
2073
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1405
2074
  }
1406
2075
  );
1407
2076
  server2.tool(
1408
2077
  "set_todo_tags",
1409
- "Replace a todo's ENTIRE canonical tag set in one call \u2014 whole-set semantics: tags not named are removed, and [] clears them all. IDs come from the org's Todo-scoped canonical tag catalog returned by list_todo_tags; the REST handler writes the shared tag assignment system used by the web app and API. Max 50. Requires the tensor:todos:write scope.",
2078
+ "Replace a todo's whole tag set with these ids from list_todo_tags; [] clears.",
1410
2079
  {
1411
- id: z.number().describe("Todo ID"),
1412
- tagIds: z.array(z.number()).describe("The full desired set of tag IDs")
2080
+ id: z2.number().describe("Todo ID"),
2081
+ tagIds: z2.array(z2.number()).describe("The full desired set of tag IDs")
1413
2082
  },
1414
2083
  async ({ id, tagIds }) => {
1415
- const data = await api("PUT", `/api/todos/${id}/tags`, { tagIds });
1416
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2084
+ const data = await api2("PUT", `/api/todos/${id}/tags`, { tagIds });
2085
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1417
2086
  }
1418
2087
  );
1419
2088
  server2.tool(
1420
2089
  "list_todo_comments",
1421
- "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.",
1422
- { id: z.number().describe("Todo ID") },
2090
+ "A todo's comments. Read bodyText.",
2091
+ { id: z2.number().describe("Todo ID") },
1423
2092
  async ({ id }) => {
1424
- const data = await api("GET", `/api/todos/${id}/comments`);
1425
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2093
+ const data = await api2("GET", `/api/todos/${id}/comments`);
2094
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1426
2095
  }
1427
2096
  );
1428
2097
  server2.tool(
1429
2098
  "create_todo_comment",
1430
- "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.",
2099
+ "Comment on a todo.",
1431
2100
  {
1432
- id: z.number().describe("Todo ID"),
1433
- body: z.string().describe("Comment text (plain text; each line becomes a paragraph)")
2101
+ id: z2.number().describe("Todo ID"),
2102
+ body: z2.string().describe("Comment text (plain text; each line becomes a paragraph)")
1434
2103
  },
1435
2104
  async ({ id, body }) => {
1436
- const data = await api("POST", `/api/todos/${id}/comments`, { bodyJson: tiptapDocJson(body) });
1437
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2105
+ const data = await api2("POST", `/api/todos/${id}/comments`, { bodyJson: tiptapDocJson(body) });
2106
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1438
2107
  }
1439
2108
  );
1440
2109
  server2.tool(
1441
2110
  "update_todo_comment",
1442
- "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.",
2111
+ "Edit a comment you wrote (404 for anyone else's). Comments cannot be deleted.",
1443
2112
  {
1444
- id: z.number().describe("Todo ID"),
1445
- commentId: z.number().describe("Comment ID"),
1446
- body: z.string().describe("Replacement comment text (plain text)")
2113
+ id: z2.number().describe("Todo ID"),
2114
+ commentId: z2.number().describe("Comment ID"),
2115
+ body: z2.string().describe("Replacement comment text (plain text)")
1447
2116
  },
1448
2117
  async ({ id, commentId, body }) => {
1449
- const data = await api("PATCH", `/api/todos/${id}/comments/${commentId}`, { bodyJson: tiptapDocJson(body) });
1450
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2118
+ const data = await api2("PATCH", `/api/todos/${id}/comments/${commentId}`, { bodyJson: tiptapDocJson(body) });
2119
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1451
2120
  }
1452
2121
  );
1453
2122
  server2.tool(
1454
2123
  "list_todo_states",
1455
- "List the org's todo workflow states: key, tag, 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 tag. Requires the tensor:todos:read scope.",
2124
+ "The workflow states with category (backlog, unstarted, started, completed, canceled) and usageCount. Category, not the name, is what behaves.",
1456
2125
  {},
1457
2126
  async () => {
1458
- const data = await api("GET", "/api/todo-states");
1459
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2127
+ const data = await api2("GET", "/api/todo-states");
2128
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1460
2129
  }
1461
2130
  );
1462
2131
  server2.tool(
1463
2132
  "create_todo_state",
1464
- "Create a todo workflow state \u2014 an org-renamable tag pinned to a fixed behavioural category. Requires the tensor:todos:write scope.",
2133
+ "Create a workflow state in one category.",
1465
2134
  {
1466
- key: z.string().describe("Stable key, e.g. 'in_review'"),
1467
- tag: z.string().describe("Display tag, e.g. 'In review'"),
1468
- category: z.enum(TODO_STATE_CATEGORIES).describe("Fixed category. Entering completed/canceled stamps completed_at; leaving clears it."),
1469
- color: z.string().optional().describe("Display color"),
1470
- position: z.number().optional().describe("Sort position among the org's states"),
1471
- notes: z.string().optional()
2135
+ key: z2.string().describe("Stable key, e.g. 'in_review'"),
2136
+ tag: z2.string().describe("Display tag, e.g. 'In review'"),
2137
+ category: z2.enum(TODO_STATE_CATEGORIES).describe("Fixed category. Entering completed/canceled stamps completed_at; leaving clears it."),
2138
+ color: z2.string().optional().describe("Display color"),
2139
+ position: z2.number().optional().describe("Sort position among the org's states"),
2140
+ notes: z2.string().optional()
1472
2141
  },
1473
2142
  async (params) => {
1474
- const data = await api("POST", "/api/todo-states", params);
1475
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2143
+ const data = await api2("POST", "/api/todo-states", params);
2144
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1476
2145
  }
1477
2146
  );
1478
2147
  server2.tool(
1479
2148
  "update_todo_state",
1480
- "Update a workflow state (partial). Renaming key/tag/color/position is free; changing `category` is refused with a 409 while any todo holds the state. Requires the tensor:todos:write scope.",
2149
+ "Edit a workflow state. Its category cannot change while todos hold it (409).",
1481
2150
  {
1482
- id: z.number().describe("State ID"),
1483
- key: z.string().optional(),
1484
- tag: z.string().optional(),
1485
- category: z.enum(TODO_STATE_CATEGORIES).optional().describe("Refused (409) while todos hold this state"),
1486
- color: z.string().nullable().optional(),
1487
- position: z.number().optional(),
1488
- notes: z.string().nullable().optional()
2151
+ id: z2.number().describe("State ID"),
2152
+ key: z2.string().optional(),
2153
+ tag: z2.string().optional(),
2154
+ category: z2.enum(TODO_STATE_CATEGORIES).optional().describe("Refused (409) while todos hold this state"),
2155
+ color: z2.string().nullable().optional(),
2156
+ position: z2.number().optional(),
2157
+ notes: z2.string().nullable().optional()
1489
2158
  },
1490
2159
  async ({ id, ...body }) => {
1491
- const data = await api("PATCH", `/api/todo-states/${id}`, body);
1492
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2160
+ const data = await api2("PATCH", `/api/todo-states/${id}`, body);
2161
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1493
2162
  }
1494
2163
  );
1495
2164
  server2.tool(
1496
2165
  "delete_todo_state",
1497
- "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.",
1498
- { id: z.number().describe("State ID") },
2166
+ "Delete a workflow state. 409 while todos hold it, or for the last one.",
2167
+ { id: z2.number().describe("State ID") },
1499
2168
  async ({ id }) => {
1500
- const data = await api("DELETE", `/api/todo-states/${id}`);
1501
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2169
+ const data = await api2("DELETE", `/api/todo-states/${id}`);
2170
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1502
2171
  }
1503
2172
  );
1504
2173
  server2.tool(
1505
2174
  "list_todo_tags",
1506
- "List the org's Todo-scoped canonical tag catalog with usage counts. These are the same tag records used by Todo reads, filters, the web app and REST API. Requires the tensor:todos:read scope.",
2175
+ "The todo tag catalog with usage counts.",
1507
2176
  {},
1508
2177
  async () => {
1509
- const data = await api("GET", "/api/todo-labels");
1510
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2178
+ const data = await api2("GET", "/api/todo-labels");
2179
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1511
2180
  }
1512
2181
  );
1513
2182
  server2.tool(
1514
2183
  "create_todo_tag",
1515
- "Create a tag in the org's Todo-scoped canonical tag catalog. Names are unique case-insensitively within the Todo surface \u2014 a duplicate is a 409. Requires the tensor:todos:write scope.",
2184
+ "Create a todo tag. A duplicate name is a 409.",
1516
2185
  {
1517
- name: z.string().describe("Tag name, 1-64 chars"),
1518
- color: z.string().optional().describe("Hex color like #6366f1")
2186
+ name: z2.string().describe("Tag name, 1-64 chars"),
2187
+ color: z2.string().optional().describe("Hex color like #6366f1")
1519
2188
  },
1520
2189
  async (params) => {
1521
- const data = await api("POST", "/api/todo-labels", params);
1522
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2190
+ const data = await api2("POST", "/api/todo-labels", params);
2191
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1523
2192
  }
1524
2193
  );
1525
2194
  server2.tool(
1526
2195
  "update_todo_tag",
1527
- "Rename or recolor a canonical Todo tag (partial update; the rename applies everywhere the tag is used). Requires the tensor:todos:write scope.",
2196
+ "Rename or recolour a todo tag everywhere it is used.",
1528
2197
  {
1529
- id: z.number().describe("Tag ID"),
1530
- name: z.string().optional(),
1531
- color: z.string().nullable().optional()
2198
+ id: z2.number().describe("Tag ID"),
2199
+ name: z2.string().optional(),
2200
+ color: z2.string().nullable().optional()
1532
2201
  },
1533
2202
  async ({ id, ...body }) => {
1534
- const data = await api("PATCH", `/api/todo-labels/${id}`, body);
1535
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2203
+ const data = await api2("PATCH", `/api/todo-labels/${id}`, body);
2204
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1536
2205
  }
1537
2206
  );
1538
2207
  server2.tool(
1539
2208
  "delete_todo_tag",
1540
- "Delete a canonical Todo tag. It is removed from every todo that carries it. Requires the tensor:todos:write scope.",
1541
- { id: z.number().describe("Tag ID") },
1542
- async ({ id }) => {
1543
- const data = await api("DELETE", `/api/todo-labels/${id}`);
1544
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
1545
- }
2209
+ "Delete a todo tag from every todo carrying it. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
2210
+ { id: z2.number().describe("Tag ID"), confirmToken: CONFIRM_TOKEN_INPUT },
2211
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/todo-labels/${id}`, void 0, { confirmToken }))
1546
2212
  );
1547
2213
  server2.tool(
1548
2214
  "list_todo_files",
1549
- "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.",
1550
- { id: z.number().describe("Todo ID") },
2215
+ "Files attached to a todo, with the linkId detach_todo_file takes. Also needs tensor:files:read.",
2216
+ { id: z2.number().describe("Todo ID") },
1551
2217
  async ({ id }) => {
1552
- const data = await api("GET", `/api/todos/${id}/files`);
1553
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2218
+ const data = await api2("GET", `/api/todos/${id}/files`);
2219
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1554
2220
  }
1555
2221
  );
1556
2222
  server2.tool(
1557
2223
  "attach_todo_file",
1558
- "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.",
2224
+ "Attach an existing file to a todo (upload first with create_file_upload_url). Also needs tensor:files:read. At most 200.",
1559
2225
  {
1560
- id: z.number().describe("Todo ID"),
1561
- fileId: z.number().describe("ID of an existing file")
2226
+ id: z2.number().describe("Todo ID"),
2227
+ fileId: z2.number().describe("ID of an existing file")
1562
2228
  },
1563
2229
  async ({ id, fileId }) => {
1564
- const data = await api("POST", `/api/todos/${id}/files`, { fileId });
1565
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2230
+ const data = await api2("POST", `/api/todos/${id}/files`, { fileId });
2231
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1566
2232
  }
1567
2233
  );
1568
2234
  server2.tool(
1569
2235
  "detach_todo_file",
1570
- "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.",
2236
+ "Detach a file from a todo; the file stays. Also needs tensor:files:read.",
1571
2237
  {
1572
- id: z.number().describe("Todo ID"),
1573
- linkId: z.number().describe("The linkId from list_todo_files \u2014 not the file id")
2238
+ id: z2.number().describe("Todo ID"),
2239
+ linkId: z2.number().describe("The linkId from list_todo_files \u2014 not the file id")
1574
2240
  },
1575
2241
  async ({ id, linkId }) => {
1576
- const data = await api("DELETE", `/api/todos/${id}/files/${linkId}`);
1577
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2242
+ const data = await api2("DELETE", `/api/todos/${id}/files/${linkId}`);
2243
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1578
2244
  }
1579
2245
  );
1580
2246
  server2.tool(
1581
2247
  "list_todo_links",
1582
- `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.`,
1583
- { id: z.number().describe("Todo ID") },
2248
+ "Records a todo is linked to. Each row's id is the linkId detach_todo_link takes. Attached files are list_todo_files.",
2249
+ { id: z2.number().describe("Todo ID") },
1584
2250
  async ({ id }) => {
1585
- const data = await api("GET", `/api/todos/${id}/links`);
1586
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2251
+ const data = await api2("GET", `/api/todos/${id}/links`);
2252
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1587
2253
  }
1588
2254
  );
1589
2255
  server2.tool(
1590
2256
  "attach_todo_link",
1591
- "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.",
2257
+ "Link a todo to a record (ledger record, todo, idea). Files go through attach_todo_file.",
1592
2258
  {
1593
- id: z.number().describe("Todo ID"),
1594
- targetType: z.enum(TODO_LINK_TARGET_TYPES).describe("Record kind to link to. Not 'file' \u2014 see attach_todo_file."),
1595
- targetId: z.number().describe("The record's ID")
2259
+ id: z2.number().describe("Todo ID"),
2260
+ targetType: z2.enum(TODO_LINK_TARGET_TYPES).describe("Record kind to link to. Not 'file' \u2014 see attach_todo_file."),
2261
+ targetId: z2.number().describe("The record's ID")
1596
2262
  },
1597
2263
  async ({ id, ...body }) => {
1598
- const data = await api("POST", `/api/todos/${id}/links`, body);
1599
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2264
+ const data = await api2("POST", `/api/todos/${id}/links`, body);
2265
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1600
2266
  }
1601
2267
  );
1602
2268
  server2.tool(
1603
2269
  "detach_todo_link",
1604
- "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.",
2270
+ "Remove a todo's link by linkId; both records stay.",
1605
2271
  {
1606
- id: z.number().describe("Todo ID"),
1607
- linkId: z.number().describe("The link's id from list_todo_links \u2014 not the target record's id")
2272
+ id: z2.number().describe("Todo ID"),
2273
+ linkId: z2.number().describe("The link's id from list_todo_links \u2014 not the target record's id")
1608
2274
  },
1609
2275
  async ({ id, linkId }) => {
1610
- const data = await api("DELETE", `/api/todos/${id}/links/${linkId}`);
1611
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2276
+ const data = await api2("DELETE", `/api/todos/${id}/links/${linkId}`);
2277
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1612
2278
  }
1613
2279
  );
1614
2280
  server2.tool(
1615
2281
  "list_ideas",
1616
- "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.",
1617
- {
1618
- limit: z.number().optional().describe("Max results. Default 500."),
1619
- offset: z.number().optional().describe("Pagination offset"),
1620
- kind: z.enum(IDEA_KINDS).optional().describe("Card shape: link, note, image or video"),
1621
- tag: z.string().optional().describe("Only ideas carrying this tag (matching is lowercase-normalized; see list_idea_tags)"),
1622
- site: z.string().optional().describe("Only ideas captured from this site \u2014 a bare host like 'youtube.com' (see list_idea_sites)"),
1623
- q: z.string().optional().describe("Case-insensitive substring over title, body, url and site name"),
1624
- 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."),
1625
- targetId: z.number().optional().describe("The record id targetType points at. Send both or neither."),
1626
- trash: z.boolean().optional().describe("true = the Trash instead of the live stream"),
2282
+ "List ideas, newest first unless sort says otherwise. Default: the active stream; `archived: true` lists the archived (still readable and searchable), `trash: true` the Trash.",
2283
+ {
2284
+ limit: LIMIT_INPUT,
2285
+ offset: OFFSET_INPUT,
2286
+ kind: z2.enum(IDEA_KINDS).optional().describe("Card shape: link, note, image or video"),
2287
+ tag: z2.string().optional().describe("Only ideas carrying this tag (matching is lowercase-normalized; see list_idea_tags)"),
2288
+ site: z2.string().optional().describe("Only ideas captured from this site \u2014 a bare host like 'youtube.com' (see list_idea_sites)"),
2289
+ q: z2.string().optional().describe("Case-insensitive substring over title, body, url and site name"),
2290
+ targetType: z2.enum(IDEA_LINK_TARGET_TYPES).optional().describe("With targetId: ideas linked to this record (not 'file')."),
2291
+ targetId: z2.number().optional().describe("The record id targetType points at. Send both or neither."),
2292
+ archived: z2.boolean().optional().describe("true = the archived ideas. Ignored with trash."),
2293
+ trash: z2.boolean().optional().describe("true = the Trash instead of the live stream"),
1627
2294
  // ORDERING, and it is the ONE thing the web stream could ask for and this
1628
2295
  // tool could not. The server has parsed it since the arrangement work
1629
2296
  // (`parseIdeaFilters`, server/http/list-options.ts) and the page has used
1630
2297
  // it the whole time; the gap was here, and it is the shape `list_todos`
1631
2298
  // already had one noun over. Optional, so every existing caller is
1632
2299
  // unaffected — which is what makes it a MINOR bump rather than a major.
1633
- 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.")
2300
+ sort: z2.enum(IDEA_SORT_MODES).optional().describe("newest (default), oldest, updated or title.")
1634
2301
  },
1635
- async ({ limit, offset, kind, tag, site, q, targetType, targetId, trash, sort }) => {
2302
+ async ({ limit, offset, kind, tag, site, q, targetType, targetId, archived, trash, sort }) => {
1636
2303
  const params = new URLSearchParams();
1637
- if (limit) params.set("limit", String(limit));
1638
- if (offset) params.set("offset", String(offset));
1639
2304
  if (kind) params.set("kind", kind);
1640
2305
  if (tag) params.set("tag", tag);
1641
2306
  if (site) params.set("site", site);
1642
2307
  if (q) params.set("q", q);
1643
2308
  if (targetType) params.set("targetType", targetType);
1644
2309
  if (targetId != null) params.set("targetId", String(targetId));
2310
+ if (archived) params.set("archived", "1");
1645
2311
  if (trash) params.set("trash", "1");
1646
2312
  if (sort) params.set("sort", sort);
1647
- const qs = params.toString();
1648
- const data = await api("GET", `/api/ideas${qs ? `?${qs}` : ""}`);
1649
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2313
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/ideas?${qs}`));
1650
2314
  }
1651
2315
  );
1652
2316
  server2.tool(
1653
2317
  "get_idea",
1654
- "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.",
1655
- { id: z.number().describe("Idea ID") },
2318
+ "One idea with tags and media. Read `body` (plain text). Each media id is what get_idea_media_url takes.",
2319
+ { id: z2.number().describe("Idea ID") },
1656
2320
  async ({ id }) => {
1657
- const data = await api("GET", `/api/ideas/${id}`);
1658
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2321
+ const data = await api2("GET", `/api/ideas/${id}`);
2322
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1659
2323
  }
1660
2324
  );
1661
2325
  server2.tool(
1662
2326
  "create_idea",
1663
- "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.",
1664
- {
1665
- kind: z.enum(IDEA_KINDS).describe("Card-shape hint: link, note, image or video"),
1666
- title: z.string().optional().describe("Title (max 1024 chars)"),
1667
- url: z.string().optional().describe("The captured link, if any"),
1668
- 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)."),
1669
- tags: z.array(z.string()).optional().describe("Tag names resolved into Idea-scoped canonical tag records; the resulting canonical assignments are written in the same transaction"),
1670
- siteName: z.string().optional().describe("Site display name (og:site_name)"),
1671
- excerpt: z.string().optional().describe("Page excerpt (og:description)"),
1672
- thumbnailUrl: z.string().optional().describe("Remote preview-image URL \u2014 kept remote, never mirrored into storage"),
1673
- media: z.array(z.object({
1674
- storageKey: z.string().describe("The storageKey echoed by create_idea_upload_url, after the bytes were PUT to its url"),
1675
- filename: z.string().nullable().optional().describe("Original filename, for display"),
1676
- checksumSha256: z.string().nullable().optional().describe("SHA-256 of the plaintext bytes"),
1677
- mimeType: z.string().optional().describe("Required for an encrypted (TDE1) upload, where the stored object is opaque; ignored for plaintext"),
1678
- 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."),
1679
- chunkSize: z.number().optional().describe("TDE1 frame size used. Required when envelopeVersion is 1."),
1680
- 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.")
2327
+ "Capture an idea: at least one of url, body or media. Text only: an image URL typed in body stays text; add pictures as media (create_idea_upload_url). A URL saved before still creates the idea, with `duplicateOf` naming the earlier one.",
2328
+ {
2329
+ kind: z2.enum(IDEA_KINDS).describe("Card-shape hint: link, note, image or video"),
2330
+ title: z2.string().optional().describe("Title (max 1024 chars)"),
2331
+ url: z2.string().optional().describe("The captured link, if any"),
2332
+ body: z2.string().optional().describe("Plain text, one paragraph per line. Max 256000."),
2333
+ tags: z2.array(z2.string()).optional().describe("Tag names."),
2334
+ siteName: z2.string().optional().describe("Site display name (og:site_name)"),
2335
+ excerpt: z2.string().optional().describe("Page excerpt (og:description)"),
2336
+ thumbnailUrl: z2.string().optional().describe("Remote preview-image URL \u2014 kept remote, never mirrored into storage"),
2337
+ media: z2.array(z2.object({
2338
+ storageKey: z2.string().describe("The storageKey echoed by create_idea_upload_url, after the bytes were PUT to its url"),
2339
+ filename: z2.string().nullable().optional().describe("Original filename, for display"),
2340
+ checksumSha256: z2.string().nullable().optional().describe("SHA-256 of the plaintext bytes"),
2341
+ mimeType: z2.string().optional().describe("Required for an encrypted (TDE1) upload, where the stored object is opaque; ignored for plaintext"),
2342
+ envelopeVersion: z2.union([z2.literal(0), z2.literal(1)]).optional().describe("The terms the bytes were uploaded under: 1 = TDE1 envelope. Must match what the presign dictated."),
2343
+ chunkSize: z2.number().optional().describe("TDE1 frame size used. Required when envelopeVersion is 1."),
2344
+ dek: z2.string().optional().describe("Base64 AES-256 key of the envelope. Required when envelopeVersion is 1; stored wrapped.")
1681
2345
  })).optional().describe("Uploads to confirm into the gallery \u2014 see create_idea_upload_url for the flow")
1682
2346
  },
1683
2347
  async (params) => {
1684
- const data = await api("POST", "/api/ideas", params);
1685
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2348
+ const data = await api2("POST", "/api/ideas", params);
2349
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1686
2350
  }
1687
2351
  );
1688
2352
  server2.tool(
1689
2353
  "update_idea",
1690
- "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.",
1691
- {
1692
- id: z.number().describe("Idea ID"),
1693
- kind: z.enum(IDEA_KINDS).optional(),
1694
- title: z.string().nullable().optional(),
1695
- url: z.string().nullable().optional(),
1696
- body: z.string().nullable().optional().describe("Plain text; REPLACES the whole body document (inline images included). null clears it. Max 256000 chars."),
1697
- tags: z.array(z.string()).optional().describe("REPLACES the whole Idea tag set by resolving names into Idea-scoped canonical tag records and writing canonical assignments transactionally"),
1698
- siteName: z.string().nullable().optional(),
1699
- excerpt: z.string().nullable().optional(),
1700
- thumbnailUrl: z.string().nullable().optional(),
1701
- media: z.array(z.object({
1702
- storageKey: z.string().describe("The storageKey echoed by create_idea_upload_url, after the bytes were PUT to its url"),
1703
- filename: z.string().nullable().optional(),
1704
- checksumSha256: z.string().nullable().optional(),
1705
- mimeType: z.string().optional().describe("Required for an encrypted (TDE1) upload"),
1706
- envelopeVersion: z.union([z.literal(0), z.literal(1)]).optional(),
1707
- chunkSize: z.number().optional().describe("Required when envelopeVersion is 1"),
1708
- dek: z.string().optional().describe("Required when envelopeVersion is 1")
2354
+ "Edit an idea. `tags` replaces the tag set; `media` appends. Sending body replaces the whole body document, inline images included (they stay in the gallery): read the idea first if you did not write it.",
2355
+ {
2356
+ id: z2.number().describe("Idea ID"),
2357
+ kind: z2.enum(IDEA_KINDS).optional(),
2358
+ title: z2.string().nullable().optional(),
2359
+ url: z2.string().nullable().optional(),
2360
+ body: z2.string().nullable().optional().describe("Plain text; REPLACES the whole body document (inline images included). null clears it. Max 256000 chars."),
2361
+ tags: z2.array(z2.string()).optional().describe("Tag names; REPLACES the tag set."),
2362
+ siteName: z2.string().nullable().optional(),
2363
+ excerpt: z2.string().nullable().optional(),
2364
+ thumbnailUrl: z2.string().nullable().optional(),
2365
+ media: z2.array(z2.object({
2366
+ storageKey: z2.string().describe("The storageKey echoed by create_idea_upload_url, after the bytes were PUT to its url"),
2367
+ filename: z2.string().nullable().optional(),
2368
+ checksumSha256: z2.string().nullable().optional(),
2369
+ mimeType: z2.string().optional().describe("Required for an encrypted (TDE1) upload"),
2370
+ envelopeVersion: z2.union([z2.literal(0), z2.literal(1)]).optional(),
2371
+ chunkSize: z2.number().optional().describe("Required when envelopeVersion is 1"),
2372
+ dek: z2.string().optional().describe("Required when envelopeVersion is 1")
1709
2373
  })).optional().describe("Uploads to APPEND to the gallery")
1710
2374
  },
1711
2375
  async ({ id, ...body }) => {
1712
- const data = await api("PATCH", `/api/ideas/${id}`, body);
1713
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2376
+ const data = await api2("PATCH", `/api/ideas/${id}`, body);
2377
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1714
2378
  }
1715
2379
  );
1716
2380
  server2.tool(
1717
2381
  "delete_idea",
1718
- "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.",
1719
- { id: z.number().describe("Idea ID") },
2382
+ "Move an idea to Trash. For one the user is done with but wants kept, use archive_idea.",
2383
+ { id: z2.number().describe("Idea ID") },
1720
2384
  async ({ id }) => {
1721
- const data = await api("DELETE", `/api/ideas/${id}`);
1722
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2385
+ const data = await api2("DELETE", `/api/ideas/${id}`);
2386
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1723
2387
  }
1724
2388
  );
1725
2389
  server2.tool(
1726
2390
  "restore_idea",
1727
- "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.",
1728
- { id: z.number().describe("Idea ID") },
2391
+ "Take an idea out of Trash, on the side it left from (active or archived).",
2392
+ { id: z2.number().describe("Idea ID") },
2393
+ async ({ id }) => {
2394
+ const data = await api2("POST", `/api/ideas/${id}/restore`);
2395
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2396
+ }
2397
+ );
2398
+ server2.tool(
2399
+ "archive_idea",
2400
+ "Archive an idea: done with, kept on file, never expires, still readable and searchable. Not a delete. Undo with unarchive_idea. 409 for an idea in Trash.",
2401
+ { id: z2.number().describe("Idea ID") },
2402
+ async ({ id }) => {
2403
+ const data = await api2("POST", `/api/ideas/${id}/archive`);
2404
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2405
+ }
2406
+ );
2407
+ server2.tool(
2408
+ "unarchive_idea",
2409
+ "Return an archived idea to the active stream. 409 for an idea in Trash.",
2410
+ { id: z2.number().describe("Idea ID") },
1729
2411
  async ({ id }) => {
1730
- const data = await api("POST", `/api/ideas/${id}/restore`);
1731
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2412
+ const data = await api2("POST", `/api/ideas/${id}/unarchive`);
2413
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1732
2414
  }
1733
2415
  );
1734
2416
  server2.tool(
1735
2417
  "list_idea_comments",
1736
- "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.",
1737
- { id: z.number().describe("Idea ID") },
2418
+ "An idea's comments. Read bodyText.",
2419
+ { id: z2.number().describe("Idea ID") },
1738
2420
  async ({ id }) => {
1739
- const data = await api("GET", `/api/ideas/${id}/comments`);
1740
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2421
+ const data = await api2("GET", `/api/ideas/${id}/comments`);
2422
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1741
2423
  }
1742
2424
  );
1743
2425
  server2.tool(
1744
2426
  "create_idea_comment",
1745
- "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.",
2427
+ "Comment on an idea.",
1746
2428
  {
1747
- id: z.number().describe("Idea ID"),
1748
- body: z.string().describe("Comment text (plain text; each line becomes a paragraph)")
2429
+ id: z2.number().describe("Idea ID"),
2430
+ body: z2.string().describe("Comment text (plain text; each line becomes a paragraph)")
1749
2431
  },
1750
2432
  async ({ id, body }) => {
1751
- const data = await api("POST", `/api/ideas/${id}/comments`, { bodyJson: tiptapDocJson(body) });
1752
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2433
+ const data = await api2("POST", `/api/ideas/${id}/comments`, { bodyJson: tiptapDocJson(body) });
2434
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1753
2435
  }
1754
2436
  );
1755
2437
  server2.tool(
1756
2438
  "update_idea_comment",
1757
- "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.",
2439
+ "Edit a comment you wrote (404 for anyone else's). Comments cannot be deleted.",
1758
2440
  {
1759
- id: z.number().describe("Idea ID"),
1760
- commentId: z.number().describe("Comment ID"),
1761
- body: z.string().describe("Replacement comment text (plain text)")
2441
+ id: z2.number().describe("Idea ID"),
2442
+ commentId: z2.number().describe("Comment ID"),
2443
+ body: z2.string().describe("Replacement comment text (plain text)")
1762
2444
  },
1763
2445
  async ({ id, commentId, body }) => {
1764
- const data = await api("PATCH", `/api/ideas/${id}/comments/${commentId}`, { bodyJson: tiptapDocJson(body) });
1765
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2446
+ const data = await api2("PATCH", `/api/ideas/${id}/comments/${commentId}`, { bodyJson: tiptapDocJson(body) });
2447
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1766
2448
  }
1767
2449
  );
1768
2450
  server2.tool(
1769
2451
  "list_idea_tags",
1770
- "Every Idea-scoped canonical tag in use across live ideas, with counts \u2014 the stream's tag rail. These are the same tag records used by Ideas reads, filters, the web app and REST API. Feed a row's tag into list_ideas' `tag` filter. Requires the tensor:ideas:read scope.",
1771
- {},
1772
- async () => {
1773
- const data = await api("GET", "/api/ideas/tags");
1774
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2452
+ "Tags in use across the active ideas (or `archived: true`), with counts, for list_ideas' tag filter.",
2453
+ {
2454
+ archived: z2.boolean().optional().describe("true = count the archived ideas instead of the active stream")
2455
+ },
2456
+ async ({ archived }) => {
2457
+ const data = await api2("GET", `/api/ideas/tags${archived ? "?archived=1" : ""}`);
2458
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1775
2459
  }
1776
2460
  );
1777
2461
  server2.tool(
1778
2462
  "list_idea_sites",
1779
- "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.",
1780
- {},
1781
- async () => {
1782
- const data = await api("GET", "/api/ideas/sites");
1783
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2463
+ "Source sites across the active ideas (or `archived: true`), with counts, for list_ideas' site filter.",
2464
+ {
2465
+ archived: z2.boolean().optional().describe("true = count the archived ideas instead of the active stream")
2466
+ },
2467
+ async ({ archived }) => {
2468
+ const data = await api2("GET", `/api/ideas/sites${archived ? "?archived=1" : ""}`);
2469
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2470
+ }
2471
+ );
2472
+ server2.tool(
2473
+ "list_idea_kinds",
2474
+ "Kinds across the active ideas (or `archived: true`), with counts (link, note, image, video).",
2475
+ {
2476
+ archived: z2.boolean().optional().describe("true = count the archived ideas instead of the active stream")
2477
+ },
2478
+ async ({ archived }) => {
2479
+ const data = await api2("GET", `/api/ideas/kinds${archived ? "?archived=1" : ""}`);
2480
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1784
2481
  }
1785
2482
  );
1786
2483
  server2.tool(
1787
2484
  "get_idea_media_url",
1788
- "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.",
2485
+ "Mint a short-lived URL for one gallery item. For encrypted media it points at ciphertext and also returns the `dek`, a permanent, logged key release. Also needs tensor:files:read.",
1789
2486
  {
1790
- id: z.number().describe("Idea ID"),
1791
- mediaId: z.number().describe("Media entry id from get_idea (an idea's media IS a file row; this is that row's id)")
2487
+ id: z2.number().describe("Idea ID"),
2488
+ mediaId: z2.number().describe("Media entry id from get_idea (an idea's media IS a file row; this is that row's id)")
1792
2489
  },
1793
2490
  async ({ id, mediaId }) => {
1794
- const data = await api("GET", `/api/ideas/${id}/media/${mediaId}/url`);
1795
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2491
+ const data = await api2("GET", `/api/ideas/${id}/media/${mediaId}/url`);
2492
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1796
2493
  }
1797
2494
  );
1798
2495
  server2.tool(
1799
2496
  "create_idea_upload_url",
1800
- "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.",
2497
+ "Media upload step 1: mint a PUT URL and storageKey; PUT the bytes, then confirm by passing {storageKey, ...} in create_idea or update_idea `media`. If the answer says envelopeVersion 1, the body must be a TDE1 envelope.",
1801
2498
  {
1802
- filename: z.string().describe("Original filename. Display data only."),
1803
- mimeType: z.string().describe("The file's MIME type. Must be on Tensor's upload allow-list."),
1804
- sizeBytes: z.number().describe("PLAINTEXT byte size of the file"),
1805
- 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."),
1806
- chunkSize: z.number().optional().describe("Requested TDE1 frame size. Omit for the default; upload under whatever the response echoes.")
2499
+ filename: z2.string().describe("Original filename. Display data only."),
2500
+ mimeType: z2.string().describe("The file's MIME type. Must be on Tensor's upload allow-list."),
2501
+ sizeBytes: z2.number().describe("PLAINTEXT byte size of the file"),
2502
+ envelopeVersion: z2.union([z2.literal(0), z2.literal(1)]).optional().describe("Capability announcement: 1 = this client can build a TDE1 envelope. The server decides and echoes the terms."),
2503
+ chunkSize: z2.number().optional().describe("Requested TDE1 frame size. Omit for the default; upload under whatever the response echoes.")
1807
2504
  },
1808
2505
  async (params) => {
1809
- const data = await api("POST", "/api/ideas/upload-url", params);
1810
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2506
+ const data = await api2("POST", "/api/ideas/upload-url", params);
2507
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1811
2508
  }
1812
2509
  );
1813
2510
  server2.tool(
1814
2511
  "list_idea_links",
1815
- "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.",
1816
- { id: z.number().describe("Idea ID") },
2512
+ "Records an idea is linked to (not its gallery, which is get_idea's media). Each row's id is the linkId detach_idea_link takes; `kind` 'mention' rows come from prose and cannot be detached.",
2513
+ { id: z2.number().describe("Idea ID") },
1817
2514
  async ({ id }) => {
1818
- const data = await api("GET", `/api/ideas/${id}/links`);
1819
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2515
+ const data = await api2("GET", `/api/ideas/${id}/links`);
2516
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1820
2517
  }
1821
2518
  );
1822
2519
  server2.tool(
1823
2520
  "attach_idea_link",
1824
- "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`.",
2521
+ "Link an idea to a record (ledger record, todo, idea). Files are its gallery: media on create_idea / update_idea.",
1825
2522
  {
1826
- id: z.number().describe("Idea ID"),
1827
- targetType: z.enum(IDEA_LINK_TARGET_TYPES).describe("Record kind to link to. Not 'file' \u2014 an idea's files are its gallery."),
1828
- targetId: z.number().describe("The record's ID")
2523
+ id: z2.number().describe("Idea ID"),
2524
+ targetType: z2.enum(IDEA_LINK_TARGET_TYPES).describe("Record kind to link to. Not 'file' \u2014 an idea's files are its gallery."),
2525
+ targetId: z2.number().describe("The record's ID")
1829
2526
  },
1830
2527
  async ({ id, ...body }) => {
1831
- const data = await api("POST", `/api/ideas/${id}/links`, body);
1832
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2528
+ const data = await api2("POST", `/api/ideas/${id}/links`, body);
2529
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1833
2530
  }
1834
2531
  );
1835
2532
  server2.tool(
1836
2533
  "detach_idea_link",
1837
- "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.",
2534
+ "Remove an idea's 'related' link by linkId. A gallery item or a 'mention' (it comes from prose: edit the text instead) is a 409.",
1838
2535
  {
1839
- id: z.number().describe("Idea ID"),
1840
- linkId: z.number().describe("The link's id from list_idea_links \u2014 not the target record's id")
2536
+ id: z2.number().describe("Idea ID"),
2537
+ linkId: z2.number().describe("The link's id from list_idea_links \u2014 not the target record's id")
1841
2538
  },
1842
2539
  async ({ id, linkId }) => {
1843
- const data = await api("DELETE", `/api/ideas/${id}/links/${linkId}`);
1844
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2540
+ const data = await api2("DELETE", `/api/ideas/${id}/links/${linkId}`);
2541
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1845
2542
  }
1846
2543
  );
1847
2544
  server2.tool(
1848
2545
  "list_bookmarks",
1849
- "List filed bookmarks in the order the owner arranged them: Unfiled first, then folder by folder in the order list_bookmark_folders answers, each folder's bookmarks in their own hand-set order (a new bookmark goes first in its folder). Keep that order \u2014 do not re-sort by date or title. The Trash (trash: true) reads newest first instead. `folderId` is THREE-VALUED and the third value is the one that is easy to lose: a positive integer asks for one folder, the string 'none' asks for the UNFILED (folderId is null \u2014 a resting state, not an error), and omitting it asks for everything. Sending 'none' as absent turns an Unfiled view into the whole library. The response is FLAT \u2014 no folder is hydrated into a row \u2014 so read the tree with list_bookmark_folders and join on each row's folderId. Requires the tensor:bookmarks:read scope.",
2546
+ "List filed bookmarks in the order the owner arranged them: Unfiled first, then folder by folder as list_bookmark_folders orders them. Keep that order rather than sorting by name or date. The Trash (trash: true) is newest first. Rows are flat; join folderId to list_bookmark_folders.",
1850
2547
  {
1851
- limit: z.number().optional().describe("Max results. Default 500."),
1852
- offset: z.number().optional().describe("Pagination offset"),
1853
- folderId: z.union([z.number(), z.literal("none")]).optional().describe("One folder by id, or 'none' for the unfiled. Omit for every bookmark."),
1854
- q: z.string().optional().describe("Case-insensitive substring over title, url and site name"),
1855
- trash: z.boolean().optional().describe("true = the Trash instead of the live library")
2548
+ limit: LIMIT_INPUT,
2549
+ offset: OFFSET_INPUT,
2550
+ folderId: z2.union([z2.number(), z2.literal("none")]).optional().describe("One folder by id, or 'none' for the unfiled. Omit for every bookmark."),
2551
+ q: z2.string().optional().describe("Case-insensitive substring over title, url and site name"),
2552
+ trash: z2.boolean().optional().describe("true = the Trash instead of the live library")
1856
2553
  },
1857
2554
  async ({ limit, offset, folderId, q, trash }) => {
1858
2555
  const params = new URLSearchParams();
1859
- if (limit) params.set("limit", String(limit));
1860
- if (offset) params.set("offset", String(offset));
1861
2556
  if (folderId !== void 0) params.set("folderId", String(folderId));
1862
2557
  if (q) params.set("q", q);
1863
2558
  if (trash) params.set("trash", "1");
1864
- const qs = params.toString();
1865
- const data = await api("GET", `/api/bookmarks${qs ? `?${qs}` : ""}`);
1866
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2559
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/bookmarks?${qs}`));
1867
2560
  }
1868
2561
  );
1869
2562
  server2.tool(
1870
2563
  "get_bookmark",
1871
- "Get one bookmark. `normalizedUrl` beside the raw url is what duplicate detection compares \u2014 it is derived server-side and cannot be written. Requires the tensor:bookmarks:read scope.",
1872
- { id: z.number().describe("Bookmark ID") },
2564
+ "One bookmark. normalizedUrl is what duplicate detection compares.",
2565
+ { id: z2.number().describe("Bookmark ID") },
1873
2566
  async ({ id }) => {
1874
- const data = await api("GET", `/api/bookmarks/${id}`);
1875
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2567
+ const data = await api2("GET", `/api/bookmarks/${id}`);
2568
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1876
2569
  }
1877
2570
  );
1878
2571
  server2.tool(
1879
2572
  "create_bookmark",
1880
- "File a bookmark. Only `url` is required; leaving `folderId` off files it as UNFILED, which is a resting state rather than an incomplete one \u2014 do not invent a folder to put it in. A DUPLICATE IS FLAGGED, NOT REFUSED: if the same page was saved before, the row is still created and the response carries `duplicateOf` naming the earlier one, so you can offer to open that instead. Requires the tensor:bookmarks:write scope.",
2573
+ "File a bookmark. Without folderId it is Unfiled, a normal state: do not invent a folder. A page saved before is still created, with `duplicateOf` naming the earlier one.",
1881
2574
  {
1882
- url: z.string().describe("The page URL (max 2048 chars)"),
1883
- title: z.string().optional().describe("Title (max 1024 chars)"),
1884
- folderId: z.number().optional().describe("File it into this folder. Omit for unfiled."),
1885
- excerpt: z.string().optional().describe("Page excerpt (og:description), max 4096"),
1886
- siteName: z.string().optional().describe("Site display name (og:site_name)"),
1887
- faviconUrl: z.string().optional().describe("Favicon URL \u2014 kept remote, never mirrored into storage"),
1888
- thumbnailUrl: z.string().optional().describe("Preview image URL \u2014 kept remote")
2575
+ url: z2.string().describe("The page URL (max 2048 chars)"),
2576
+ title: z2.string().optional().describe("Title (max 1024 chars)"),
2577
+ folderId: z2.number().optional().describe("File it into this folder. Omit for unfiled."),
2578
+ excerpt: z2.string().optional().describe("Page excerpt (og:description), max 4096"),
2579
+ siteName: z2.string().optional().describe("Site display name (og:site_name)"),
2580
+ faviconUrl: z2.string().optional().describe("Favicon URL \u2014 kept remote, never mirrored into storage"),
2581
+ thumbnailUrl: z2.string().optional().describe("Preview image URL \u2014 kept remote")
1889
2582
  },
1890
2583
  async (params) => {
1891
- const data = await api("POST", "/api/bookmarks", params);
1892
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2584
+ const data = await api2("POST", "/api/bookmarks", params);
2585
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1893
2586
  }
1894
2587
  );
1895
2588
  server2.tool(
1896
2589
  "update_bookmark",
1897
- "Edit a bookmark. Every field is optional and only what you send changes. Pass folderId as null to UNFILE it \u2014 omitting the field leaves it where it is. Requires the tensor:bookmarks:write scope.",
2590
+ "Edit a bookmark. folderId null unfiles it; omitted leaves it.",
2591
+ {
2592
+ id: z2.number().describe("Bookmark ID"),
2593
+ url: z2.string().optional().describe("Replacement URL"),
2594
+ title: z2.string().nullable().optional().describe("Replacement title"),
2595
+ folderId: z2.number().nullable().optional().describe("Move to this folder, or null to unfile"),
2596
+ excerpt: z2.string().nullable().optional().describe("Replacement excerpt"),
2597
+ siteName: z2.string().nullable().optional().describe("Replacement site name"),
2598
+ faviconUrl: z2.string().nullable().optional().describe("Replacement favicon URL"),
2599
+ thumbnailUrl: z2.string().nullable().optional().describe("Replacement preview image URL")
2600
+ },
2601
+ async ({ id, ...body }) => {
2602
+ const data = await api2("PATCH", `/api/bookmarks/${id}`, body);
2603
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2604
+ }
2605
+ );
2606
+ server2.tool(
2607
+ "move_bookmark",
2608
+ "Move a bookmark to another folder and/or a place in the order (beforeId or afterId; neither puts it last).",
1898
2609
  {
1899
- id: z.number().describe("Bookmark ID"),
1900
- url: z.string().optional().describe("Replacement URL"),
1901
- title: z.string().nullable().optional().describe("Replacement title"),
1902
- folderId: z.number().nullable().optional().describe("Move to this folder, or null to unfile"),
1903
- excerpt: z.string().nullable().optional().describe("Replacement excerpt"),
1904
- siteName: z.string().nullable().optional().describe("Replacement site name"),
1905
- faviconUrl: z.string().nullable().optional().describe("Replacement favicon URL"),
1906
- thumbnailUrl: z.string().nullable().optional().describe("Replacement preview image URL")
2610
+ id: z2.number().describe("Bookmark ID"),
2611
+ folderId: z2.number().nullable().optional().describe("Destination folder; null = unfiled. Omit to stay in the current folder."),
2612
+ beforeId: z2.number().nullable().optional().describe("The row that will sit directly ABOVE it, in the destination"),
2613
+ afterId: z2.number().nullable().optional().describe("The row that will sit directly BELOW it, in the destination")
1907
2614
  },
1908
2615
  async ({ id, ...body }) => {
1909
- const data = await api("PATCH", `/api/bookmarks/${id}`, body);
1910
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2616
+ const data = await api2("POST", `/api/bookmarks/${id}/move`, body);
2617
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1911
2618
  }
1912
2619
  );
1913
2620
  server2.tool(
1914
2621
  "delete_bookmark",
1915
- "Move a bookmark to the Trash (soft delete). Restorable with restore_bookmark, and it goes back to the folder it was filed in. The Trash empties itself sixty days after deletion; the permanent purge is deliberately not reachable with an API key, so a key cannot unrecoverably delete a bookmark. Returns the trashed row rather than an ok flag, so you can read the deletedAt it just earned. Requires the tensor:bookmarks:write scope.",
1916
- { id: z.number().describe("Bookmark ID") },
2622
+ "Move a bookmark to Trash; restore puts it back in its folder.",
2623
+ { id: z2.number().describe("Bookmark ID") },
1917
2624
  async ({ id }) => {
1918
- const data = await api("DELETE", `/api/bookmarks/${id}`);
1919
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2625
+ const data = await api2("DELETE", `/api/bookmarks/${id}`);
2626
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1920
2627
  }
1921
2628
  );
1922
2629
  server2.tool(
1923
2630
  "restore_bookmark",
1924
- "Restore a bookmark from the Trash, back into the folder it was filed in. 404 when it is not in the Trash. Requires the tensor:bookmarks:write scope.",
1925
- { id: z.number().describe("Bookmark ID") },
2631
+ "Take a bookmark out of Trash, back into its folder.",
2632
+ { id: z2.number().describe("Bookmark ID") },
1926
2633
  async ({ id }) => {
1927
- const data = await api("POST", `/api/bookmarks/${id}/restore`);
1928
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2634
+ const data = await api2("POST", `/api/bookmarks/${id}/restore`);
2635
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1929
2636
  }
1930
2637
  );
1931
2638
  server2.tool(
1932
2639
  "list_bookmark_folders",
1933
- "The bookmark folder tree \u2014 every folder in the organization, each with its parentId, in the order the owner arranged them: parents before children, siblings in their hand-set order. Keep that order rather than sorting by name. Folders nest. This is a SIBLING resource of /api/bookmarks rather than a sub-path of it, but one scope opens both. Requires the tensor:bookmarks:read scope.",
2640
+ "The bookmark folder tree, each with parentId, in the owner's order (parents first, siblings as arranged). Keep that order rather than sorting by name.",
1934
2641
  {},
1935
2642
  async () => {
1936
- const data = await api("GET", "/api/bookmark-folders");
1937
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2643
+ const data = await api2("GET", "/api/bookmark-folders");
2644
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1938
2645
  }
1939
2646
  );
1940
2647
  server2.tool(
1941
2648
  "create_bookmark_folder",
1942
- "Create a bookmark folder, optionally inside another. Requires the tensor:bookmarks:write scope.",
2649
+ "Create a bookmark folder, optionally inside another.",
1943
2650
  {
1944
- name: z.string().describe("Folder name (1-256 chars)"),
1945
- parentId: z.number().optional().describe("Nest it inside this folder. Omit for a root folder.")
2651
+ name: z2.string().describe("Folder name (1-256 chars)"),
2652
+ parentId: z2.number().optional().describe("Nest it inside this folder. Omit for a root folder.")
1946
2653
  },
1947
2654
  async (params) => {
1948
- const data = await api("POST", "/api/bookmark-folders", params);
1949
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2655
+ const data = await api2("POST", "/api/bookmark-folders", params);
2656
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1950
2657
  }
1951
2658
  );
1952
2659
  server2.tool(
1953
2660
  "update_bookmark_folder",
1954
- "Rename a folder or move it to a different parent. Pass parentId as null to make it a root folder. A move that would put a folder inside itself, or push the tree past its depth ceiling, is refused with 409 and a message saying which \u2014 branch on the message rather than retrying. Requires the tensor:bookmarks:write scope.",
2661
+ "Rename a bookmark folder or change its parent (null for root). 409 for a cycle or past the depth cap.",
1955
2662
  {
1956
- id: z.number().describe("Folder ID"),
1957
- name: z.string().optional().describe("Replacement name"),
1958
- parentId: z.number().nullable().optional().describe("New parent, or null for a root folder")
2663
+ id: z2.number().describe("Folder ID"),
2664
+ name: z2.string().optional().describe("Replacement name"),
2665
+ parentId: z2.number().nullable().optional().describe("New parent, or null for a root folder")
1959
2666
  },
1960
2667
  async ({ id, ...body }) => {
1961
- const data = await api("PATCH", `/api/bookmark-folders/${id}`, body);
1962
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2668
+ const data = await api2("PATCH", `/api/bookmark-folders/${id}`, body);
2669
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1963
2670
  }
1964
2671
  );
1965
2672
  server2.tool(
1966
- "delete_bookmark_folder",
1967
- "Destroy a folder AND NOTHING ELSE. Its bookmarks are UNFILED \u2014 folderId set to null, still in the library and not in the Trash \u2014 and its sub-folders are promoted to its own parent. A non-empty folder is therefore accepted, unlike delete_file_folder which refuses one: nothing under it is lost. THERE IS NO UNDO, because a folder is a filing decision rather than a Trash surface; the bookmarks survive but the folder does not come back. Requires the tensor:bookmarks:write scope.",
1968
- { id: z.number().describe("Folder ID") },
1969
- async ({ id }) => {
1970
- const data = await api("DELETE", `/api/bookmark-folders/${id}`);
1971
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2673
+ "move_bookmark_folder",
2674
+ "Move a bookmark folder under another and/or among its siblings. 409 for a cycle; ten levels at most.",
2675
+ {
2676
+ id: z2.number().describe("Folder ID"),
2677
+ parentId: z2.number().nullable().optional().describe("New parent folder; null = top level. Omit to keep the current parent."),
2678
+ beforeId: z2.number().nullable().optional().describe("The row that will sit directly ABOVE it, in the destination"),
2679
+ afterId: z2.number().nullable().optional().describe("The row that will sit directly BELOW it, in the destination")
2680
+ },
2681
+ async ({ id, ...body }) => {
2682
+ const data = await api2("POST", `/api/bookmark-folders/${id}/move`, body);
2683
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1972
2684
  }
1973
2685
  );
2686
+ server2.tool(
2687
+ "delete_bookmark_folder",
2688
+ "Delete a folder only: its bookmarks become Unfiled and its sub-folders move up. The folder cannot come back. Permanent. Two calls: the first deletes nothing and returns a preview and a confirmToken; repeat with it only after the user agrees.",
2689
+ { id: z2.number().describe("Folder ID"), confirmToken: CONFIRM_TOKEN_INPUT },
2690
+ async ({ id, confirmToken }) => confirmable(() => api2("DELETE", `/api/bookmark-folders/${id}`, void 0, { confirmToken }))
2691
+ );
1974
2692
  server2.tool(
1975
2693
  "list_tab_groups",
1976
- "List tab groups synced from a browser, each hydrated with its tabs \u2014 there is no per-tab read, because the group is the unit of everything except search. Starred groups come first, then newest first. `limit`/`offset` page the GROUPS; a group's tabs are never truncated. Requires the tensor:tabs:read scope, which is SEPARATE from tensor:bookmarks:read on purpose: a synced group is in effect a partial browsing history.",
2694
+ "This person's parked tab groups, each with all its tabs. Starred groups come first, then newest first. limit/offset page groups, never tabs.",
1977
2695
  {
1978
- limit: z.number().optional().describe("Max GROUPS. Default 500."),
1979
- offset: z.number().optional().describe("Pagination offset, in groups"),
1980
- trash: z.boolean().optional().describe("true = trashed groups instead of live ones")
2696
+ limit: LIMIT_INPUT,
2697
+ offset: OFFSET_INPUT,
2698
+ trash: z2.boolean().optional().describe("true = trashed groups instead of live ones")
1981
2699
  },
1982
2700
  async ({ limit, offset, trash }) => {
1983
2701
  const params = new URLSearchParams();
1984
- if (limit) params.set("limit", String(limit));
1985
- if (offset) params.set("offset", String(offset));
1986
2702
  if (trash) params.set("trash", "1");
1987
- const qs = params.toString();
1988
- const data = await api("GET", `/api/tabs${qs ? `?${qs}` : ""}`);
1989
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2703
+ return listPage(params, limit, offset, (qs) => api2("GET", `/api/tabs?${qs}`));
1990
2704
  }
1991
2705
  );
1992
2706
  server2.tool(
1993
2707
  "get_tab_group",
1994
- "Get one tab group with its tabs in order. `deviceLabel` says which machine collapsed it and is display only \u2014 never an identity or a key. Requires the tensor:tabs:read scope.",
1995
- { id: z.number().describe("Tab group ID") },
2708
+ "One tab group with its tabs in order.",
2709
+ { id: z2.number().describe("Tab group ID") },
1996
2710
  async ({ id }) => {
1997
- const data = await api("GET", `/api/tabs/${id}`);
1998
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2711
+ const data = await api2("GET", `/api/tabs/${id}`);
2712
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
1999
2713
  }
2000
2714
  );
2001
2715
  server2.tool(
2002
2716
  "create_tab_group",
2003
- "Park a set of tabs as one group. ONE CALL CARRIES THE WHOLE GROUP and that is a requirement rather than a convenience \u2014 the per-key rate limit is 120 requests a minute, so posting fifty tabs one at a time would spend a third of the window on a single collapse. Between 1 and 500 tabs, kept in the order you send them. Requires the tensor:tabs:write scope.",
2717
+ "Park tabs as one group in ONE call (1 to 500, in order), never tab by tab.",
2004
2718
  {
2005
- items: z.array(z.object({
2006
- url: z.string().describe("The tab's URL (max 2048 chars)"),
2007
- title: z.string().nullable().optional().describe("Page title"),
2008
- faviconUrl: z.string().nullable().optional().describe("Favicon URL \u2014 kept remote")
2719
+ items: z2.array(z2.object({
2720
+ url: z2.string().describe("The tab's URL (max 2048 chars)"),
2721
+ title: z2.string().nullable().optional().describe("Page title"),
2722
+ faviconUrl: z2.string().nullable().optional().describe("Favicon URL \u2014 kept remote")
2009
2723
  })).describe("The tabs, in order. At least one, at most 500."),
2010
- name: z.string().nullable().optional().describe(`Group name. THE SERVER NEVER FILLS THIS IN: omit it and the group stays unnamed, and every Tensor surface renders it as "Untitled group". The Chrome extension's groups look dated because the extension stamps a date itself before posting, which is not something this route does for you \u2014 so name the group here, or accept that it has none.`),
2011
- deviceLabel: z.string().nullable().optional().describe("Which machine this came from. Display only."),
2012
- locked: z.boolean().optional().describe("Do not let anything clear this group"),
2013
- starred: z.boolean().optional().describe("Pin it to the top of the list")
2724
+ name: z2.string().nullable().optional().describe('Group name. Never filled in for you: without one the group shows as "Untitled group".'),
2725
+ deviceLabel: z2.string().nullable().optional().describe("Which machine this came from. Display only."),
2726
+ locked: z2.boolean().optional().describe("Do not let anything clear this group"),
2727
+ starred: z2.boolean().optional().describe("Pin it to the top of the list")
2014
2728
  },
2015
2729
  async (params) => {
2016
- const data = await api("POST", "/api/tabs", params);
2017
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2730
+ const data = await api2("POST", "/api/tabs", params);
2731
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2018
2732
  }
2019
2733
  );
2020
2734
  server2.tool(
2021
2735
  "update_tab_group",
2022
- `Edit a tab group. EXACTLY THREE FIELDS ARE EDITABLE \u2014 name, locked, starred \u2014 and the tab list is deliberately not among them: a whole-array replace would make "which tabs did I have" unanswerable from the audit trail. A tab leaves through delete_tab; tabs arrive by creating another group (the HTTP API's batched POST /api/tabs/{id}/items, used by the browser extension, has no tool). A trashed group answers 404 until it is restored. Requires the tensor:tabs:write scope.`,
2736
+ "Edit a tab group's name, locked or starred. Tabs leave by delete_tab and arrive by add_tabs_to_group.",
2023
2737
  {
2024
- id: z.number().describe("Tab group ID"),
2025
- name: z.string().nullable().optional().describe("Replacement name"),
2026
- locked: z.boolean().optional().describe("Do not let anything clear this group"),
2027
- starred: z.boolean().optional().describe("Pin it to the top of the list")
2738
+ id: z2.number().describe("Tab group ID"),
2739
+ name: z2.string().nullable().optional().describe("Replacement name"),
2740
+ locked: z2.boolean().optional().describe("Do not let anything clear this group"),
2741
+ starred: z2.boolean().optional().describe("Pin it to the top of the list")
2028
2742
  },
2029
2743
  async ({ id, ...body }) => {
2030
- const data = await api("PATCH", `/api/tabs/${id}`, body);
2031
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2744
+ const data = await api2("PATCH", `/api/tabs/${id}`, body);
2745
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2746
+ }
2747
+ );
2748
+ server2.tool(
2749
+ "add_tabs_to_group",
2750
+ "Append 1 to 500 tabs to a group in one call.",
2751
+ {
2752
+ id: z2.number().describe("Tab group ID"),
2753
+ items: z2.array(z2.object({
2754
+ url: z2.string().describe("The tab's URL (max 2048 chars)"),
2755
+ title: z2.string().nullable().optional().describe("Page title"),
2756
+ faviconUrl: z2.string().nullable().optional().describe("Favicon URL")
2757
+ })).describe("The tabs to append, in order")
2758
+ },
2759
+ async ({ id, items }) => {
2760
+ const data = await api2("POST", `/api/tabs/${id}/items`, { items });
2761
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2032
2762
  }
2033
2763
  );
2034
2764
  server2.tool(
2035
2765
  "delete_tab",
2036
- "Remove ONE tab from a live group. Immediate and not recoverable \u2014 a tab has no Trash of its own because the GROUP is the recoverable unit. To put the whole group aside instead, use delete_tab_group. Requires the tensor:tabs:write scope.",
2766
+ "Remove one tab from a group, immediately and for good (only groups have Trash).",
2037
2767
  {
2038
- id: z.number().describe("Tab group ID"),
2039
- itemId: z.number().describe("The tab's own id, from the group's items")
2768
+ id: z2.number().describe("Tab group ID"),
2769
+ itemId: z2.number().describe("The tab's own id, from the group's items")
2040
2770
  },
2041
2771
  async ({ id, itemId }) => {
2042
- const data = await api("DELETE", `/api/tabs/${id}/items/${itemId}`);
2043
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2772
+ const data = await api2("DELETE", `/api/tabs/${id}/items/${itemId}`);
2773
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2044
2774
  }
2045
2775
  );
2046
2776
  server2.tool(
2047
2777
  "delete_tab_group",
2048
- "Move a whole tab group to the Trash (soft delete). The tabs stay attached and restore_tab_group undoes it. The Trash empties itself sixty days after deletion; the permanent purge is deliberately not reachable with an API key. Requires the tensor:tabs:write scope.",
2049
- { id: z.number().describe("Tab group ID") },
2778
+ "Move a tab group, tabs and all, to Trash.",
2779
+ { id: z2.number().describe("Tab group ID") },
2050
2780
  async ({ id }) => {
2051
- const data = await api("DELETE", `/api/tabs/${id}`);
2052
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2781
+ const data = await api2("DELETE", `/api/tabs/${id}`);
2782
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2053
2783
  }
2054
2784
  );
2055
2785
  server2.tool(
2056
2786
  "restore_tab_group",
2057
- "Restore a tab group from the Trash, tabs and all. 404 when it is not in the Trash. Requires the tensor:tabs:write scope.",
2058
- { id: z.number().describe("Tab group ID") },
2787
+ "Take a tab group out of Trash.",
2788
+ { id: z2.number().describe("Tab group ID") },
2059
2789
  async ({ id }) => {
2060
- const data = await api("POST", `/api/tabs/${id}/restore`);
2061
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
2790
+ const data = await api2("POST", `/api/tabs/${id}/restore`);
2791
+ return { content: [{ type: "text", text: JSON.stringify(data) }] };
2062
2792
  }
2063
2793
  );
2064
2794
  }
2795
+ async function visibleToolScopes(client, timeoutMs = 5e3) {
2796
+ let timer;
2797
+ try {
2798
+ const timeout = new Promise((_, reject) => {
2799
+ timer = setTimeout(() => reject(new Error("whoami timed out")), timeoutMs);
2800
+ });
2801
+ const answer = await Promise.race([client("GET", "/api/v1/whoami"), timeout]);
2802
+ const scopes = answer?.effectiveScopes;
2803
+ return Array.isArray(scopes) && scopes.every((s) => typeof s === "string") ? scopes : null;
2804
+ } catch {
2805
+ return null;
2806
+ } finally {
2807
+ if (timer) clearTimeout(timer);
2808
+ }
2809
+ }
2065
2810
  function createApiClient(opts) {
2066
2811
  const baseUrl = opts.baseUrl.replace(/\/+$/, "");
2067
2812
  const apiKey = opts.apiKey;
2068
- return async (method, path, body) => {
2813
+ const extraHeaders = Object.fromEntries(
2814
+ Object.entries(opts.headers ?? {}).filter(
2815
+ ([name]) => !/^(authorization|accept|content-type|idempotency-key|tensor-confirm)$/i.test(name)
2816
+ )
2817
+ );
2818
+ return async (method, path, body, options) => {
2069
2819
  const headers = {
2820
+ ...extraHeaders,
2070
2821
  Authorization: `Bearer ${apiKey}`,
2071
2822
  Accept: "application/json"
2072
2823
  };
2073
2824
  if (body !== void 0) {
2074
2825
  headers["Content-Type"] = "application/json";
2075
2826
  }
2827
+ if (options?.idempotencyKey && method !== "GET") {
2828
+ headers["Idempotency-Key"] = options.idempotencyKey;
2829
+ }
2830
+ if (options?.confirmToken && method === "DELETE") {
2831
+ headers["Tensor-Confirm"] = options.confirmToken;
2832
+ }
2076
2833
  const res = await fetch(`${baseUrl}${path}`, {
2077
2834
  method,
2078
2835
  headers,
@@ -2080,7 +2837,12 @@ function createApiClient(opts) {
2080
2837
  });
2081
2838
  const text = await res.text();
2082
2839
  if (!res.ok) {
2083
- throw new Error(`Tensor API ${method} ${path} \u2192 ${res.status}: ${text}`);
2840
+ let body2 = text;
2841
+ try {
2842
+ body2 = JSON.parse(text);
2843
+ } catch {
2844
+ }
2845
+ throw new ApiError(describeApiFailure(method, path, res.status, text, res.headers.get("retry-after")), res.status, body2);
2084
2846
  }
2085
2847
  try {
2086
2848
  return JSON.parse(text);
@@ -2090,10 +2852,24 @@ function createApiClient(opts) {
2090
2852
  };
2091
2853
  }
2092
2854
 
2855
+ // identity.ts
2856
+ var TENSOR_WEBSITE_URL = "https://tensor.levitating.org";
2857
+ var SERVER_IDENTITY = {
2858
+ name: "tensor",
2859
+ title: "Tensor",
2860
+ description: "A private family-office workbench: the ledger (entities, accounts, positions, transactions, loans, funds) and the work (todos, ideas, files, bookmarks).",
2861
+ websiteUrl: TENSOR_WEBSITE_URL,
2862
+ icons: [
2863
+ { src: `${TENSOR_WEBSITE_URL}/favicon.svg`, mimeType: "image/svg+xml", sizes: ["any"] },
2864
+ { src: `${TENSOR_WEBSITE_URL}/apple-touch-icon.png`, mimeType: "image/png", sizes: ["180x180"] },
2865
+ { src: `${TENSOR_WEBSITE_URL}/favicon.png`, mimeType: "image/png", sizes: ["32x32"] }
2866
+ ]
2867
+ };
2868
+
2093
2869
  // package.json
2094
2870
  var package_default = {
2095
2871
  name: "@levitating/tensor-mcp",
2096
- version: "5.3.1",
2872
+ version: "6.0.0",
2097
2873
  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.",
2098
2874
  type: "module",
2099
2875
  main: "./dist/index.js",
@@ -2102,6 +2878,7 @@ var package_default = {
2102
2878
  },
2103
2879
  files: [
2104
2880
  "dist",
2881
+ "skills",
2105
2882
  "README.md"
2106
2883
  ],
2107
2884
  scripts: {
@@ -2128,7 +2905,7 @@ var package_default = {
2128
2905
  license: "UNLICENSED",
2129
2906
  dependencies: {
2130
2907
  "@modelcontextprotocol/sdk": "^1.29.0",
2131
- zod: "^3.24.2"
2908
+ zod: "^4.6.7"
2132
2909
  },
2133
2910
  devDependencies: {
2134
2911
  esbuild: "^0.24.0",
@@ -2144,7 +2921,9 @@ if (!API_KEY) {
2144
2921
  process.exit(1);
2145
2922
  }
2146
2923
  var server = new McpServer({
2147
- name: "tensor",
2924
+ // Name, title, description, website and icons: one object, shared with the
2925
+ // hosted /mcp (./identity.ts).
2926
+ ...SERVER_IDENTITY,
2148
2927
  // READ FROM package.json, NOT TYPED HERE. This is the version the client sees
2149
2928
  // in the `initialize` response, and a hand-kept copy of a number that lives
2150
2929
  // somewhere else drifts — twice now. It was 1.0.0 while the package was
@@ -2158,9 +2937,19 @@ var server = new McpServer({
2158
2937
  // and never looks for a file at runtime. smoke:clerk-api-keys asserts the two
2159
2938
  // cannot disagree again.
2160
2939
  version: package_default.version
2940
+ }, {
2941
+ // What every agent reads on connect, before any tool. The text and the
2942
+ // reasoning live in ./guide.ts; server/routes/mcp.ts passes the same constant.
2943
+ instructions: SERVER_INSTRUCTIONS
2161
2944
  });
2162
- registerAllTools(server, createApiClient({ apiKey: API_KEY, baseUrl: BASE_URL }));
2945
+ var api = createApiClient({ apiKey: API_KEY, baseUrl: BASE_URL });
2946
+ var SELECTION = {
2947
+ readOnly: parseFlag(process.env.TENSOR_MCP_READ_ONLY),
2948
+ toolsets: parseToolsets(process.env.TENSOR_MCP_TOOLSETS)
2949
+ };
2163
2950
  async function main() {
2951
+ registerAllTools(server, api, { scopes: await visibleToolScopes(api), ...SELECTION });
2952
+ registerGuide(server);
2164
2953
  const transport = new StdioServerTransport();
2165
2954
  await server.connect(transport);
2166
2955
  }