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