-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
3839 lines (3621 loc) · 223 KB
/
Copy pathindex.ts
File metadata and controls
3839 lines (3621 loc) · 223 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { parseDoctorFlags, runDoctor, formatDoctorReport } from "./check.js";
import {
isDemoMode,
isSigningTool,
getDemoFixture,
demoSigningRefusalMessage,
} from "./demo/index.js";
import {
getLendingPositions,
getLpPositions,
getHealthAlerts,
simulatePositionChange,
} from "./modules/positions/index.js";
import {
getLendingPositionsInput,
getLpPositionsInput,
getHealthAlertsInput,
simulatePositionChangeInput,
} from "./modules/positions/schemas.js";
import { getSafePositions } from "./modules/safe/index.js";
import {
prepareSafeTxApprove,
prepareSafeTxPropose,
submitSafeTxSignature,
} from "./modules/safe/actions.js";
import { prepareSafeTxExecute } from "./modules/safe/execute.js";
import {
getSafePositionsInput,
prepareSafeTxApproveInput,
prepareSafeTxExecuteInput,
prepareSafeTxProposeInput,
submitSafeTxSignatureInput,
} from "./modules/safe/schemas.js";
import {
checkContractSecurityHandler,
checkPermissionRisksHandler,
getProtocolRiskScoreHandler,
} from "./modules/security/index.js";
import {
checkContractSecurityInput,
checkPermissionRisksInput,
getProtocolRiskScoreInput,
} from "./modules/security/schemas.js";
import { compareYields } from "./modules/yields/index.js";
import { compareYieldsInput } from "./modules/yields/schemas.js";
import {
getStakingPositions,
getStakingRewards,
estimateStakingYield,
} from "./modules/staking/index.js";
import {
getStakingPositionsInput,
getStakingRewardsInput,
estimateStakingYieldInput,
} from "./modules/staking/schemas.js";
import { getPortfolioSummary } from "./modules/portfolio/index.js";
import { getPortfolioDiff } from "./modules/diff/index.js";
import { getPortfolioDiffInput } from "./modules/diff/schemas.js";
import { shareStrategy, importStrategy } from "./modules/strategy/index.js";
import {
shareStrategyInput,
importStrategyInput,
} from "./modules/strategy/schemas.js";
import {
generateReadonlyLink,
importReadonlyToken,
listReadonlyInvites,
revokeReadonlyInvite,
} from "./modules/share/index.js";
import {
generateReadonlyLinkInput,
importReadonlyTokenInput,
listReadonlyInvitesInput,
revokeReadonlyInviteInput,
} from "./modules/share/schemas.js";
import { getDailyBriefing } from "./modules/digest/index.js";
import { getDailyBriefingInput } from "./modules/digest/schemas.js";
import { getPnlSummary } from "./modules/pnl/index.js";
import { getPnlSummaryInput } from "./modules/pnl/schemas.js";
import { explainTx } from "./modules/postmortem/index.js";
import { explainTxInput } from "./modules/postmortem/schemas.js";
import { getPortfolioSummaryInput } from "./modules/portfolio/schemas.js";
import { getVaultPilotConfigStatus } from "./modules/diagnostics/index.js";
import { getLedgerDeviceInfo } from "./modules/diagnostics/ledger-device-info.js";
import { verifyLedgerFirmware } from "./modules/diagnostics/ledger-firmware-verify.js";
import { verifyLedgerLiveCodesign } from "./modules/diagnostics/ledger-live-codesign-tool.js";
import { verifyLedgerAttestation } from "./signing/se-attestation.js";
import { getTransactionHistory } from "./modules/history/index.js";
import { getTransactionHistoryInput } from "./modules/history/schemas.js";
import { getSwapQuote, prepareSwap } from "./modules/swap/index.js";
import { getSwapQuoteInput, prepareSwapInput } from "./modules/swap/schemas.js";
import { prepareUniswapSwap } from "./modules/uniswap-swap/index.js";
import { prepareUniswapSwapInput } from "./modules/uniswap-swap/schemas.js";
import { getSessionStatus as getLedgerStatus } from "./signing/session.js";
import {
pairLedgerLive,
pairLedgerTron,
pairLedgerSolana,
pairLedgerBitcoin,
prepareSolanaNativeSend,
prepareSolanaSplSend,
prepareSolanaNonceInit,
prepareSolanaNonceClose,
getSolanaSwapQuote,
prepareSolanaSwap,
prepareMarginfiInit,
prepareMarginfiSupply,
prepareMarginfiWithdraw,
prepareMarginfiBorrow,
prepareMarginfiRepay,
prepareMarinadeStake,
prepareJitoStake,
prepareMarinadeUnstakeImmediate,
prepareNativeStakeDelegate,
prepareNativeStakeDeactivate,
prepareNativeStakeWithdraw,
prepareSolanaLifiSwap,
prepareTronLifiSwap,
prepareKaminoInitUser,
prepareKaminoSupply,
prepareKaminoBorrow,
prepareKaminoWithdraw,
prepareKaminoRepay,
getKaminoPositions,
getBitcoinBalance,
getBitcoinBalances,
getBitcoinFeeEstimates,
getBitcoinBlockTip,
getLitecoinBlockTip,
getBitcoinBlocksRecent,
getLitecoinBlocksRecent,
getBitcoinChainTips,
getLitecoinChainTips,
getBitcoinBlockStats,
getLitecoinBlockStats,
getBitcoinMempoolSummary,
getLitecoinMempoolSummary,
getBitcoinAccountBalance,
rescanBitcoinAccount,
getBitcoinTxHistory,
prepareBitcoinNativeSend,
prepareBitcoinRbfBump,
registerBtcMultisigWallet,
unregisterBtcMultisigWallet,
signBtcMultisigPsbt,
combineBtcPsbts,
finalizeBtcPsbt,
prepareBtcMultisigSend,
getBtcMultisigBalance,
getBtcMultisigUtxos,
signBtcMessage,
pairLedgerLitecoin,
getLitecoinBalance,
prepareLitecoinNativeSend,
signLtcMessage,
rescanLitecoinAccount,
getMarginfiPositions,
getSolanaStakingPositions,
getMarginfiDiagnostics,
getSolanaSetupStatus,
prepareAaveSupply,
prepareAaveWithdraw,
prepareAaveBorrow,
prepareAaveRepay,
prepareUniswapV3Mint,
prepareUniswapV3IncreaseLiquidity,
prepareUniswapV3DecreaseLiquidity,
prepareUniswapV3Collect,
prepareUniswapV3Burn,
prepareUniswapV3Rebalance,
prepareLidoStake,
prepareLidoUnstake,
prepareEigenLayerDeposit,
prepareNativeSend,
prepareWethUnwrap,
prepareTokenSend,
prepareRevokeApproval,
previewSend,
previewSolanaSend,
sendTransaction,
getTransactionStatus,
getTxVerification,
getVerificationArtifact,
verifyTxDecode,
} from "./modules/execution/index.js";
import {
pairLedgerLiveInput,
pairLedgerTronInput,
pairLedgerSolanaInput,
pairLedgerBitcoinInput,
prepareSolanaNativeSendInput,
prepareSolanaSplSendInput,
prepareSolanaNonceInitInput,
prepareSolanaNonceCloseInput,
getSolanaSwapQuoteInput,
prepareSolanaSwapInput,
prepareMarginfiInitInput,
prepareMarginfiSupplyInput,
prepareMarginfiWithdrawInput,
prepareMarginfiBorrowInput,
prepareMarginfiRepayInput,
prepareMarinadeStakeInput,
prepareJitoStakeInput,
prepareMarinadeUnstakeImmediateInput,
prepareNativeStakeDelegateInput,
prepareNativeStakeDeactivateInput,
prepareNativeStakeWithdrawInput,
prepareSolanaLifiSwapInput,
prepareTronLifiSwapInput,
prepareKaminoInitUserInput,
prepareKaminoSupplyInput,
prepareKaminoBorrowInput,
prepareKaminoWithdrawInput,
prepareKaminoRepayInput,
getKaminoPositionsInput,
getBitcoinBalanceInput,
getBitcoinBalancesInput,
getBitcoinFeeEstimatesInput,
getBitcoinBlockTipInput,
getLitecoinBlockTipInput,
getBitcoinBlocksRecentInput,
getLitecoinBlocksRecentInput,
getBitcoinChainTipsInput,
getLitecoinChainTipsInput,
getBitcoinBlockStatsInput,
getLitecoinBlockStatsInput,
getBitcoinMempoolSummaryInput,
getLitecoinMempoolSummaryInput,
getBitcoinAccountBalanceInput,
rescanBitcoinAccountInput,
getBitcoinTxHistoryInput,
prepareBitcoinNativeSendInput,
prepareBitcoinRbfBumpInput,
registerBitcoinMultisigWalletInput,
unregisterBitcoinMultisigWalletInput,
signBitcoinMultisigPsbtInput,
combineBitcoinPsbtsInput,
finalizeBitcoinPsbtInput,
prepareBitcoinMultisigSendInput,
getBitcoinMultisigBalanceInput,
getBitcoinMultisigUtxosInput,
signBtcMessageInput,
pairLedgerLitecoinInput,
getLitecoinBalanceInput,
prepareLitecoinNativeSendInput,
signLtcMessageInput,
rescanLitecoinAccountInput,
getMarginfiPositionsInput,
getSolanaStakingPositionsInput,
getMarginfiDiagnosticsInput,
getSolanaSetupStatusInput,
getVaultPilotConfigStatusInput,
getLedgerDeviceInfoInput,
verifyLedgerFirmwareInput,
verifyLedgerLiveCodesignInput,
verifyLedgerAttestationInput,
getLedgerStatusInput,
prepareAaveSupplyInput,
prepareAaveWithdrawInput,
prepareAaveBorrowInput,
prepareAaveRepayInput,
prepareUniswapV3MintInput,
prepareUniswapV3IncreaseLiquidityInput,
prepareUniswapV3DecreaseLiquidityInput,
prepareUniswapV3CollectInput,
prepareUniswapV3BurnInput,
prepareUniswapV3RebalanceInput,
prepareLidoStakeInput,
prepareLidoUnstakeInput,
prepareEigenLayerDepositInput,
prepareNativeSendInput,
prepareWethUnwrapInput,
prepareTokenSendInput,
prepareRevokeApprovalInput,
previewSendInput,
previewSolanaSendInput,
sendTransactionInput,
getTransactionStatusInput,
getTxVerificationInput,
getVerificationArtifactInput,
} from "./modules/execution/schemas.js";
import {
getTokenBalance,
getTokenMetadata,
resolveName,
reverseResolve,
} from "./modules/balances/index.js";
import { getTokenAllowances } from "./modules/allowances/index.js";
import { getTokenAllowancesInput } from "./modules/allowances/schemas.js";
import {
getNftCollection,
getNftHistory,
getNftPortfolio,
} from "./modules/nft/index.js";
import {
getNftCollectionInput,
getNftHistoryInput,
getNftPortfolioInput,
} from "./modules/nft/schemas.js";
import {
getTokenBalanceInput,
getTokenMetadataInput,
resolveNameInput,
reverseResolveInput,
} from "./modules/balances/schemas.js";
import {
addContact,
removeContact,
listContacts,
verifyContacts,
} from "./contacts/index.js";
import {
addContactInput,
removeContactInput,
listContactsInput,
verifyContactsInput,
} from "./contacts/schemas.js";
import { getTronStaking } from "./modules/tron/staking.js";
import { listTronWitnesses } from "./modules/tron/witnesses.js";
import {
buildTronNativeSend,
buildTronTokenSend,
buildTronTrc20Approve,
buildTronClaimRewards,
buildTronFreeze,
buildTronUnfreeze,
buildTronWithdrawExpireUnfreeze,
buildTronVote,
} from "./modules/tron/actions.js";
import {
getTronStakingInput,
prepareTronNativeSendInput,
prepareTronTokenSendInput,
prepareTronTrc20ApproveInput,
prepareTronClaimRewardsInput,
prepareTronFreezeInput,
prepareTronUnfreezeInput,
prepareTronWithdrawExpireUnfreezeInput,
listTronWitnessesInput,
prepareTronVoteInput,
} from "./modules/tron/schemas.js";
import { getCompoundPositions } from "./modules/compound/index.js";
import { getCurvePositions } from "./modules/curve/positions.js";
import { buildCurveAddLiquidity } from "./modules/curve/actions.js";
import {
getCurvePositionsInput,
prepareCurveAddLiquidityInput,
} from "./modules/curve/schemas.js";
import { getCompoundMarketInfo } from "./modules/compound/market-info.js";
import { getMarketIncidentStatus } from "./modules/incidents/index.js";
import { getMarketIncidentStatusInput } from "./modules/incidents/schemas.js";
import { startOraclePoller } from "./modules/incidents/oracle-poller.js";
import {
buildCompoundSupply,
buildCompoundWithdraw,
buildCompoundBorrow,
buildCompoundRepay,
} from "./modules/compound/actions.js";
import {
getCompoundPositionsInput,
getCompoundMarketInfoInput,
prepareCompoundSupplyInput,
prepareCompoundWithdrawInput,
prepareCompoundBorrowInput,
prepareCompoundRepayInput,
} from "./modules/compound/schemas.js";
import { getMorphoPositions } from "./modules/morpho/index.js";
import {
buildMorphoSupply,
buildMorphoWithdraw,
buildMorphoBorrow,
buildMorphoRepay,
buildMorphoSupplyCollateral,
buildMorphoWithdrawCollateral,
} from "./modules/morpho/actions.js";
import {
getMorphoPositionsInput,
prepareMorphoSupplyInput,
prepareMorphoWithdrawInput,
prepareMorphoBorrowInput,
prepareMorphoRepayInput,
prepareMorphoSupplyCollateralInput,
prepareMorphoWithdrawCollateralInput,
} from "./modules/morpho/schemas.js";
import {
getTokenPriceInput,
getTokenPriceTool,
getCoinPriceInput,
getCoinPriceTool,
} from "./modules/prices/index.js";
import { simulateTransaction } from "./modules/simulation/index.js";
import { simulateTransactionInput } from "./modules/simulation/schemas.js";
import { requestCapability, requestCapabilityInput } from "./modules/feedback/index.js";
import { issueHandles } from "./signing/tx-store.js";
import {
renderAgentTaskBlock,
renderLedgerHashBlock,
renderMissingSkillWarning,
renderMissingSetupSkillWarning,
renderPostBroadcastBlock,
renderPostSendPollBlock,
renderBitcoinVerificationBlock,
renderLitecoinVerificationBlock,
renderPrepareReceiptBlock,
renderPreviewVerifyAgentTaskBlock,
renderSolanaAgentTaskBlock,
renderSolanaPrepareAgentTaskBlock,
renderSolanaPrepareSummaryBlock,
renderSolanaVerificationBlock,
renderTronAgentTaskBlock,
renderTronVerificationBlock,
renderVerificationBlock,
shouldRenderVerificationBlock,
type RenderableSolanaPrepareResult,
} from "./signing/render-verification.js";
import { verifyEvmCalldata, type VerifyDecodeResult } from "./signing/verify-decode.js";
import type {
SupportedChain,
TxVerification,
UnsignedBitcoinTx,
UnsignedLitecoinTx,
UnsignedSolanaTx,
UnsignedTronTx,
UnsignedTx,
} from "./types/index.js";
import type { SendTransactionArgs } from "./modules/execution/schemas.js";
import { readUserConfig } from "./config/user-config.js";
import { safeErrorMessage } from "./shared/error-message.js";
/**
* URL of the agent-side preflight skill's git repo. Single source of truth
* for every place the MCP tells the user where to clone from (the missing-
* skill warning, the README, future SECURITY.md copy). Kept as a constant
* so one rename in one place updates every surface.
*/
const SKILL_REPO_URL = "https://github.com/szhygulin/vaultpilot-skill.git";
/**
* Companion `vaultpilot-setup` skill (conversational /setup flow). Lives in
* its own repo so a compromise of `vaultpilot-mcp` can't weaken it. The
* setup-skill notice is the secondary install path — it fires when the
* wizard's auto-install (`src/setup/install-skills.ts`) didn't complete
* (git missing / network down / user declined).
*/
const SETUP_SKILL_REPO_URL =
"https://github.com/szhygulin/vaultpilot-setup-skill.git";
/**
* Default filesystem marker for the installed skill. `existsSync` against
* this path is the cheap "is the skill installed" check we run on every
* prepare_ / preview_ response. Overridable via env var for tests.
*/
const DEFAULT_SKILL_MARKER = join(
homedir(),
".claude",
"skills",
"vaultpilot-preflight",
"SKILL.md",
);
const DEFAULT_SETUP_SKILL_MARKER = join(
homedir(),
".claude",
"skills",
"vaultpilot-setup",
"SKILL.md",
);
function skillMarkerPath(): string {
return process.env.VAULTPILOT_SKILL_MARKER_PATH ?? DEFAULT_SKILL_MARKER;
}
function setupSkillMarkerPath(): string {
return (
process.env.VAULTPILOT_SETUP_SKILL_MARKER_PATH ?? DEFAULT_SETUP_SKILL_MARKER
);
}
/**
* Returns `true` iff the `vaultpilot-preflight` skill appears installed in
* the user's Claude Code skills directory. Checked per-call rather than at
* startup so installing the skill mid-session takes effect without a
* server restart.
*/
export function isPreflightSkillInstalled(): boolean {
return existsSync(skillMarkerPath());
}
/**
* Returns `true` iff the `vaultpilot-setup` skill appears installed.
* Mirrors the per-call check pattern of `isPreflightSkillInstalled` so a
* mid-session install (the user runs `git clone` after seeing the notice)
* takes effect without a server restart.
*/
export function isSetupSkillInstalled(): boolean {
return existsSync(setupSkillMarkerPath());
}
/**
* Module-level dedup: the missing-skill notice is emitted once per MCP
* process lifetime (i.e. once per client session, since stdio servers get
* a fresh process per client connection). Emitting on every tool call
* created a review-readable nag that competing agent systems began
* treating as prompt injection. One notice per session, on the first
* tool call that fires after the skill is absent, is enough.
*
* If the user installs the skill mid-session, `isPreflightSkillInstalled`
* flips to true and resets the flag so that a later removal would retrigger.
*/
let missingSkillNoticeEmitted = false;
/**
* Exported for tests — lets a test reset the dedup state between cases so
* "warning appears once" and "warning suppressed on second call" can be
* asserted independently.
*/
export function _resetMissingPreflightSkillDedup(): void {
missingSkillNoticeEmitted = false;
}
/**
* Render the missing-skill notice block if the skill is NOT installed AND
* the notice has not yet been emitted in this session; otherwise return
* `null`. Called by every tool handler so the notice surfaces on whatever
* is the user's first vaultpilot-mcp call (read-only or signing).
*
* This is a UX nudge, not a security boundary — an actually-compromised
* MCP would suppress its own notice. The purpose is to catch the
* honest-MCP case where the user hasn't completed the install step so
* they don't silently run with a weaker agent. See SECURITY.md for the
* full layered-defense reasoning.
*/
export function missingPreflightSkillWarning(): string | null {
if (isPreflightSkillInstalled()) {
// Reset dedup flag: if the user installs the skill mid-session, a
// subsequent uninstall should re-trigger the notice.
missingSkillNoticeEmitted = false;
return null;
}
if (missingSkillNoticeEmitted) return null;
missingSkillNoticeEmitted = true;
return renderMissingSkillWarning({ skillRepoUrl: SKILL_REPO_URL });
}
/**
* Independent dedup flag for the setup-skill notice. Separate from
* `missingSkillNoticeEmitted` so a session can surface both notices
* (preflight + setup) once each — the two skills are independently
* useful and live at different lifecycle points (every-tool-call vs
* setup-flow only).
*/
let missingSetupSkillNoticeEmitted = false;
export function _resetMissingSetupSkillDedup(): void {
missingSetupSkillNoticeEmitted = false;
}
/**
* Render the setup-skill missing-notice — once per session, only when the
* skill file is absent. Designed to be invoked from the
* `get_vaultpilot_config_status` handler (the canonical entry point the
* setup skill prescribes), so the notice fires exactly when the agent is
* already in a setup-flow context. Wider invocation would stack two
* unrelated install notices on every response and dilute the signal.
*/
export function missingSetupSkillWarning(): string | null {
if (isSetupSkillInstalled()) {
missingSetupSkillNoticeEmitted = false;
return null;
}
if (missingSetupSkillNoticeEmitted) return null;
missingSetupSkillNoticeEmitted = true;
return renderMissingSetupSkillWarning({ skillRepoUrl: SETUP_SKILL_REPO_URL });
}
/**
* Collect rendered verification blocks from a result, walking `.next` for
* EVM approve→action chains. Each prepared tx in the chain gets its own
* block so the user can cross-check every hash they will sign — never a
* single aggregated block that conflates two separate signatures.
*
* Runs the independent 4byte.directory cross-check inline so its summary
* is ALWAYS emitted, regardless of whether the agent remembers to call
* `verify_tx_decode`. A compromised agent could previously skip the tool
* and fabricate a "✓ cross-check passed" line; now the server emits the
* real result adjacent to the verification block.
*
* Unknown shapes return an empty array (non-prepare tools have no
* verification field).
*/
export async function collectVerificationBlocks(
result: unknown,
opts?: {
verify?: (
tx: UnsignedTx & { verification: TxVerification },
) => Promise<VerifyDecodeResult>;
},
): Promise<string[]> {
const verify = opts?.verify ?? verifyEvmCalldata;
if (!result || typeof result !== "object") return [];
const blocks: string[] = [];
// EVM path: UnsignedTx has `chain` / `to` / `data` / `value` / `verification` + optional `.next`.
const r = result as Record<string, unknown>;
const verification = r.verification as TxVerification | undefined;
const chain = r.chain as string | undefined;
// Solana drafts (prepare_solana_*) carry no `verification` field — the
// verification bundle is built at `preview_solana_send` time when the
// message bytes are pinned. Handle drafts before bailing on missing
// `verification`.
if (chain === "solana" && !verification && !r.messageBase64) {
if (
typeof r.handle === "string" &&
typeof r.action === "string" &&
typeof r.description === "string" &&
r.decoded !== undefined
) {
const prepared = result as RenderableSolanaPrepareResult;
blocks.push(renderSolanaPrepareSummaryBlock(prepared));
blocks.push(renderSolanaPrepareAgentTaskBlock(prepared));
}
return blocks;
}
// Bitcoin prepare results carry no `verification` field — the Ledger BTC
// app clear-signs every output, so the per-output address+amount
// projection IS the review surface. Handle BEFORE the `!verification`
// early-return that the EVM branch relies on.
if (chain === "bitcoin" && typeof r.psbtBase64 === "string") {
blocks.push(renderBitcoinVerificationBlock(result as UnsignedBitcoinTx));
return blocks;
}
if (chain === "litecoin" && typeof r.psbtBase64 === "string") {
blocks.push(renderLitecoinVerificationBlock(result as UnsignedLitecoinTx));
return blocks;
}
if (!verification) return blocks;
if (chain === "tron" && typeof r.rawDataHex === "string") {
const tronTx = result as UnsignedTronTx & { verification: TxVerification };
blocks.push(renderTronVerificationBlock(tronTx));
blocks.push(renderTronAgentTaskBlock(tronTx));
return blocks;
}
if (chain === "solana" && typeof r.messageBase64 === "string") {
// Pinned Solana tx — emitted by `preview_solana_send`. Full VERIFY +
// CHECKS block (agent auto-runs CHECK 1 + CHECK 2, matches hash).
const solanaTx = result as UnsignedSolanaTx;
blocks.push(renderSolanaVerificationBlock(solanaTx));
blocks.push(renderSolanaAgentTaskBlock(solanaTx));
return blocks;
}
if (typeof r.to === "string" && typeof r.data === "string" && typeof r.value === "string" && typeof chain === "string") {
const tx = result as UnsignedTx & { verification: TxVerification };
// ERC-20 approvals clear-sign on Ledger's Ethereum app — skip rendering
// (the send-time payload-hash guard still runs, using tx.verification).
if (shouldRenderVerificationBlock(tx)) {
blocks.push(renderVerificationBlock(tx));
// Auto-emit the independent 4byte.directory cross-check. If the network
// call fails, verifyEvmCalldata returns an "error" summary — we still
// emit it so the agent surfaces the degraded state to the user rather
// than silently skipping.
try {
const cross = await verify(tx);
blocks.push(
`[CROSS-CHECK SUMMARY — RELAY VERBATIM TO USER AS THE FIRST LINE OF YOUR REPLY]\n${cross.summary}`,
);
} catch (e) {
blocks.push(
`[CROSS-CHECK SUMMARY — RELAY VERBATIM TO USER AS THE FIRST LINE OF YOUR REPLY]\n` +
`Could not run the independent calldata cross-check this turn (${e instanceof Error ? e.message : String(e)}). ` +
`The local ABI decode above is still shown; open the swiss-knife decoder URL in a browser for a manual check.`,
);
}
// Per-call agent directives (compact bullet summary, two trust-boundary
// options, Ledger-match reminder). Adjacent to the verification block so
// the model is far more likely to act on it than on the session-level
// instructions field, which it tends to ignore after the first few turns.
const taskBlock = renderAgentTaskBlock(tx);
if (taskBlock) blocks.push(taskBlock);
}
if (r.next) blocks.push(...(await collectVerificationBlocks(r.next, opts)));
}
return blocks;
}
/**
* Wrap a plain async function into the shape MCP expects.
* Returns `{ content: [{ type: "text", text }] }` on success,
* `{ content, isError: true }` on failure.
*
* When the result carries a `verification` field (every `prepare_*` tool
* output does), a SECOND text content block is appended with the rendered
* "VERIFY BEFORE SIGNING" prose — decoder URL, local decode, comparison
* string, payload hash, and the nudge to open the URL before approving.
* The block lives next to the JSON so machine readers still get the
* structured data AND the user sees the verification prose verbatim.
*/
function handler<T, R>(
fn: (args: T) => Promise<R> | R,
opts?: { toolName?: string },
) {
return async (args: T) => {
try {
const result = await fn(args);
const content: { type: "text"; text: string }[] = [
{ type: "text", text: JSON.stringify(result, bigintReplacer, 2) },
];
// Prefix the missing-skill warning to EVERY vaultpilot-mcp tool
// response when the agent-side preflight skill is absent. Applied
// unconditionally (not just prepare_*/preview_*) so the nudge
// surfaces on the canonical gateway calls — `get_ledger_status`,
// portfolio reads, pair_ledger_* — giving the user a chance to
// install before they reach a signing flow, by which point
// breaking out of the workflow is disruptive. Users who never
// sign anything can suppress via VAULTPILOT_SKILL_MARKER_PATH.
{
const warning = missingPreflightSkillWarning();
if (warning) content.push({ type: "text", text: warning });
}
// Emit the prepare-receipt for every tool that built a transaction
// (result carries `verification`). Gives the user a verbatim-relay view
// of the args that hit the server, independent of the agent's bullet
// summary — raises the tampering bar against narrow prompt injections
// and malicious add-ons that rewrite args without also crafting an
// output filter. See render-verification.ts for the full rationale.
if (
opts?.toolName &&
result !== null &&
typeof result === "object" &&
"verification" in (result as Record<string, unknown>)
) {
content.push({
type: "text",
text: renderPrepareReceiptBlock({
tool: opts.toolName,
args: (args ?? {}) as Record<string, unknown>,
}),
});
}
for (const block of await collectVerificationBlocks(result)) {
content.push({ type: "text", text: block });
}
return { content };
} catch (error) {
// Issue #326: the legacy `error instanceof Error ? error.message :
// String(error)` pattern produced `Error: [object Object]` when the
// underlying SDK (WalletConnect, viem) threw an Error whose .message
// was itself a structured object. Use the hardened helper instead so
// the agent (and the user) sees the actual failure cause.
return {
content: [{ type: "text" as const, text: `Error: ${safeErrorMessage(error)}` }],
isError: true,
};
}
};
}
/**
* Handler wrapper for prepare_* tools that return UnsignedTx. Runs the function,
* then issues opaque handles across the tx and every `.next` node so
* `send_transaction` can re-hydrate the exact tx from server state. The agent
* never passes raw calldata to the signing path — it calls send_transaction
* with a handle, which closes the prompt-injection → arbitrary-calldata window.
*
* `toolName` is the registered MCP tool name; it's threaded through so the
* prepare-receipt block can label which tool was called with which args.
*/
function txHandler<T>(toolName: string, fn: (args: T) => Promise<UnsignedTx> | UnsignedTx) {
return handler(async (args: T) => issueHandles(await fn(args)), { toolName });
}
/**
* Demo-mode-aware wrapper around `server.registerTool`. When
* `VAULTPILOT_DEMO=true` is set in the environment AT REQUEST TIME (not
* at startup), every tool call is intercepted before reaching its real
* handler:
*
* - signing tools (prepare_*, send_transaction, pair_ledger_*, etc.)
* refuse with a structured demo-mode error (`isSigningTool` decides);
* - read tools return a deterministic fixture from `DEMO_FIXTURES`,
* or — for tools without a fixture — a `_demoFixture: "not-implemented"`
* payload so the user sees what's covered.
*
* When the env var is unset, this function is a transparent pass-through
* to the real `server.registerTool` — zero runtime cost on the hot path.
*
* Single point of demo enforcement so adding a new tool only requires
* (a) registering it through `registerTool(server, ...)` like every
* other tool and optionally (b) adding a fixture entry. The signing-vs-
* read classification is pattern-based so new prepare_* / pair_ledger_*
* tools are gated automatically.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function registerTool(
server: InstanceType<typeof McpServer>,
name: string,
// `opts` mirrors the shape `server.registerTool` accepts (description +
// optional zod inputSchema); the SDK's parameter type is overloaded and
// doesn't infer cleanly through a generic wrapper, so we cast through
// `any` at the delegation point. Call-site type-safety is preserved by
// the SDK's own validation of the registered schema.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
opts: any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
realHandler: (args: any) => Promise<{ content: unknown[]; isError?: boolean }> | { content: unknown[]; isError?: boolean },
): ReturnType<InstanceType<typeof McpServer>["registerTool"]> {
// Pre-build the demo handler at registration time; it's only invoked
// when `isDemoMode()` is true at request time, but allocating it once
// up front keeps the request-path branch trivial.
const demoHandler = handler<unknown, unknown>(
(args: unknown) => {
if (isSigningTool(name)) {
throw new Error(demoSigningRefusalMessage(name));
}
return getDemoFixture(name, args);
},
{ toolName: name },
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dispatch = async (args: any) => {
if (isDemoMode()) return demoHandler(args);
return realHandler(args);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return server.registerTool(name, opts, dispatch as any);
}
/**
* Handler wrapper for `get_vaultpilot_config_status`. Tacks on the
* setup-skill missing-notice (once per session) AFTER the standard handler
* has emitted the preflight notice and JSON result. This is the canonical
* setup-flow entry point — the only tool both the setup wizard and the
* `vaultpilot-setup` skill prescribe calling first — so the notice fires
* exactly when an agent is in setup-flow context. Wider invocation would
* stack two unrelated install notices on every tool response.
*/
function configStatusHandler<T>(fn: (args: T) => unknown) {
const inner = handler(fn);
return async (args: T) => {
const res = await inner(args);
const notice = missingSetupSkillWarning();
if (notice && Array.isArray(res.content)) {
res.content.push({ type: "text", text: notice });
}
return res;
};
}
/**
* Handler wrapper for `preview_send`. Appends the user-facing LEDGER BLIND-
* SIGN HASH block so the agent relays the hash verbatim BEFORE calling
* `send_transaction` — which is the whole point of the preview step: the
* user must see the hash on their screen before the Ledger device prompt
* fires, since a single MCP tool call cannot emit content between pinning
* and signing.
*
* Exported for direct unit testing (the alternative is mirroring the
* content-array assembly in tests, which rots with every refactor).
*/
export function previewSendHandler(
fn: (args: { handle: string }) => Promise<{
handle: string;
chain: SupportedChain;
to: `0x${string}`;
valueWei: string;
preSignHash: `0x${string}`;
pinned: {
nonce: number;
maxFeePerGas: string;
maxPriorityFeePerGas: string;
gas: string;
};
previewToken: string;
decoderUrl?: string;
clearSignOnly?: boolean;
}>,
) {
return async (args: { handle: string }) => {
try {
const result = await fn(args);
const content: { type: "text"; text: string }[] = [
{ type: "text", text: JSON.stringify(result, bigintReplacer, 2) },
];
const warning = missingPreflightSkillWarning();
if (warning) content.push({ type: "text", text: warning });
// Suppress the LEDGER BLIND-SIGN HASH block for tx types where the
// Ledger Ethereum app clear-signs on-device (native sends, ERC-20
// approve, ERC-20 transfer). Showing a blind-sign hash that the
// device won't display trains the user to hunt for a match that
// doesn't exist — worse than useless: it dilutes the signal value
// of the hash block in real blind-sign flows (swaps, supplies, etc).
// The agent-task block below already tailors its NEXT ON-DEVICE
// section to clear-sign-only when `clearSignOnly: true`.
if (!result.clearSignOnly) {
content.push({
type: "text",
text: renderLedgerHashBlock({
preSignHash: result.preSignHash,
to: result.to,
valueWei: result.valueWei,
}),
});
}
// Agent-task block: offer the user an independent hash re-computation
// against a compromised MCP that lies about the hash. Optional, not
// run unprompted. Emitting it here (per-call) keeps the values in-
// context for the agent to splice into the local viem command.
content.push({
type: "text",
text: renderPreviewVerifyAgentTaskBlock({
chain: result.chain,
preSignHash: result.preSignHash,
pinned: result.pinned,
to: result.to,
valueWei: result.valueWei,
...(result.decoderUrl ? { decoderUrl: result.decoderUrl } : {}),
...(result.clearSignOnly ? { clearSignOnly: true } : {}),
}),
});
return { content };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text" as const, text: `Error: ${message}` }],
isError: true,
};
}
};
}
/**
* Handler wrapper for `preview_solana_send`. Pins a fresh blockhash against
* the draft handle and emits (a) the pinned UnsignedSolanaTx as JSON, (b) the
* user-facing VERIFY BEFORE SIGNING block with the Message Hash, and (c) the
* agent-task block with CHECK 1 + CHECK 2 recipes. Parallel to
* `previewSendHandler` but Solana-native — the message bytes are pinned
* here (not nonce + EIP-1559 fees).
*/
function previewSolanaSendHandler(
fn: (args: { handle: string }) => Promise<UnsignedSolanaTx>,
) {
return async (args: { handle: string }) => {
try {
const pinned = await fn(args);
const content: { type: "text"; text: string }[] = [
{ type: "text", text: JSON.stringify(pinned, bigintReplacer, 2) },
];
const warning = missingPreflightSkillWarning();
if (warning) content.push({ type: "text", text: warning });
content.push({ type: "text", text: renderSolanaVerificationBlock(pinned) });
content.push({ type: "text", text: renderSolanaAgentTaskBlock(pinned) });
return { content };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text" as const, text: `Error: ${message}` }],
isError: true,
};
}
};
}
/**
* Handler wrapper for `send_transaction`. Emits a user-facing post-broadcast
* block with the txHash + explorer link (so the agent cannot silently drop
* the hash from the chat — a live-test regression that motivated this
* block), followed by an agent-task block directing self-polling via
* `get_transaction_status`. The session-level instructions tend to drift out
* of attention after a few hundred tokens, so we put the directive adjacent
* to the txHash it refers to.
*/
function sendTransactionHandler(
fn: (args: SendTransactionArgs) => Promise<{
txHash: `0x${string}` | string;
chain: SupportedChain | "tron" | "solana" | "bitcoin" | "litecoin";