contextvm-sdk 0.1.1

Rust SDK for the ContextVM protocol — MCP over Nostr
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
================================================================
Files
================================================================

================
File: docs/getting-started/quick-overview.md
================
---
title: Quick Overview
description: An overview of the ContextVM documentation, including the specification and SDK documentation.
---

# Quick Overview

Welcome to the ContextVM documentation! This guide provides a brief overview of what you'll find in our documentation to help you get started with ContextVM.

## Documentation Structure

Our documentation is organized into several main sections:

### 🚀 Getting Started

- **Quick Overview**: This page - a brief introduction to what ContextVM offers

### 📋 Specification

- **[Specification](/spec/ctxvm-draft-spec)**: The official ContextVM draft specification detailing the protocol
- **[CEP - Guidelines](/spec/cep-guidelines)**: ContextVM Enhancement Proposal guidelines for contributing to the protocol

### 🛠️ ts-SDK

The TypeScript SDK provides tools and libraries for building applications with ContextVM:

- **[SDK Quick Overview](/ts-sdk/quick-overview)**: A comprehensive overview of the SDK's modules and core concepts
- **Core Concepts**: Fundamental definitions, constants, interfaces, and utilities
- **Transports**: Communication modules for MCP over Nostr
- **Components**: Gateway, Relay Handlers, Signers, and Proxy implementations
- **Tutorials**: Practical examples and guides

## What is ContextVM?

ContextVM is a protocol that bridges the Model Context Protocol (MCP) with the Nostr network, enabling decentralized communication. It allows MCP servers and clients to communicate over the Nostr protocol, leveraging its decentralized infrastructure for secure and private interactions.

## Key Features

- **Decentralized Communication**: Use Nostr's decentralized network for MCP communication
- **Security First**: Leveraging Nostr's cryptographic primitives for verification, authorization, and additional features
- **Easy Integration**: Typescript SDK to work with ContextVM

## Getting Started

1. **Read the Specification**: Start with the [ContextVM specification](/spec/ctxvm-draft-spec) to understand the protocol
2. **Explore the SDK**: Check out the [SDK Quick Overview](/ts-sdk/quick-overview) for development guidance
3. **Follow Tutorials**: Work through practical examples to see ContextVM in action

## Next Steps

Choose your path based on your interests:

- **Protocol Development**: Dive into the [Specification](/spec/ctxvm-draft-spec) to understand the protocol details
- **SDK Development**: Start with the [SDK Quick Overview](/ts-sdk/quick-overview) to begin building with ContextVM
- **Contributing**: Learn about contributing to the protocol with [CEP Guidelines](/spec/cep-guidelines)

For the latest updates and community discussions, visit our [GitHub repository](https://github.com/contextvm/).

================
File: docs/spec/ceps/cep-4.md
================
---
title: CEP-4 Encryption Support
description: End-to-end encryption for ContextVM messages using NIP-17 and NIP-59
---

# Encryption Support

**Status:** Final
**Author:** @contextvm-org
**Type:** Standards Track

## Abstract

This CEP proposes optional end-to-end encryption for ContextVM messages to enhance privacy and security. The encryption mechanism leverages a simplified version of NIP-17 (Private Direct Messages) for secure message encryption and NIP-59 (Gift Wrap) pattern with no 'rumor' using NIP-59 gift wrapping for metadata protection. This approach ensures message content privacy and metadata protection while maintaining full compatibility with the standard protocol.

## Specification

### Encryption Support Discovery

Encryption support is advertised through the `support_encryption` tag in server initialization responses or public server announcements. The presence of this tag indicates that the server supports encryption; its absence signifies that the server does not support encryption:

```json
{
  "pubkey": "<server-pubkey>",
  "content": {
    /* server details */
  },
  "tags": [
    ["support_encryption"] // Presence alone indicates encryption support
    // ... other tags
  ]
}
```

Clients can discover encryption support by:

1. **Direct Discovery**: Check for the presence of the `support_encryption` tag in initialization responses
2. **Encrypted Handshake**: Attempt an encrypted initialization

### Message Encryption Flow

When encryption is enabled, ContextVM messages follow a simplified NIP-17 pattern with no 'rumor', using NIP-59 gift wrapping.

#### 1. Content Preparation

The request is prepared as usual, and should be signed:

```json
{
  "kind": 25910,
  "id": "<request-event-id>",
  "pubkey": "<client-pubkey>",
  "content": {
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "get_weather",
      "arguments": {
        "location": "New York"
      }
    }
  },
  "tags": [["p", "<server-pubkey>"]],
  "sig": "<signature>"
}
```

#### 2. Seal Creation

The request is converted into a JSON string and encrypted to the recipient's public key, following NIP-44 encryption scheme.

#### 3. Gift Wrapping

The encrypted request is then gift-wrapped by placing it in the content field of a NIP-59 gift-wrap event.

```json
{
  "id": "<gift-wrap-hash>",
  "pubkey": "<random-pubkey>",
  "created_at": "<randomized-timestamp>",
  "kind": 1059,
  "tags": [["p", "<server-pubkey>"]],
  "content": "<nip44-encrypted-request>",
  "sig": "<random-key-signature>"
}
```

Server responses follow the same pattern.

The decrypted inner content contains the standard ContextVM response format. The id field used in responses should match the inner id field used in requests, not the id of the gift-wrap event.

#### Observations

While this encryption scheme is secure and private enough, it has a main limitation in metadata leakage protection, as the recipient's public key is added to the gift-wrap event as a `p` tag. Therefore, the only leaked metadata is the recipient's public key, but not the sender, the kind of event contained in the gift-wrap, or the timestamp of the event. This is a limitation of the NIP-59 gift-wrapping pattern.

## Backward Compatibility

This CEP introduces no breaking changes to the existing protocol. Encryption is entirely optional:

- **Existing servers** continue to work without modification
- **Existing clients** continue to work with existing servers
- **New encrypted communication** only occurs when both client and server support encryption

The only compatibility issue is that servers or clients might require encrypted communication. Therefore, if encryption is required and one of the participants does not support it, the communication will fail

## Reference Implementation

A reference implementation can be found in the [ContextVM sdk](https://github.com/ContextVM/sdk/blob/master/src/core/encryption.ts)

================
File: docs/spec/ceps/cep-6.md
================
---
title: CEP-6 Public Server Announcements
description: Public server discovery mechanism for ContextVM capabilities
---

# Public Server Announcements

**Status:** Final
**Author:** @contextvm-org
**Type:** Standards Track

## Abstract

This CEP proposes a public server discovery mechanism for ContextVM using Nostr replaceable events. The mechanism allows MCP servers to advertise their capabilities and metadata through the Nostr network, enabling clients to discover and browse available services without requiring prior knowledge of server public keys. This enhances discoverability while maintaining the decentralized nature of the protocol.

## Specification

### Overview

Public server announcements act as a service catalog, allowing clients or users to discover servers and their capabilities through replaceable events on the Nostr network. This mechanism provides an initial overview of what a server offers, and their public keys to connect with them.

Since each server is uniquely identified by its public key, the announcement events are replaceable (kinds 11316-11320), ensuring that only the most recent version of the server's information is active.

Providers announce their servers and capabilities by publishing events with kinds 11316 (server), 11317 (tools/list), 11318 (resources/list), 11319 (resource templates/list), and 11320 (prompts/list).

**Note:** The examples below present the `content` as a JSON object for readability; it must be stringified before inclusion in a Nostr event.

### Event Kinds for Server Announcements

| Kind  | Description             |
| ----- | ----------------------- |
| 11316 | Server Announcement     |
| 11317 | Tools List              |
| 11318 | Resources List          |
| 11319 | Resource Templates List |
| 11320 | Prompts List            |

### Server Announcement Event

```json
{
  "kind": 11316,
  "pubkey": "<provider-pubkey>",
  "content": {
    "protocolVersion": "2025-07-02",
    "capabilities": {
      "prompts": {
        "listChanged": true
      },
      "resources": {
        "subscribe": true,
        "listChanged": true
      },
      "tools": {
        "listChanged": true
      }
    },
    "serverInfo": {
      "name": "ExampleServer",
      "version": "1.0.0"
    },
    "instructions": "Optional instructions for the client"
  },
  "tags": [
    ["name", "Example Server"], // Optional: Human-readable server name
    ["about", "Server description"], // Optional: Server description
    ["picture", "https://example.com/server.png"], // Optional: Server icon/avatar URL
    ["website", "https://example.com"], // Optional: Server website
    ["support_encryption"] // Optional: Presence indicates server supports encrypted messages
  ]
}
```

#### Content Field Structure

The `content` field contains structured server information following the [MCP specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle#initialization), it should be a JSON string.

#### Tags Field Structure

The `tags` field provides additional metadata for discoverability:

- **name**: Human-readable server name
- **about**: Server description
- **picture**: URL to server icon/avatar
- **website**: Server website URL
- **support_encryption**: Indicates server supports encrypted messages

### Capability List Announcements

As in the Server Announcement event, the `content` field contains a JSON string with the list of capabilities. The list is the result of a call to the `list` method of each capability.

### Tools List Event Example

```json
{
  "kind": 11317,
  "pubkey": "<provider-pubkey>",
  "content": {
    "tools": [
      {
        "name": "get_weather",
        "description": "Get current weather information for a location",
        "inputSchema": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "City name or zip code"
            }
          },
          "required": ["location"]
        }
      }
    ]
  },
  "tags": []
}
```

### Discovery Process

#### Client Discovery Flow

1. **Subscribe to Server Announcement**: Clients subscribe to kinds 11316 (Server Announcement) on Nostr relays
2. **Subcribe to Capability List Announcements**: Once the server announcement is fetched and parsed, the client can subscribe to the capabilities events present in the server announcement.
3. **Initialize Connection**: Client proceeds with standard MCP initialization using the server's public key

An alternative flow is to subscribe to all announcements published by the server public key, and get all the public announcements at once, instead of first fetching the server announcement and then fetching the capabilities.

### Event Replacement Behavior

Since announcement events use kinds 11316-11320 (in the 10000-20000 range), they are replaceable:

- **Relay Behavior**: Relays store only the latest event for each combination of kind, and pubkey
- **Client Behavior**: Clients should always request the latest version of announcement events
- **Server Behavior**: Servers must update announcement events when capabilities change

## Reference Implementation

A reference implementation can be found in the [ContextVM SDK server transport implementation](https://github.com/ContextVM/sdk/blob/master/src/transport/nostr-server-transport.ts). It is implemented by calling the list methods from the transport during the initialization of the transport and then publishing the results of those list methods.

## Dependencies

- [CEP-4: Encryption Support](/spec/ceps/cep-4)

================
File: docs/spec/ceps/cep-8.md
================
---
title: CEP-8 Capability Pricing and Payment Flow
description: Pricing mechanism and payment processing for ContextVM capabilities
---

# Capability Pricing and Payment Flow

**Status:** Draft
**Author:** @Gzuuus
**Type:** Standards Track

## Abstract

This CEP proposes a standardized pricing mechanism and payment flow for MCP capabilities over ContextVM. The mechanism allows servers to advertise pricing for their capabilities, enables clients to discover and pay for these capabilities through various payment methods, and defines a notification system for payment requests. This creates a sustainable ecosystem for capability servers while maintaining the decentralized nature of the protocol.

## Specification

### Overview

ContextVM pricing for capabilities is implemented through a standardized mechanism with three main components:

1. **Pricing Tags**: Servers advertise pricing information using the `cap` tag
2. **Payment Method Identifiers (PMI)**: Both parties advertise supported payment methods using the `pmi` tag
3. **Payment Notifications**: Servers notify clients of payment requirements through the `notifications/payment_required` notification

When a capability requires payment, the server acts as the payment processor (generating and validating payment requests) while the client acts as the payment handler (executing payments for supported payment methods). Clients can discover supported payment methods beforehand through PMI discovery, enabling informed decisions before initiating requests.

### New Tags Introduced

This CEP introduces two new tags to the ContextVM protocol:

#### `cap` Tag

The `cap` tag is used to convey pricing information for capabilities. It follows this format:

```json
["cap", "<capability-identifier>", "<price>", "<currency-unit>"]
```

Where:

- `<capability-identifier>` is the name of the tool, prompt, or resource URI
- `<price>` is a string representing the numerical amount. For fixed prices, this is an integer (e.g., "100"). For variable prices, this can be a range (e.g., "100-1000") to indicate a variable pricing model.
- `<currency-unit>` is the currency symbol (e.g., "sats", "usd")

#### `pmi` Tag

The `pmi` tag is used to advertise supported Payment Method Identifiers. It follows this format:

```json
["pmi", "<payment-method-identifier>"]
```

Where `<payment-method-identifier>` is a standardized PMI string following the W3C Payment Method Identifiers specification (e.g., "bitcoin-lightning-bolt11", "bitcoin-cashu").

### Pricing Mechanism

Pricing information is advertised using the `cap` tag in server announcements and capability list responses:

#### Server Announcements

```json
{
  "kind": 11317,
  "content": {
    "tools": [
      {
        "name": "get_weather",
        "description": "Get current weather information"
        // ... other tool properties
      }
    ]
  },
  "tags": [["cap", "get_weather", "100", "sats"]]
}
```

#### Capability List Responses

```json
{
  "kind": 25910,
  "pubkey": "<provider-pubkey>",
  "content": {
    "result": {
      "tools": [
        {
          "name": "get_weather",
          "description": "Get current weather information"
          // ... other tool properties
        }
      ],
      "nextCursor": "next-page-cursor"
    }
  },
  "tags": [
    ["e", "<request-event-id>"],
    ["cap", "get_weather", "100", "sats"]
  ]
}
```

The `cap` tag indicates that using the `get_weather` tool costs 100 satoshis, allowing clients to display pricing to users.

### Payment Method Identifiers (PMI)

The protocol supports multiple payment methods through Payment Method Identifiers (PMI) that follow the W3C Payment Method Identifiers specification.

#### PMI Format and Registry

PMIs MUST follow the format defined by the [W3C Payment Method Identifiers](https://www.w3.org/TR/payment-method-id/) specification, matching the pattern: `[a-z0-9-]+` (e.g., `bitcoin-onchain`, `bitcoin-lightning-bolt11`, `bitcoin-cashu`, `basic-card`, etc).

**ContextVM PMI References:**

- `"bitcoin-onchain"` - Bitcoin on-chain transactions
- `"bitcoin-lightning-bolt11"` - Lightning Network with BOLT11 invoice format
- `"bitcoin-cashu"` - Bitcoin via Cashu ecash tokens

**Note:** The listed PMIs are reference recommendations for the ContextVM ecosystem. Users can use any PMI that follows the W3C format, propose new PMIs for inclusion, or extend the reference list over time.

#### PMI Benefits and Roles

Using standardized PMIs provides:

1. **Interoperability**: Clear communication about supported payment methods
2. **Extensibility**: Easy addition of new payment methods
3. **Multi-currency support**: Different PMIs handle different currencies and networks
4. **Clear separation of concerns**: Servers focus on payment processing, clients on payment handling

### PMI Discovery

PMI discovery allows clients and servers to determine compatibility with payment methods, similar to encryption support discovery in [CEP-4](/spec/ceps/cep-4).

#### PMI Advertisement

Servers advertise supported PMIs using the `pmi` tag in initialization responses or public announcements:

```json
{
  "pubkey": "<server-pubkey>",
  "content": {
    /* server details */
  },
  "tags": [
    ["pmi", "bitcoin-lightning-bolt11"],
    ["pmi", "bitcoin-cashu"],
    ["pmi", "bitcoin-onchain"]
  ]
}
```

Clients advertise their supported PMIs in initialization requests:

```json
{
  "kind": 25910,
  "content": {
    "jsonrpc": "2.0",
    "id": 0,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-07-02"
      // Other initialization parameters
    }
  },
  "tags": [
    ["p", "<server-pubkey>"],
    ["pmi", "bitcoin-lightning-bolt11"],
    ["pmi", "bitcoin-cashu"]
  ]
}
```

#### Discovery Methods

Clients can discover PMI support through:

1. **Public Announcements**: Check `pmi` tags in server announcements
2. **Initialization Responses**: Check `pmi` tags in server initialization responses
3. **Stateless Operations**: Handle compatibility at request time when no prior discovery is possible

Servers can discover PMI support through:

1. **Client Initialization Request**: Check `pmi` tags in client initialization request

### Payment Flow

The complete payment flow for a capability with pricing information follows these steps:

#### 1. Capability Request

The client sends a capability request to the server:

```json
{
  "kind": 25910,
  "id": "<request-event-id>",
  "pubkey": "<client-pubkey>",
  "content": {
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "get_weather",
      "arguments": {
        "location": "New York"
      }
    }
  },
  "tags": [["p", "<provider-pubkey>"]]
}
```

#### 2. Payment Required Notification

If the capability requires payment, the server responds with a `notifications/payment_required` notification containing payment details:

```json
{
  "kind": 25910,
  "pubkey": "<provider-pubkey>",
  "content": {
    "method": "notifications/payment_required",
    "params": {
      "amount": 1000,
      "pay_req": "lnbc...",
      "description": "Payment for tool execution",
      "pmi": "bitcoin-lightning-bolt11"
    }
  },
  "tags": [
    ["p", "<client-pubkey>"],
    ["e", "<request-event-id>"]
  ]
}
```

#### 3. Payment Processing

The client processes the payment and the server verifies it. When the client receives a payment request notification, it matches the PMI to determine if it supports the specified payment method. If compatible, the client processes the payment using the appropriate method for that PMI. The server verifies the payment according to the PMI implementation.

#### 4. Capability Access

Once payment is verified, the server processes the capability request and responds with the result:

```json
{
  "kind": 25910,
  "pubkey": "<provider-pubkey>",
  "content": {
    "jsonrpc": "2.0",
    "id": 2,
    "result": {
      "content": [
        {
          "type": "text",
          "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
        }
      ],
      "isError": false
    }
  },
  "tags": [["e", "<request-event-id>"]]
}
```

### Payment Request Notification Fields

The `notifications/payment_required` notification `params` object contains:

- `amount` (required): Numeric payment amount
- `pay_req` (required): Payment request data string
- `description` (optional): Human-readable payment description
- `pmi` (required): Payment Method Identifier string

## Backward Compatibility

This CEP introduces no breaking changes to the existing protocol:

- **Existing servers** can continue to operate without pricing
- **Existing clients** continue to work with existing servers
- **New pricing** is additive - capabilities can be free or paid
- **Optional participation**: Both providers and clients can choose to participate in pricing

## Reference Implementation

// TODO

## Dependencies

- [CEP-4: Encryption Support](/spec/ceps/cep-4)
- [CEP-6: Public Server Announcements](/spec/ceps/cep-6)
- [W3C Payment Method Identifiers](https://www.w3.org/TR/payment-method-id/)

================
File: docs/spec/cep-guidelines.md
================
---
title: ContextVM Enhancement Proposal Guidelines
description: Guidelines for proposing changes to the ContextVM protocol
---

# CEP Guidelines

> ContextVM Enhancement Proposal (CEP) guidelines for proposing changes to the ContextVM protocol

## What is a CEP?

CEP stands for ContextVM Enhancement Proposal. A CEP is a design document providing information to the ContextVM community, or describing a new feature for the ContextVM protocol or its processes or environment. The CEP should provide a concise technical specification of the feature and a rationale for the feature.

We intend CEPs to be the primary mechanisms for proposing major new features, for collecting community input on an issue, and for documenting the design decisions that have gone into ContextVM. The CEP author is responsible for building consensus within the community and documenting dissenting opinions.

Because the CEPs are maintained as text files in a versioned repository, their revision history is the historical record of the feature proposal.

## What qualifies a CEP?

The goal is to reserve the CEP process for changes that are substantial enough to require broad community discussion, a formal design document, and a historical record of the decision-making process. A regular GitHub issue or pull request is often more appropriate for smaller, more direct changes.

Consider proposing a CEP if your change involves any of the following:

- **A New Feature or Protocol Change**: Any change that adds, modifies, or removes features in the ContextVM protocol. This includes:
  - Adding new event kinds or Nostr integration patterns.
  - Changing the syntax or semantics of existing data structures or messages.
  - Introducing a new standard for interoperability between different ContextVM-compatible tools.
  - Significant changes to how the specification itself is defined, presented, or validated.
- **A Breaking Change**: Any change that is not backwards-compatible.
- **A Change to Governance or Process**: Any proposal that alters the project's decision-making, contribution guidelines (like this document itself).
- **A Complex or Controversial Topic**: If a change is likely to have multiple valid solutions or generate significant debate, the CEP process provides the necessary framework to explore alternatives, document the rationale, and build community consensus before implementation begins.

## CEP Types

There are three kinds of CEP:

1. **Standards Track** CEP describes a new feature or implementation for the ContextVM protocol. Standards Track CEPs are maintained as separate documents from the main ContextVM specification and extend or enhance the base protocol. The main specification maintains references to all accepted and finalized Standards Track CEPs.

2. **Informational** CEP describes a ContextVM protocol design issue, or provides general guidelines or information to the ContextVM community, but does not propose a new feature. Informational CEPs do not necessarily represent a ContextVM community consensus or recommendation.

3. **Process** CEP describes a process surrounding ContextVM, or proposes a change to (or an event in) a process. Process CEPs are like Standards Track CEPs but apply to areas other than the ContextVM protocol itself.

## Submitting a CEP

The CEP process begins with a new idea for the ContextVM protocol. It is highly recommended that a single CEP contain a single key proposal or new idea. Small enhancements or patches often don't need a CEP and can be injected into the ContextVM development workflow with a pull request to the ContextVM repo. The more focused the CEP, the more successful it tends to be.

Each CEP must have an **CEP author** -- someone who writes the CEP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The CEP author should first attempt to ascertain whether the idea is CEP-able. Posting to the ContextVM community forums (Nostr, Signal, GitHub Discussions) is the best way to go about this.

**Important Note**: The CEP process uses both GitHub Issues and Pull Requests:

- **GitHub Issues** are used for discussion, review, and tracking the CEP proposal lifecycle
- **Pull Requests** are normally used for Standards Track CEPs to contain the actual CEP document and specification changes

### CEP Workflow

CEPs should be submitted as a GitHub Issue in the [ContextVM-docs repository](https://github.com/ContextVM/contextvm-docs). The standard CEP workflow varies slightly depending on the CEP type:

#### For Standards Track CEPs

1. You, the CEP author, create a [well-formatted](#cep-format) GitHub Issue with the `CEP` and `proposal` tags. The CEP number is the same as the GitHub Issue number, the two can be used interchangeably.
2. **Simultaneously**, create a Pull Request that adds a markdown document draft in the `ceps` directory. This PR should contain the focused specification sections following the [CEP Format](#cep-format) structure. Link to this PR in your GitHub Issue.

**Important**: The GitHub Issue and Pull Request serve different purposes and contain different content:

- **GitHub Issue**: Initially contains the comprehensive CEP proposal including all sections (abstract, motivation, rationale, specification, security implications, etc.). This is where community discussion happens. Once a Pull Request is opened, the specification section in the issue should be replaced with a link to the PR to avoid redundancy.
- **Pull Request**: Contains only the specification-related sections (abstract, specification, backwards compatibility, reference implementation, and dependencies) that will become part of the final specification document. The PR should focus exclusively on technical specification content.

3. Find a Maintainer to sponsor your proposal. Maintainers will regularly go over the list of open proposals to determine which proposals to sponsor. You can tag relevant maintainers in your proposal.
4. Once a sponsor is found, the GitHub Issue is assigned to the sponsor. The sponsor will add the `draft` tag.
5. The sponsor will informally review both the Issue and the Pull Request, and may request changes based on community feedback. When ready for formal review, the sponsor will add the `in-review` tag.
6. After the `in-review` tag is added, the CEP enters formal review by the Maintainers. The CEP may be accepted, rejected, or returned for revision.
7. If the CEP has not found a sponsor within three months, Maintainers may close the CEP as `dormant`.

#### For Informational and Process CEPs

1. You, the CEP author, create a [well-formatted](#cep-format) GitHub Issue with the `CEP` and `proposal` tags. The CEP number is the same as the GitHub Issue number, the two can be used interchangeably.
2. Find a Maintainer to sponsor your proposal. Maintainers will regularly go over the list of open proposals to determine which proposals to sponsor. You can tag relevant maintainers in your proposal.
3. Once a sponsor is found, the GitHub Issue is assigned to the sponsor. The sponsor will add the `draft` tag, ensure the CEP number is in the title, and assign a milestone.
4. The sponsor will informally review the proposal and may request changes based on community feedback. When ready for formal review, the sponsor will add the `in-review` tag.
5. After the `in-review` tag is added, the CEP enters formal review by the Maintainers. The CEP may be accepted, rejected, or returned for revision.
6. If the CEP has not found a sponsor within three months, Maintainers may close the CEP as `dormant`.

### CEP Format

Each CEP should have the following parts. For Standards Track CEPs, these sections are distributed between the GitHub Issue and Pull Request as described below:

#### GitHub Issue Content (for discussion and review):

1. **Preamble** -- A short descriptive title, the names and contact info for each author, the current status.
2. **Abstract** -- A short (~200 word) description of the technical issue being addressed.
3. **Motivation** -- The motivation should clearly explain why the existing protocol specification is inadequate to address the problem that the CEP solves. The motivation is critical for CEPs that want to change the ContextVM protocol. CEP submissions without sufficient motivation may be rejected outright.
4. **Rationale** -- The rationale explains why particular design decisions were made. It should describe alternate designs that were considered and related work. The rationale should provide evidence of consensus within the community and discuss important objections or concerns raised during discussion.
5. **Security Implications** -- If there are security concerns in relation to the CEP, those concerns should be explicitly written out to make sure reviewers of the CEP are aware of them.
6. **Specification** -- Initially, this section should contain the technical specification describing syntax and semantics of any new protocol feature. Once a Pull Request is opened, this section should be replaced with a link to the PR to avoid duplication.

#### Pull Request Content (for specification - Standards Track CEPs only):

1. **Preamble** -- A short descriptive title, the names and contact info for each author, the current status.
2. **Abstract** - A short (~200 word) description of the technical issue being addressed (can reference the Issue for full details)
3. **Specification** - The technical specification should describe the syntax and semantics of any new protocol feature. The specification should be detailed enough to allow competing, interoperable implementations. For Standards Track CEPs, this should include the actual changes to the specification files in the Pull Request.
4. **Backward Compatibility** - All CEPs that introduce backward incompatibilities must include a section describing these incompatibilities and their severity. The CEP must explain how the author proposes to deal with these incompatibilities.
5. **Dependencies** - For Standards Track CEPs, this section should list any CEPs that this proposal depends on. Each dependency should be listed with its CEP number and a brief description of how it relates to the current proposal. This helps maintain a clear dependency map and ensures proper implementation order.
6. **Reference Implementation** - The reference implementation must be completed before any CEP is given status "Final", but it need not be completed before the CEP is accepted. While there is merit to the approach of reaching consensus on the specification and rationale before writing code, the principle of "rough consensus and running code" is still useful when it comes to resolving many discussions of protocol details.

**Important**: Once a Pull Request is open, the GitHub Issue's "Specification" section should be updated to simply link to the PR. This ensures the technical specification is maintained in a single location (the PR) while keeping the issue focused on discussion and consensus building.

### Main Specification Integration

Once a Standards Track CEP reaches "Accepted" status, it should be referenced in the main ContextVM specification document. When a CEP reaches "Final" status, the main specification should be updated to include a link to the finalized CEP document.

This ensures that the main specification maintains an up-to-date record of all protocol extensions and enhancements.

### CEP States

CEPs can be one one of the following states:

- `proposal`: CEP proposal without a sponsor.
- `draft`: CEP proposal with a sponsor.
- `in-review`: CEP proposal ready for review.
- `accepted`: CEP accepted by Maintainers, but still requires final wording and reference implementation.
- `rejected`: CEP rejected by Maintainers.
- `withdrawn`: CEP withdrawn.
- `final`: CEP finalized.
- `superseded`: CEP has been replaced by a newer CEP.
- `dormant`: CEP that has not found sponsors and was subsequently closed.

### CEP Review & Resolution

CEPs are reviewed by the ContextVM Maintainers on a regular basis.

For a CEP to be accepted it must meet certain minimum criteria:

- A prototype implementation demonstrating the proposal
- Clear benefit to the ContextVM ecosystem
- Community support and consensus

Once a CEP has been accepted, the reference implementation must be completed. When the reference implementation is complete and incorporated into the main source code repository, the status will be changed to "Final".

A CEP can also be "Rejected" or "Withdrawn". A CEP that is "Withdrawn" may be re-submitted at a later date.

## Reporting CEP Bugs, or Submitting CEP Updates

How you report a bug, or submit a CEP update depends on several factors, such as the maturity of the CEP, the preferences of the CEP author, and the nature of your comments. For CEPs not yet reaching `final` state, it's probably best to send your comments and changes directly to the CEP author. Once CEP is finalized, you may want to submit corrections as a GitHub comment on the issue or pull request to the reference implementation.

## Transferring CEP Ownership

It occasionally becomes necessary to transfer ownership of CEPs to a new CEP author. In general, we'd like to retain the original author as a co-author of the transferred CEP, but that's really up to the original author. A good reason to transfer ownership is when the original author no longer has the time or interest in updating it or following through with the CEP process, or has become unreachable (not responding to email). A bad reason to transfer ownership is when you don't agree with the direction of the CEP. We try to build consensus around a CEP, but if that's not possible, you can always submit a competing CEP.

================
File: docs/spec/ctxvm-draft-spec.md
================
---
title: ContextVM Protocol Specification
description: Technical specification for the ContextVM protocol
---

**Status:** Draft

## Abstract

The Context Vending Machine (ContextVM) specification defines how the Nostr protocol can be used as a transport layer for the Model Context Protocol (MCP), leveraging the Nostr relay network as the underlying communication mechanism. Also benefiting from Nostr's cryptographic primitives for verification, authorization, and additional features.

## Table of Contents

- [Introduction](#introduction)
  - [ContextVM as MCP Transport](#contextvm-as-mcp-transport)
  - [Public Key Cryptography](#public-key-cryptography)
- [Protocol Overview](#protocol-overview)
  - [Main Actors](#main-actors)
  - [Transport Layer Architecture](#transport-layer-architecture)
  - [Message Structure](#message-structure)
- [Event Kinds](#event-kinds)
- [Server Discovery](#server-discovery)
  - [Client Initialization Request](#client-initialization-request)
  - [Server Initialization Response](#server-initialization-response)
  - [Client Initialized Notification](#client-initialized-notification)
- [Capability Operations](#capability-operations)
  - [List Operations](#list-operations)
    - [List Request Template](#list-request-template)
    - [List Response Template](#list-response-template)
  - [Capability-Specific Item Examples](#capability-specific-item-examples)
    - [Call Tool Request](#call-tool-request)
    - [Call Tool Response](#call-tool-response)
- [Notifications](#notifications)
- [ContextVM Enhancement Proposals (CEPs)](#contextvm-enhancement-proposals-ceps)
- [Complete Protocol Flow](#complete-protocol-flow)

## Introduction

The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) defines a standardized way for servers to expose capabilities and for clients to consume them. MCP is transport-agnostic, meaning it can operate over various communication channels. The Context Vending Machine (ContextVM) specification defines a Nostr-based transport layer for MCP, and some conventions on top for enabling secure, decentralized communication between MCP servers and clients.

### ContextVM as MCP Transport

ContextVM operates at the **transport layer** of MCP, providing a Nostr-based implementation that:

- **Transports MCP messages** through Nostr's relay network
- **Preserves JSON-RPC semantics** while leveraging Nostr's event structure
- **Adds cryptographic verification** and metadata capabilities to standard MCP communication
- **Enables decentralized service discovery** and communication without centralized infrastructure

This approach allows MCP servers and clients to communicate through Nostr while maintaining full compatibility with the MCP specification and gaining the benefits of Nostr's cryptographic security model.

### Public Key Cryptography

ContextVM leverages Nostr's public key cryptography to ensure message authenticity and integrity:

1. **Message Verification**: Every message is cryptographically signed by the sender's private key and can be verified using their public key, ensuring that:
   - Server announcements are legitimate
   - Client requests are from authorized users
   - Responses are from the expected servers

2. **Identity Management**: Public keys serve as persistent identifiers for all actors in the system:
   - Servers can maintain consistent identities across relays
   - Clients can be uniquely identified for authorization purposes

The cryptographic properties enable secure authorization flows for capability execution without requiring centralized authentication services.

## Protocol Overview

### Transport Layer Architecture

ContextVM operates as a transport layer for MCP, meaning it handles the communication channel while preserving the semantics of MCP messages. The architecture consists of:

1. **Transport Layer**: Nostr events and relays serve as the transport mechanism
2. **Message Layer**: JSON-RPC MCP messages are embedded within Nostr event content
3. **Metadata Layer**: Nostr event tags provide addressing and correlation information

This layered approach allows ContextVM to:

- Transport standard MCP messages without modification
- Add Nostr-specific addressing and verification
- Maintain compatibility with existing MCP implementations

### Message Structure

The protocol uses these key design principles for message handling:

1. **Content Field Structure**: The `content` field of Nostr events contains stringified MCP messages. All MCP message structures are preserved exactly as defined in the MCP specification, ensuring compatibility with standard MCP clients and servers.

2. **Nostr Metadata in Tags**: All Nostr-specific metadata uses event tags:
   - `p`: Public key for addressing servers or clients
   - `e`: Event ID references for correlating requests and responses

3. **Unified Event Kind**: ContextVM uses a single event kind for all communication:
   - `25910`: All ContextVM messages (ephemeral events)

   The event kind follows Nostr's conventions in [NIP-01](https://github.com/nostr-protocol/nips/blob/master/01.md#kinds):
   - For kind n such that 20000 <= n < 30000, events are ephemeral, which means they are not expected to be stored by relays for a long period, but rather just transmitted.

### Main Actors

There are three main actors in ContextVM architecture:

- **Servers**: MCP servers exposing capabilities, using a public key to sign messages
- **Relays**: Core component of the Nostr protocol that enables communication between clients and servers
- **Clients**: MCP or Nostr clients that discover and consume capabilities from servers, using a public key to sign messages

## Server Discovery

You can connect to MCP servers using ContextVM by knowing their public key and the relay(s) they are listening on. This process follows the standard MCP initialization specification, with ContextVM providing the transport mechanism by embedding JSON-RPC MCP messages in the `content` field of Nostr events.

**Note:** The content field of ContextVM events contains stringified MCP messages. The examples below present the content as a JSON object for readability; it must be stringified before inclusion in a Nostr event.

#### Client Initialization Request

```json
{
  "kind": 25910,
  "content": {
    "jsonrpc": "2.0",
    "id": 0,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-07-02",
      "capabilities": {
        "roots": {
          "listChanged": true
        },
        "sampling": {}
      },
      "clientInfo": {
        "name": "ExampleClient",
        "version": "1.0.0"
      }
    }
  },
  "tags": [["p", "<server-pubkey>"]]
}
```

- Tags:
  - `p`: Server public key

#### Server Initialization Response

```json
{
  "kind": 25910,
  "pubkey": "<server-pubkey>",
  "content": {
    "jsonrpc": "2.0",
    "id": 0,
    "result": {
      "protocolVersion": "2025-07-02",
      "capabilities": {
        "logging": {},
        "prompts": {
          "listChanged": true
        },
        "resources": {
          "subscribe": true,
          "listChanged": true
        },
        "tools": {
          "listChanged": true
        }
      },
      "serverInfo": {
        "name": "ExampleServer",
        "version": "1.0.0"
      },
      "instructions": "Optional instructions for the client"
    }
  },
  "tags": [["e", "<client-init-request-id>"]]
}
```

- Tags:
  - `e`: Reference to the client's initialization request event

#### Client Initialized Notification

After receiving the server initialization response, the client MUST send an initialized notification to indicate it is ready to begin normal operations:

```json
{
  "kind": 25910,
  "pubkey": "<client-pubkey>",
  "content": {
    "jsonrpc": "2.0",
    "method": "notifications/initialized"
  },
  "tags": [
    ["p", "<provider-pubkey>"] // Required: Target provider public key
  ]
}
```

This notification completes the initialization process and signals to the server that the client has processed the server's capabilities and is ready to begin normal operations.

**Note:** The initialization process is not required for ContextVM servers to operate as they can work in a stateless fashion. However, it is recommended to use it to ensure that the server is ready to accept requests from clients.

## Capability Operations

After initialization, clients can interact with server capabilities.

### List Operations

All list operations follow the same structure described by MCP, with the specific capability type indicated in the method name.

- Tags:
  - `p`: Provider public key

#### List Request Template

```json
{
  "kind": 25910,
  "pubkey": "<client-pubkey>",
  "id": "<request-event-id>",
  "content": {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "<capability>/list", // tools/list, resources/list, or prompts/list
    "params": {
      "cursor": "optional-cursor-value"
    }
  },
  "tags": [
    ["p", "<provider-pubkey>"] // Required: Provider's public key
  ]
}
```

#### List Response Template

```json
{
  "kind": 25910,
  "pubkey": "<provider-pubkey>",
  "content": {
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
      "<items>": [
        // "tools", "resources", or "prompts" based on capability
        // Capability-specific item objects
      ],
      "nextCursor": "next-page-cursor"
    }
  },
  "tags": [
    ["e", "<request-event-id>"] // Required: Reference to the request event
  ]
}
```

### Capability-Specific Item Examples

#### Call Tool Request

```json
{
  "kind": 25910,
  "id": "<request-event-id>",
  "pubkey": "<client-pubkey>",
  "content": {
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "get_weather",
      "arguments": {
        "location": "New York"
      }
    }
  },
  "tags": [["p", "<provider-pubkey>"]]
}
```

#### Call Tool Response

```json
{
  "kind": 25910,
  "pubkey": "<provider-pubkey>",
  "content": {
    "jsonrpc": "2.0",
    "id": 2,
    "result": {
      "content": [
        {
          "type": "text",
          "text": "Current weather in New York:\nTemperature: 72°F\nConditions: Partly cloudy"
        }
      ],
      "isError": false
    }
  },
  "tags": [["e", "<request-event-id>"]]
}
```

For other capabilities (resources, prompts, completions, ping, etc.), the `content` field follows the same pattern as other MCP messages, containing a stringified JSON-RPC object that adheres to the MCP specification.

## Notifications

All notifications in ContextVM follow the standard MCP notification format and conventions, using the unified kind 25910 event type. This includes notifications for payment requests, progress updates, and all other server-to-client or client-to-server communications.

Notifications are constructed according to the standard MCP notification template.

## ContextVM Enhancement Proposals (CEPs)

The ContextVM protocol is subject to ongoing improvements and enhancements. These improvements are managed through the ContextVM Enhancement Proposal (CEP) process, which is described in detail in the [CEP Guidelines](https://docs.contextvm.org/spec/cep-guidelines/)

### Accepted CEPs

The following CEPs have been accepted:

### Final CEPs

The following CEPs have been finalized:

- [CEP-4: Encryption Support](/spec/ceps/cep-4)
- [CEP-6: Public Server Announcements](/spec/ceps/cep-6)

## Complete Protocol Flow

```mermaid
sequenceDiagram
    participant MCP Client
    participant Relays
    participant MCP Server

    note over MCP Client, MCP Server: MCP Initialization over Relays

    MCP Client->>Relays: Publish kind 25910 (initialize request)
    Relays->>MCP Server: Deliver MCP initialize message
    MCP Server->>Relays: Publish kind 25910 (initialize response)
    Relays-->>MCP Client: Deliver MCP initialize response

    MCP Client->>Relays: Publish kind 25910 (initialized notification)
    Relays->>MCP Server: Deliver MCP initialized notification

    note over MCP Client, MCP Server: MCP Capability Operations over Relays

    MCP Client->>Relays: Publish kind 25910 (tools/list request)
    Relays->>MCP Server: Deliver MCP tools/list request
    MCP Server->>Relays: Publish kind 25910 (tools/list response)
    Relays-->>MCP Client: Deliver MCP tools/list response
```

================
File: docs/ts-sdk/core/constants.md
================
---
title: Constants
description: A set of constants used throughout the @contextvm/sdk.
---

# Constants

The `@contextvm/sdk` exports a set of constants that are used throughout the library for event kinds, tags, and other protocol-specific values. These constants ensure consistency and alignment with the ContextVM specification.

## Event Kinds

The ContextVM protocol defines several Nostr event kinds for different types of messages.

| Constant                      | Kind  | Description                                                                   |
| ----------------------------- | ----- | ----------------------------------------------------------------------------- |
| `CTXVM_MESSAGES_KIND`         | 25910 | The kind for standard, ephemeral ContextVM messages.                          |
| `GIFT_WRAP_KIND`              | 1059  | The kind for encrypted messages, wrapped using the NIP-59 gift wrap standard. |
| `SERVER_ANNOUNCEMENT_KIND`    | 11316 | A replaceable event for announcing a server's presence and basic info.        |
| `TOOLS_LIST_KIND`             | 11317 | A replaceable event for listing a server's available tools.                   |
| `RESOURCES_LIST_KIND`         | 11318 | A replaceable event for listing a server's available resources.               |
| `RESOURCETEMPLATES_LIST_KIND` | 11319 | A replaceable event for listing a server's available resource templates.      |
| `PROMPTS_LIST_KIND`           | 11320 | A replaceable event for listing a server's available prompts.                 |

## Nostr Tags

The SDK defines an object `NOSTR_TAGS` that contains constants for the various Nostr event tags used in the ContextVM protocol.

| Key                  | Tag                  | Description                                                            |
| -------------------- | -------------------- | ---------------------------------------------------------------------- |
| `PUBKEY`             | `p`                  | The public key of the message recipient.                               |
| `EVENT_ID`           | `e`                  | The event ID used to correlate requests and responses.                 |
| `CAPABILITY`         | `cap`                | A tag for specifying pricing metadata for a tool, resource, or prompt. |
| `NAME`               | `name`               | The human-readable name of a server in an announcement.                |
| `WEBSITE`            | `website`            | The URL of a server's website in an announcement.                      |
| `PICTURE`            | `picture`            | The URL of a server's icon in an announcement.                         |
| `ABOUT`              | `about`              | A tag for providing a short description of a server.                   |
| `SUPPORT_ENCRYPTION` | `support_encryption` | A tag indicating that a server supports end-to-end encryption.         |

## Announcement Methods

The `announcementMethods` object maps capability types to their corresponding MCP method names for server announcements.

```typescript
export const announcementMethods = {
  server: "initialize",
  tools: "tools/list",
  resources: "resources/list",
  resourceTemplates: "resources/templates/list",
  prompts: "prompts/list",
} as const;
```

This object is used internally by the `NostrServerTransport` to construct announcement events.

## Next Steps

With a solid understanding of the core modules, you are now ready to explore the **[Transports](/transports/base-nostr-transport)**, which are responsible for all network communication in the SDK.

================
File: docs/ts-sdk/core/encryption.md
================
---
title: Encryption
description: An overview of the encryption mechanism in the @contextvm/sdk.
---

# Encryption

The `@contextvm/sdk` supports optional end-to-end encryption for all communication, providing enhanced privacy and security. This section explains the encryption mechanism, how to enable it, and the underlying principles.

## Overview

ContextVM's encryption leverages a simplified version of [NIP-17](https://github.com/nostr-protocol/nips/blob/master/17.md) to ensure:

1.  **Message Content Privacy**: All MCP message content is encrypted using NIP-44.
2.  **Metadata Protection**: The gift wrap pattern conceals participant identities and other metadata.
3.  **Selective Encryption**: Clients and servers can negotiate encryption on a per-session basis.

When encryption is enabled, all ephemeral messages (kind 25910) are wrapped in a kind 1059 gift wrap event. Server announcements and capability lists remain unencrypted for public discoverability.

## How It Works

The encryption flow is designed to be secure and efficient:

1.  **Content Preparation**: The original MCP message is serialized into a standard Nostr event.
2.  **Gift Wrapping**: The entire event is then encrypted using `nip44.v2` and wrapped inside a "gift wrap" event (kind 1059). A new, random keypair is generated for each gift wrap.
3.  **Transmission**: The encrypted gift wrap event is published to the Nostr network.

The recipient then unwraps the gift using their private key to decrypt the original message.

### Why a Simplified NIP-17/NIP-59 Pattern?

The standard implementation of NIP-17 is designed for persistent private messages and includes a "rumor" and "seal" mechanism to prevent message leakage. Since ContextVM messages are ephemeral and not intended to be stored by relays, this complexity is unnecessary. The SDK uses a more direct gift-wrapping approach that provides strong encryption and metadata protection without the overhead of the full NIP-17 standard.

## Enabling Encryption

Encryption is configured at the transport level using the `EncryptionMode` enum. You can set the desired mode when creating a `NostrClientTransport` or `NostrServerTransport`.

```typescript
import { NostrClientTransport } from "@contextvm/sdk";
import { EncryptionMode } from "@contextvm/sdk";

const transport = new NostrClientTransport({
  // ... other options
  encryptionMode: EncryptionMode.OPTIONAL, // or REQUIRED, DISABLED
});
```

### `EncryptionMode`

- **`REQUIRED`**: The transport will only communicate with peers that support encryption. If the other party does not support it, the connection will fail.
- **`OPTIONAL`**: (Default) The transport will attempt to use encryption if the peer supports it. If not, it will fall back to unencrypted communication.
- **`DISABLED`**: The transport will not use encryption, even if the peer supports it.

## Encryption Support Discovery

Clients and servers can discover if a peer supports encryption in two ways:

1.  **Server Announcements**: Public server announcements (kind 11316) include a `support_encryption` tag to indicate that the server is capable of encrypted communication.
2.  **Initialization Handshake**: During the MCP initialization process, both the client and server can signal their support for encryption.

## API Reference

The core encryption functions are exposed in the `core` module:

- `encryptMessage(message: string, recipientPublicKey: string): NostrEvent`
- `decryptMessage(event: NostrEvent, signer: NostrSigner): Promise<string>`

These functions handle the low-level details of gift wrapping and unwrapping, but in most cases, you will interact with encryption through the transport's `encryptionMode` setting.

## Next Steps

Now that you understand how encryption works, let's look at the [Constants](/core/constants) used throughout the SDK.

================
File: docs/ts-sdk/core/interfaces.md
================
---
title: Interfaces
description: A deep dive into the core interfaces used in the @contextvm/sdk.
---

# Core Interfaces

The `@contextvm/sdk` is designed with a modular and extensible architecture, centered around a set of core interfaces. These interfaces define the essential components for signing, relay management, and communication.

## `NostrSigner`

The `NostrSigner` interface is fundamental for cryptographic operations within the SDK. It abstracts the logic for signing Nostr events, ensuring that all communications are authenticated and verifiable.

### Definition

```typescript
export interface NostrSigner {
  getPublicKey(): Promise<string>;
  signEvent(event: EventTemplate): Promise<NostrEvent>;

  // Optional NIP-04 encryption support (deprecated)
  nip04?: {
    encrypt: (pubkey: string, plaintext: string) => Promise<string>;
    decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
  };

  // Optional NIP-44 encryption support
  nip44?: {
    encrypt: (pubkey: string, plaintext: string) => Promise<string>;
    decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
  };
}
```

Any object that implements this interface can be used to sign events, allowing you to integrate with various key management systems, such as web, hardware wallets or remote signing services. The SDK provides a default implementation, `PrivateKeySigner`, which signs events using a raw private key.

- **Learn more:** [`NostrSigner` Deep Dive](/signer/nostr-signer-interface/)
- **Default Implementation:** [`PrivateKeySigner`](/signer/private-key-signer/)

## `RelayHandler`

The `RelayHandler` interface manages interactions with Nostr relays. It is responsible for subscribing to events and publishing events to the Nostr network.

### Definition

```typescript
export interface RelayHandler {
  connect(): Promise<void>;
  disconnect(relayUrls?: string[]): Promise<void>;
  publish(event: NostrEvent): Promise<void>;
  subscribe(
    filters: Filter[],
    onEvent: (event: NostrEvent) => void,
    onEose?: () => void,
  ): Promise<void>;
  unsubscribe(): void;
}
```

By implementing this interface, you can create custom relay management logic, such as sophisticated relay selection strategies or custom reconnection policies. The SDK includes `SimpleRelayPool` as a default implementation.

- **Learn more:** [`RelayHandler` Deep Dive](/relay/relay-handler-interface)
- **Default Implementation:** [`SimpleRelayPool`](/relay/simple-relay-pool)

## `EncryptionMode`

The `EncryptionMode` enum defines the encryption policy for a transport.

```typescript
export enum EncryptionMode {
  OPTIONAL = "optional",
  REQUIRED = "required",
  DISABLED = "disabled",
}
```

This enum is used to configure the encryption behavior of the `NostrClientTransport` and `NostrServerTransport`.

- **Learn more:** [Encryption](/core/encryption)

## `ServerInfo`

The `ServerInfo` interface provides metadata about a server, used by the Nostr server transport to add metadata to server announcements.

### Definition

```typescript
export interface ServerInfo {
  name?: string;
  picture?: string;
  website?: string;
  about?: string;
}
```

This interface allows servers to include descriptive information in their announcements, making them more discoverable and providing users with context about the server's purpose and identity.

- **name**: A human-readable name for the server
- **picture**: URL to an image representing the server
- **website**: The server's official website or repository
- **about**: A description of the server's purpose or content

================
File: docs/ts-sdk/core/logging.md
================
---
title: Logging
description: Logging in the @contextvm/sdk
---

### Logging

The SDK uses Pino for high-performance logging with structured JSON output. By default, logs are written to stderr to comply with the MCP protocol expectations.

#### Basic Usage

[`typescript`](src/content/docs/ts-sdk/core/logging.md:10)

```typescript
import { createLogger } from "@contextvm/sdk/core";

// Create a logger for your module
const logger = createLogger("my-module");

logger.info("Application started");
logger.error("An error occurred", { error: "details" });
```

#### Configuration Options

[`typescript`](src/content/docs/ts-sdk/core/logging.md:20)

```typescript
import { createLogger, LoggerConfig } from "@contextvm/sdk/core";

const config: LoggerConfig = {
  level: "debug", // Minimum log level (debug, info, warn, error)
  file: "app.log", // Optional: log to a file instead of stderr
};

const logger = createLogger("my-module", config);
```

**Note:** Pretty printing is automatically enabled when logs are written to stderr/stdout (not to a file) for better readability during development.

#### Configuring with Environment Variables

The logger can be configured using environment variables, which is useful for adjusting log output without changing the code.

- **`LOG_LEVEL`**: Sets the minimum log level.
  - **Values**: `debug`, `info`, `warn`, `error`.
  - **Default**: `info`.
- **`LOG_DESTINATION`**: Sets the log output destination.
  - **Values**: `stderr` (default), `stdout`, or `file`.
- **`LOG_FILE`**: Specifies the file path when `LOG_DESTINATION` is `file`.
- **`LOG_ENABLED`**: Enables or disables logging.
  - **Values**: `true` (default) or `false`.

##### Configuration in Node.js

[`bash`](src/content/docs/ts-sdk/core/logging.md:49)

```bash
# Set log level to debug
LOG_LEVEL=debug node app.js

# Log to a file instead of the console
LOG_DESTINATION=file LOG_FILE=./app.log node app.js

# Disable logging entirely
LOG_ENABLED=false node app.js
```

##### Configuration in Browsers

[`javascript`](src/content/docs/ts-sdk/core/logging.md:63)

```javascript
// Set this in a <script> tag in your HTML or at the top of your entry point
window.LOG_LEVEL = "debug";

// Now, when you import and use the SDK, it will use the 'debug' log level.
import { logger } from "@contextvm/sdk";
logger.debug("This is a debug message.");
```

#### Module-specific Loggers

[`typescript`](src/content/docs/ts-sdk/core/logging.md:75)

```typescript
const baseLogger = createLogger("my-app");
const authLogger = baseLogger.withModule("auth");
const dbLogger = baseLogger.withModule("database");

authLogger.info("User login attempt");
dbLogger.debug("Query executed", { query: "SELECT * FROM users" });
```

#### Conventions and Best Practices

- Log levels:
  - debug: detailed developer-oriented information (traces, SQL queries, internal state).
  - info: high-level lifecycle events and successful operations (startup, shutdown, user actions).
  - warn: unexpected situations that don't stop execution but may need attention.
  - error: failures that require investigation (exceptions, failed requests).
- Use structured fields to add context instead of human-parsed messages. Preferred field names:
  - `module`: module or component name (string).
  - `event`: short event name (string).
  - `txId` / `traceId`: request or trace identifier (string).
  - `userId`: authenticated user id when applicable (string).
  - `durationMs`: operation duration in milliseconds (number).
  - `error`: when logging errors, include an `error` object with `message` and `stack`.
- Avoid logging sensitive data (passwords, secrets, full tokens). Redact or hash when necessary.
- Keep log messages concise and use structured metadata for details.
- Prefer logger.method(message, meta) over string interpolation that embeds structured data into the message.

#### Examples (Best Practice)

[`typescript`](src/content/docs/ts-sdk/core/logging.md:105)

```typescript
logger.info("payment.processed", {
  module: "payments",
  txId: "abcd-1234",
  userId: "user-42",
  amount: 1999,
  currency: "EUR",
  durationMs: 245,
});

try {
  // do something that throws
} catch (err) {
  logger.error("payment.failed", {
    module: "payments",
    txId: "abcd-1234",
    error: { message: err.message, stack: err.stack },
  });
}
```

#### Performance and Safety

- The SDK logger is optimized for minimal allocations. Prefer structured objects over building large strings.
- When logging high-frequency events, consider using lower log levels (info -> debug) or sampling.
- Ensure log files are rotated and monitored if using file destinations.

---

See also: [`src/content/docs/ts-sdk/core/interfaces.md`](src/content/docs/ts-sdk/core/interfaces.md:1)

================
File: docs/ts-sdk/gateway/overview.md
================
---
title: Gateway Overview
description: Understanding the NostrMCPGateway component for bridging MCP and Nostr
---

# Gateway

The `NostrMCPGateway` is a server-side bridging component that exposes a traditional MCP server to the Nostr network. It acts as a gateway, translating communication between Nostr-based clients and a standard MCP server.

## Purpose and Capabilities

The gateway manages two transports simultaneously:

1.  **Nostr Server Transport**: A [`NostrServerTransport`](/transports/nostr-server-transport) that listens for incoming connections from clients on the Nostr network.
2.  **MCP Server Transport**: A standard MCP client transport (like `StdioClientTransport`) that connects to a local or remote MCP server.

The gateway's role is to forward requests from Nostr clients to the MCP server and relay the server's responses back to the appropriate client on Nostr.

## Integration Scenarios

The `NostrMCPGateway` is ideal for:

- **Exposing Existing Servers**: If you have an existing MCP server, you can use the gateway to make it accessible to Nostr clients without modifying the server's core logic. The server continues to operate with its standard transport, while the gateway handles all Nostr-related communication.
- **Decoupling Services**: You can run your core MCP server in a secure environment and use the gateway as a public-facing entry point on the Nostr network. The gateway can be configured with its own security policies (like `allowedPublicKeys`).
- **Adding Nostr Capabilities**: It allows you to add features like public server announcements and decentralized discovery to a conventional MCP server.

## `NostrMCPGatewayOptions`

To create a `NostrMCPGateway`, you need to provide a configuration object that implements the `NostrMCPGatewayOptions` interface:

```typescript
export interface NostrMCPGatewayOptions {
  mcpClientTransport: Transport;
  nostrTransportOptions: NostrServerTransportOptions;
}
```

- **`mcpClientTransport`**: An instance of a client-side MCP transport that the gateway will use to connect to your existing MCP server. For example, `new StdioClientTransport(...)`.
- **`nostrTransportOptions`**: The full configuration object required by the `NostrServerTransport`. This includes the `signer`, `relayHandler`, and options like `isPublicServer`.

## Usage Example

This example shows how to create a gateway that connects to a local MCP server (running in a separate process) and exposes it to the Nostr network.

```typescript
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { NostrMCPGateway } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";

// 1. Configure the signer and relay handler for the Nostr transport
const signer = new PrivateKeySigner("your-gateway-private-key");
const relayPool = new SimpleRelayPool(["wss://relay.damus.io"]);

// 2. Configure the transport to connect to your existing MCP server
const clientTransport = new StdioClientTransport({
  command: "bun",
  args: ["run", "path/to/your/mcp-server.ts"],
});

// 3. Create the gateway instance
const gateway = new NostrMCPGateway({
  mcpClientTransport: clientTransport,
  nostrTransportOptions: {
    signer,
    relayHandler: relayPool,
  },
});

// 4. Start the gateway
await gateway.start();

console.log("Gateway is running, exposing the MCP server to Nostr.");

// To stop the gateway: await gateway.stop();
```

## Next Steps

This concludes the core components of the SDK. The final section provides practical examples of how to use these components together.

- **[Tutorials](/tutorials/client-server-communication)**

================
File: docs/ts-sdk/proxy/overview.md
================
---
title: Proxy Overview
description: A client-side bridging component for the @contextvm/sdk.
---

# Proxy

The `NostrMCPProxy` is a powerful, client-side bridging component in the `@contextvm/sdk`. Its primary function is to act as a local proxy that translates communication between a standard MCP client and a remote, Nostr-based MCP server.

## Functionality Overview

The proxy manages two transports simultaneously:

1.  **MCP Host Transport**: This is a standard MCP transport (like `StdioServerTransport`) that communicates with a local MCP client application.
2.  **Nostr Client Transport**: This is a [`NostrClientTransport`](/transports/nostr-client-transport) that communicates with the remote MCP server over the Nostr network.

The proxy sits in the middle, seamlessly forwarding messages between these two transports. When the local client sends a request, the proxy forwards it over Nostr. When the remote server sends a response, the proxy relays it back to the local client.

## Use Cases and Capabilities

The `NostrMCPProxy` is particularly useful in the following scenarios:

- **Integrating with Existing Clients**: If you have an existing MCP client that does not have native Nostr support, you can use the proxy to enable it to communicate with Nostr-based MCP servers without modifying the client's code. The client simply connects to the proxy's local transport.
- **Simplifying Client-Side Logic**: The proxy abstracts away all the complexities of Nostr communication (signing, relay management, encryption), allowing your main client application to remain simple and focused on its core tasks.
- **Local Development and Testing**: The proxy can be a valuable tool for local development, allowing you to easily test a client against a remote Nostr server.

## `NostrMCPProxyOptions`

To create a `NostrMCPProxy`, you need to provide a configuration object that implements the `NostrMCPProxyOptions` interface:

```typescript
export interface NostrMCPProxyOptions {
  mcpHostTransport: Transport;
  nostrTransportOptions: NostrTransportOptions;
}
```

- **`mcpHostTransport`**: An instance of a server-side MCP transport that the local client will connect to. For example, `new StdioServerTransport()`.
- **`nostrTransportOptions`**: The full configuration object required by the `NostrClientTransport`. This includes the `signer`, `relayHandler`, and the remote `serverPubkey`.

## Usage Example

This example demonstrates how to create a proxy that listens for a local client over standard I/O and connects to a remote server over Nostr.

```typescript
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { NostrMCPProxy } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";

// 1. Configure the signer and relay handler for the Nostr connection
const signer = new PrivateKeySigner("your-private-key");
const relayPool = new SimpleRelayPool(["wss://relay.damus.io"]);
const REMOTE_SERVER_PUBKEY = "remote-server-public-key";

// 2. Configure the transport for the local client
// In this case, a stdio transport that the local client can connect to
const hostTransport = new StdioServerTransport();

// 3. Create the proxy instance
const proxy = new NostrMCPProxy({
  mcpHostTransport: hostTransport,
  nostrTransportOptions: {
    signer,
    relayHandler: relayPool,
    serverPubkey: REMOTE_SERVER_PUBKEY,
  },
});

// 4. Start the proxy
await proxy.start();

console.log("Proxy is running. Connect your local MCP client.");

// To stop the proxy: await proxy.stop();
```

In this setup, a separate MCP client process could connect to this proxy's `StdioServerTransport` and it would be transparently communicating with the remote server on Nostr.

## Next Steps

Next, we'll look at the server-side equivalent of the proxy:

- **[Gateway](/overview)**

================
File: docs/ts-sdk/relay/applesauce-relay-pool.md
================
---
title: ApplesauceRelayPool
description: An advanced relay handler implementation using the applesauce-relay library for the @contextvm/sdk.
---

# `ApplesauceRelayPool`

The `ApplesauceRelayPool` is an advanced implementation of the [`RelayHandler`](/relay/relay-handler-interface) interface that uses the `applesauce-relay` library. It provides sophisticated relay management with automatic reconnection, connection monitoring, and robust subscription handling.

## Overview

The `ApplesauceRelayPool` offers enhanced features compared to the basic [`SimpleRelayPool`](/relay/simple-relay-pool):

- **Automatic Connection Management**: Uses `RelayPool` for efficient connection handling
- **Connection Monitoring**: Monitors relay connections and automatically resubscribes when connections are lost
- **Retry Logic**: Built-in retry mechanisms for failed operations
- **Observable-based Architecture**: Leverages RxJS-style observables for event handling
- **Advanced Subscription Management**: Persistent subscriptions with automatic reconnection

This implementation is ideal for applications that require more sophisticated relay management and better resilience against network interruptions.

## `constructor(relayUrls: string[])`

The constructor takes a single argument:

- **`relayUrls`**: An array of strings, where each string is the URL of a Nostr relay (e.g., `wss://relay.damus.io`).

## Usage Example

```typescript
import { ApplesauceRelayPool } from "@contextvm/sdk";
import { NostrClientTransport } from "@contextvm/sdk";

// 1. Define the list of relays you want to connect to
const myRelays = [
  "wss://relay.damus.io",
  "wss://relay.primal.net",
  "wss://nos.lol",
];

// 2. Create an instance of the ApplesauceRelayPool
const relayPool = new ApplesauceRelayPool(myRelays);

// 3. Pass the instance to a transport
const transport = new NostrClientTransport({
  relayHandler: relayPool,
  // ... other options
});
```

## How It Works

The `ApplesauceRelayPool` implements the `RelayHandler` interface using the `applesauce-relay` library:

### Connection Management

- **`connect()`**: Validates relay URLs and initializes the `RelayPool`. The pool automatically manages connections to relays as needed.
- **`disconnect()`**: Closes all active subscriptions and clears internal state. Note that the underlying `RelayPool` manages connections automatically.

### Event Publishing

- **`publish(event)`**: Uses `relayGroup.publish()` which includes automatic retry logic. The method returns a Promise that resolves when the publish operation completes.

### Subscription Management

- **`subscribe(filters, onEvent, onEose)`**: Creates a persistent subscription using `relayGroup.subscription()` with automatic reconnection. Subscriptions are tracked internally for lifecycle management.
- **`unsubscribe()`**: Closes all active subscriptions and clears the internal subscription tracking.

### Advanced Features

#### Connection Monitoring

The pool automatically monitors relay connections and triggers resubscription when connections are lost:

```typescript
private setupConnectionMonitoring(): void {
  this.pool.relays$.subscribe((relays) => {
    relays.forEach((relay) => {
      relay.connected$.subscribe((connected) => {
        if (!connected) {
          this.resubscribeAll();
        }
      });
    });
  });
}
```

#### Automatic Resubscription

When a relay connection is lost and reestablished, the pool automatically resubscribes to all active subscriptions:

```typescript
private resubscribeAll(): void {
  this.subscriptions.forEach((sub) => {
    if (sub.closer) sub.closer.unsubscribe();
    sub.closer = this.createSubscription(
      sub.filters,
      sub.onEvent,
      sub.onEose,
    );
  });
}
```

#### Error Handling

The implementation includes comprehensive error handling for both publishing and subscription operations:

- **Publish Errors**: Logs warnings for failed publishes but doesn't reject the Promise unless there's a critical error
- **Subscription Errors**: Removes failed subscriptions from tracking and logs the error

## Key Differences from SimpleRelayPool

| Feature                      | SimpleRelayPool                      | ApplesauceRelayPool                       |
| ---------------------------- | ------------------------------------ | ----------------------------------------- |
| **Library**                  | `nostr-tools`                        | `applesauce-relay`                        |
| **Connection Management**    | Manual connection tracking           | Automatic connection management           |
| **Reconnection**             | Manual reconnection logic            | Automatic reconnection with monitoring    |
| **Retry Logic**              | Basic retry with exponential backoff | Built-in retry mechanisms                 |
| **Subscription Persistence** | Manual resubscription                | Automatic resubscription on reconnect     |
| **Error Handling**           | Basic error logging                  | Comprehensive error handling with cleanup |

## When to Use ApplesauceRelayPool

Consider using `ApplesauceRelayPool` when:

- You need robust connection management and automatic reconnection
- Your application requires high availability and resilience
- You want advanced subscription management with automatic recovery
- You're building a production application that needs to handle network interruptions gracefully

For simpler use cases or when you want to minimize dependencies, the [`SimpleRelayPool`](/relay/simple-relay-pool) may be sufficient.

## Next Steps

- Learn how to build a custom relay handler: **[Custom Relay Handler](/relay/custom-relay-handler)**
- Understand the relay handler interface: **[Relay Handler Interface](/relay/relay-handler-interface)**

================
File: docs/ts-sdk/relay/custom-relay-handler.md
================
---
title: Custom Relay Handler Development
description: Learn how to create a custom relay handler for the @contextvm/sdk.
---

# Custom Relay Handler Development

The `@contextvm/sdk`'s-pluggable architecture, centered around the [`RelayHandler`](/relay/relay-handler-interface) interface, allows developers to implement custom logic for managing Nostr-relay connections. This is particularly useful for advanced use cases that require more sophisticated behavior than what the default [`SimpleRelayPool`](/relay/simple-relay-pool) provides.

## Why Create a Custom Relay Handler?

You might want to create a custom `RelayHandler` for several reasons:

- **Intelligent Relay Selection**: To dynamically select relays based on performance, reliability, or the specific type of data being requested. For example, you might use a different set of relays for fetching user metadata versus broadcasting messages.
- **Auth Relays**: To integrate with auth relays that require authentication or specific connection logic.
- **Dynamic Relay Discovery**: To discover and connect to new relays at runtime, rather than using a static list.
- **Custom Caching**: To implement a custom caching layer to reduce redundant requests to relays.
- **Resiliency and-failover**: To build more robust-failover logic, such as automatically retrying failed connections or switching to backup relays.

## Non-Blocking Subscription Requirement

A critical requirement for implementing the `RelayHandler` interface is that the `subscribe` method must be **non-blocking**. This design ensures that the transport layer can create multiple subscriptions concurrently without waiting for each one to complete.

### Key Implementation Principles

1. **Immediate Return**: The `subscribe` method should return immediately after initiating the subscription
2. **Internal State Management**: Store active subscriptions internally for lifecycle management
3. **Automatic Reconnection**: Handle resubscription when connections are reestablished

## Implementing the `RelayHandler` Interface

To create a custom relay handler, you need to create a class that implements the `RelayHandler` interface. This involves implementing five methods: `connect`, `disconnect`, `publish`, `subscribe`, and `unsubscribe`.

### Implementation Pattern For Non-Blocking Subscriptions

```typescript
class MyRelayHandler implements RelayHandler {
  private subscriptions: Array<{
    filters: Filter[];
    onEvent: (event: NostrEvent) => void;
    onEose?: () => void;
    closer?: SubCloser; // Or similar subscription management object
  }> = [];

  async connect(): Promise<void> {
    // Connect to the relays
  }

  async disconnect(relayUrls?: string[]): Promise<void> {
    // Disconnect from the relays
  }

  async publish(event: NostrEvent): Promise<void> {
    // Publish the event to the relays
  }

  async subscribe(
    filters: Filter[],
    onEvent: (event: NostrEvent) => void,
    onEose?: () => void,
  ): Promise<void> {
    // Create the subscription (non-blocking)
    const closer = this.pool.subscribeMany(relayUrls, filters, {
      onevent: onEvent,
      oneose: onEose,
    });

    // Store the subscription for management
    this.subscriptions.push({ filters, onEvent, onEose, closer });
  }

  unsubscribe(): void {
    // Close all active subscriptions
    this.subscriptions.forEach((sub) => sub.closer?.close());
    this.subscriptions = [];
  }
}
```

This pattern is used by both [`SimpleRelayPool`](/relay/simple-relay-pool) and [`ApplesauceRelayPool`](/relay/applesauce-relay-pool) implementations.

## Using Your Custom Relay Handler

Once your custom handler class is created, you can instantiate it and pass it to any component that requires a `RelayHandler`, such as the `NostrClientTransport` or `NostrServerTransport`. The SDK will then use your custom logic for all relay interactions.

## Next Steps

With the `Relay` component covered, we will now look at the high-level bridging components provided by the SDK.

- **[Proxy](/proxy/overview)**
- **[Gateway](/overview)**

================
File: docs/ts-sdk/relay/relay-handler-interface.md
================
---
title: RelayHandler Interface
description: An interface for managing Nostr relay connections.
---

# `RelayHandler` Interface

The `RelayHandler` interface is another crucial abstraction in the `@contextvm/sdk`. It defines the standard for managing connections to Nostr relays, which are the backbone of the Nostr network responsible for message propagation.

## Purpose and Design

The `RelayHandler`'s purpose is to abstract the complexities of relay management, including:

- Connecting and disconnecting from a set of relays.
- Subscribing to events with specific filters.
- Publishing events to the network.
- Handling relay-specific logic, such as connection retries, timeouts, and relay selection.

By depending on this interface, the SDK's transports can remain agnostic about the specific relay management strategy being used. This allows developers to plug in different relay handlers to suit their needs.

## Non-Blocking Subscription Model

A critical aspect of the `RelayHandler` interface is that the `subscribe` method must be **non-blocking**. This design choice ensures that transports can create multiple subscriptions without waiting for each one to complete, allowing for efficient concurrent event handling.

### Key Design Principles

1. **Immediate Return**: The `subscribe` method should return immediately after initiating the subscription, without awaiting the subscription's completion.

2. **Internal Subscription Management**: Relay handlers must maintain active subscriptions internally, typically using an array or similar data structure to track subscription state.

3. **Automatic Reconnection**: Subscriptions should automatically resubscribe when connections are reestablished, ensuring continuous event delivery even during network interruptions.

## Interface Definition

The `RelayHandler` interface is defined in [`core/interfaces.ts`](/core/interfaces#relayhandler) and includes several key methods:

```typescript
export interface RelayHandler {
  connect(): Promise<void>;
  disconnect(relayUrls?: string[]): Promise<void>;
  publish(event: NostrEvent): Promise<void>;
  subscribe(
    filters: Filter[],
    onEvent: (event: NostrEvent) => void,
    onEose?: () => void,
  ): Promise<void>;
  unsubscribe(): void;
}
```

- `connect()`: Establishes connections to the configured relays.
- `disconnect()`: Closes connections to all relays.
- `subscribe(filters, onEvent)`: Creates a subscription on the connected relays, listening for events that match the provided filters and passing them to the `onEvent` callback, it also accepts an optional `onEose` callback that is called when the relay reach "end of stored events".
- `unsubscribe()`: Closes all active subscriptions.
- `publish(event)`: Publishes a Nostr event to the connected relays.

## Implementations

The SDK provides a default implementation for common use cases and allows for custom implementations for advanced scenarios.

- **[SimpleRelayPool](/relay/simple-relay-pool)**: The default implementation, which manages a pool of relays and handles connection and subscription logic.
- **[Custom Relay Handler](/relay/custom-relay-handler)**: For creating custom relay handlers that integrate with specific relay management systems, such as auth relays or custom caching.

## Next Steps

- Learn about the default implementation: **[SimpleRelayPool](/relay/simple-relay-pool)**
- Learn how to create your own: **[Custom Relay Handler](/relay/custom-relay-handler)**

================
File: docs/ts-sdk/relay/simple-relay-pool.md
================
---
title: SimpleRelayPool
description: A default relay handler implementation for the @contextvm/sdk.
---

# `SimpleRelayPool`

The `SimpleRelayPool` is the default implementation of the [`RelayHandler`](/relay/relay-handler-interface) interface provided by the `@contextvm/sdk`. It uses the `SimplePool` from the `nostr-tools` library to manage connections to a list of specified relays.

## Overview

The `SimpleRelayPool` provides a straightforward way to manage relay connections for most common use cases. Its responsibilities include:

- Connecting to a predefined list of Nostr relays.
- Publishing events to all relays in the pool.
- Subscribing to events from all relays in the pool.
- Managing the lifecycle of connections and subscriptions.

It is a simple but effective solution for applications that need to interact with a static set of relays.

## `constructor(relayUrls: string[])`

The constructor takes a single argument:

- **`relayUrls`**: An array of strings, where each string is the URL of a Nostr relay (e.g., `wss://relay.damus.io`).

## Usage Example

```typescript
import { SimpleRelayPool } from "@contextvm/sdk";
import { NostrClientTransport } from "@contextvm/sdk";

// 1. Define the list of relays you want to connect to
const myRelays = [
  "wss://relay.damus.io",
  "wss://relay.primal.net",
  "wss://nos.lol",
];

// 2. Create an instance of the SimpleRelayPool
const relayPool = new SimpleRelayPool(myRelays);

// 3. Pass the instance to a transport
const transport = new NostrClientTransport({
  relayHandler: relayPool,
  // ... other options
});
```

## How It Works

The `SimpleRelayPool` wraps the `SimplePool` from `nostr-tools` and implements the methods of the `RelayHandler` interface:

- **`connect()`**: Iterates through the provided `relayUrls` and calls `pool.ensureRelay()` for each one, which establishes a connection if one doesn't already exist.
- **`disconnect()`**: Closes the connections to the specified relays.
- **`publish(event)`**: Publishes the given event to all relays in the pool by calling `pool.publish()`.
- **`subscribe(filters, onEvent)`**: Creates a subscription on all relays in the pool using `pool.subscribeMany()`. It tracks all active subscriptions so they can be closed later.
- **`unsubscribe()`**: Closes all active subscriptions that were created through the `subscribe` method.

## Limitations

The `SimpleRelayPool` is designed for simplicity. It connects to all provided relays and does not include advanced features.

For applications that require more sophisticated relay management, you may want to create a [Custom Relay Handler](/relay/custom-relay-handler).

## Next Steps

- Learn how to build a custom relay handler: **[Custom Relay Handler](/relay/custom-relay-handler)**

================
File: docs/ts-sdk/signer/custom-signer-development.md
================
---
title: Custom Signer Development
description: Learn how to create a custom signer for the @contextvm/sdk.
---

# Custom Signer Development

One of the key design features of the `@contextvm/sdk` is its modularity, which is exemplified by the [`NostrSigner`](/signer/nostr-signer-interface) interface. By creating your own implementation of this interface, you can integrate the SDK with any key management system, such as a hardware wallet, a remote signing service (like an HSM), or a browser extension.

## Why Create a Custom Signer?

While the [`PrivateKeySigner`](/signer/private-key-signer) is a common choice for most applications, there are cases where you may need to use a different approach:

- **Security is paramount**: You need to keep private keys isolated from the main application logic, for example, in a hardware security module (HSM) or a secure enclave.
- **Interacting with external wallets**: Your application needs to request signatures from a user's wallet, such as a browser extension (e.g., Alby, Noster) or a mobile wallet.
- **Complex key management**: Your application uses a more complex key management architecture that doesn't involve direct access to raw private keys.

## Implementing the `NostrSigner` Interface

To create a custom signer, you need to create a class that implements the `NostrSigner` interface. This involves implementing two main methods: `getPublicKey()` and `signEvent()`, as well as an optional `nip44` object for encryption.

### Example: A NIP-07 Browser Signer (window.nostr)

A common use case for a custom signer is in a web application that needs to interact with a Nostr browser extension (like Alby, nos2x, or Blockcore) that exposes the `window.nostr` object according to [NIP-07](https://github.com/nostr-protocol/nips/blob/master/07.md). This allows the application to request signatures and encryption from the user's wallet without ever handling private keys directly.

Here is how you could implement a `NostrSigner` that wraps the `window.nostr` object:

```typescript
import { NostrSigner } from "@contextvm/sdk";
import { UnsignedEvent, NostrEvent } from "nostr-tools";

// Define the NIP-07 window.nostr interface for type-safety
declare global {
  interface Window {
    nostr?: {
      getPublicKey(): Promise<string>;
      signEvent(event: UnsignedEvent): Promise<NostrEvent>;
      nip44?: {
        encrypt(pubkey: string, plaintext: string): Promise<string>;
        decrypt(pubkey: string, ciphertext: string): Promise<string>;
      };
    };
  }
}

class Nip07Signer implements NostrSigner {
  constructor() {
    if (!window.nostr) {
      throw new Error("NIP-07 compatible browser extension not found.");
    }
  }

  async getPublicKey(): Promise<string> {
    if (!window.nostr) throw new Error("window.nostr not found.");
    return await window.nostr.getPublicKey();
  }

  async signEvent(event: UnsignedEvent): Promise<NostrEvent> {
    if (!window.nostr) throw new Error("window.nostr not found.");
    return await window.nostr.signEvent(event);
  }

  nip44 = {
    encrypt: async (pubkey: string, plaintext: string): Promise<string> => {
      if (!window.nostr?.nip44) {
        throw new Error("The extension does not support NIP-44 encryption.");
      }
      return await window.nostr.nip44.encrypt(pubkey, plaintext);
    },

    decrypt: async (pubkey: string, ciphertext: string): Promise<string> => {
      if (!window.nostr?.nip44) {
        throw new Error("The extension does not support NIP-44 decryption.");
      }
      return await window.nostr.nip44.decrypt(pubkey, ciphertext);
    },
  };
}
```

### Implementing `nip44` for Decryption

When using a NIP-07 signer, the `nip44` implementation is straightforward, as you can see in the example above. You simply delegate the calls to the `window.nostr.nip44` object.

It's important to include checks to ensure that the user's browser extension supports `nip44`, as it is an optional part of the NIP-07 specification. If the extension does not support it, you should throw an error to prevent unexpected behavior.

## Using Your Custom Signer

Once your custom signer class is created, you can instantiate it and pass it to any component that requires a `NostrSigner`, such as the `NostrClientTransport` or `NostrServerTransport`. The rest of the SDK will use your custom implementation seamlessly.

## Next Steps

With the `Signer` component covered, let's move on to the **[Relay](/relay/simple-relay-pool)** component, which handles the connection and management of Nostr relays.

================
File: docs/ts-sdk/signer/nostr-signer-interface.md
================
---
title: NostrSigner Interface
description: An interface for signing Nostr events.
---

# `NostrSigner` Interface

The `NostrSigner` interface is a central component of the `@contextvm/sdk`, defining the standard for cryptographic signing operations. Every Nostr event must be signed by a private key to be considered valid, and this interface provides a consistent, pluggable way to handle this requirement.

## Purpose and Design

The primary purpose of the `NostrSigner` is to abstract the process of event signing. By depending on this interface rather than a concrete implementation, the SDK's transports and other components can remain agnostic about how and where private keys are stored and used.

This design offers several key benefits:

- **Security**: Private keys can be managed in secure environments (e.g., web extensions, hardware wallets, dedicated signing services) without exposing them to the application logic.
- **Flexibility**: Developers can easily swap out the default signer with a custom implementation that meets their specific needs.
- **Modularity**: The signing logic is decoupled from the communication logic, leading to a cleaner, more maintainable codebase.

## Interface Definition

The `NostrSigner` interface is defined in [`core/interfaces.ts`](/core/interfaces#nostrsigner).

```typescript
export interface NostrSigner {
  getPublicKey(): Promise<string>;
  signEvent(event: EventTemplate): Promise<NostrEvent>;

  // Optional NIP-04 encryption support (deprecated)
  nip04?: {
    encrypt: (pubkey: string, plaintext: string) => Promise<string>;
    decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
  };

  // Optional NIP-44 encryption support
  nip44?: {
    encrypt: (pubkey: string, plaintext: string) => Promise<string>;
    decrypt: (pubkey: string, ciphertext: string) => Promise<string>;
  };
}
```

- `getPublicKey()`: Asynchronously returns the public key corresponding to the signer's private key.
- `signEvent(event)`: Takes an unsigned Nostr event, signs it, and returns the signature.
- `nip04`: (Deprecated) Provides NIP-04 encryption support.
- `nip44`: Provides NIP-44 encryption support.

Any class that implements this interface can be used as a signer throughout the SDK.

## Implementations

The SDK provides a default implementation for common use cases and allows for custom implementations for advanced scenarios.

- **[PrivateKeySigner](/signer/private-key-signer)**: The default implementation, which takes a raw private key string and performs signing operations locally.
- **[Custom Signer Development](/signer/custom-signer-development)**: For creating custom signers that integrate with key management systems, such as hardware wallets or remote signing services.

## Next Steps

- Learn about the default implementation: **[PrivateKeySigner](/signer/private-key-signer)**
- Learn how to create your own: **[Custom Signer Development](/signer/custom-signer-development)**

================
File: docs/ts-sdk/signer/private-key-signer.md
================
---
title: PrivateKeySigner
description: A default signer implementation for the @contextvm/sdk.
---

# `PrivateKeySigner`

The `PrivateKeySigner` is the default implementation of the [`NostrSigner`](/signer/nostr-signer-interface) interface provided by the `@contextvm/sdk`. It is a straightforward and easy-to-use signer that operates directly on a raw private key provided as a hexadecimal string.

## Overview

The `PrivateKeySigner` is designed for scenarios where the private key is readily available in the application's environment. It handles all the necessary cryptographic operations locally, including:

- Deriving the corresponding public key.
- Signing Nostr events.
- Encrypting and decrypting messages using NIP-44.

## `constructor(privateKey: string)`

The constructor takes a single argument:

- **`privateKey`**: A hexadecimal string representing the 32-byte Nostr private key.

When instantiated, the `PrivateKeySigner` will immediately convert the hex string into a `Uint8Array` and derive the public key, which is then cached for future calls to `getPublicKey()`.

## Usage Example

```typescript
import { PrivateKeySigner } from "@contextvm/sdk";

// Replace with a securely stored private key
const privateKeyHex = "your-32-byte-private-key-in-hex";

const signer = new PrivateKeySigner(privateKeyHex);

// You can now pass this signer instance to a transport
const transportOptions = {
  signer: signer,
  // ... other options
};
```

## Key Methods

The `PrivateKeySigner` implements all the methods required by the `NostrSigner` interface.

### `async getPublicKey(): Promise<string>`

Returns a promise that resolves with the public key corresponding to the private key provided in the constructor.

### `async signEvent(event: UnsignedEvent): Promise<NostrEvent>`

Takes an unsigned Nostr event, signs it using the private key, and returns a promise that resolves with the finalized, signed `NostrEvent`.

### `nip44`

The `PrivateKeySigner` also provides a `nip44` object that implements NIP-44 encryption and decryption. This is used internally by the transports when encryption is enabled, and it allows the `decryptMessage` function to work seamlessly with this signer.

- `encrypt(pubkey, plaintext)`: Encrypts a plaintext message for a given recipient public key.
- `decrypt(pubkey, ciphertext)`: Decrypts a ciphertext message received from a given sender public key.

## Security Considerations

While the `PrivateKeySigner` is convenient, it requires you to handle a raw private key directly in your application code. **It is crucial to manage this key securely.** Avoid hard-coding private keys in your source code. Instead, use environment variables or a secure secret management system to load the key at runtime.

For applications requiring a higher level of security, consider creating a custom signer that interacts with a hardware wallet or a remote signing service.

## Next Steps

- Learn how to build a custom signer: **[Custom Signer Development](/signer/custom-signer-development)**

================
File: docs/ts-sdk/transports/base-nostr-transport.md
================
---
title: Base Nostr Transport
description: An abstract class that provides the core functionality for all Nostr-based transports in the @contextvm/sdk.
---

# Base Nostr Transport

The `BaseNostrTransport` is an abstract class that provides the core functionality for all Nostr-based transports in the `@contextvm/sdk`. It serves as the foundation for the [`NostrClientTransport`](/transports/nostr-client-transport) and [`NostrServerTransport`](/transports/nostr-server-transport), handling the common logic for connecting to relays, managing subscriptions, and converting messages between the MCP and Nostr formats.

## Core Responsibilities

The `BaseNostrTransport` is responsible for:

- **Connection Management**: Establishing and terminating connections to the Nostr relay network via a `RelayHandler`.
- **Event Serialization**: Converting MCP JSON-RPC messages into Nostr events and vice-versa.
- **Cryptographic Operations**: Signing Nostr events using a `NostrSigner`.
- **Message Publishing**: Publishing events to the Nostr network.
- **Subscription Management**: Creating and managing subscriptions to listen for relevant events.
- **Encryption Handling**: Managing the encryption and decryption of messages based on the configured `EncryptionMode`.

## `BaseNostrTransportOptions`

When creating a transport that extends `BaseNostrTransport`, you must provide a configuration object that implements the `BaseNostrTransportOptions` interface:

```typescript
export interface BaseNostrTransportOptions {
  signer: NostrSigner;
  relayHandler: RelayHandler;
  encryptionMode?: EncryptionMode;
}
```

- **`signer`**: An instance of a `NostrSigner` for signing events. This is a required parameter.
- **`relayHandler`**: An instance of a `RelayHandler` for managing relay connections. This is a required parameter.
- **`encryptionMode`**: An optional `EncryptionMode` enum that determines the encryption policy for the transport. Defaults to `OPTIONAL`.

## Key Methods

The `BaseNostrTransport` provides several protected methods that are used by its subclasses to implement their specific logic:

- `connect()`: Connects to the configured Nostr relays.
- `disconnect()`: Disconnects from the relays and clears subscriptions.
- `subscribe(filters, onEvent)`: Subscribes to Nostr events that match the given filters.
- `sendMcpMessage(...)`: Converts an MCP message to a Nostr event, signs it, optionally encrypts it, and publishes it to the network.
- `createSubscriptionFilters(...)`: A helper method to create standard filters for listening to messages directed at a specific public key.

## How It Fits Together

The `BaseNostrTransport` encapsulates the shared logic of Nostr communication, allowing the `NostrClientTransport` and `NostrServerTransport` to focus on their specific roles in the client-server interaction model. By building on this common base, the SDK ensures consistent behavior and a unified approach to handling MCP over Nostr.

## Next Steps

Now that you understand the foundation of the Nostr transports, let's explore the concrete implementations:

- **[Nostr Client Transport](/transports/nostr-client-transport)**: For building MCP clients that communicate over Nostr.
- **[Nostr Server Transport](/transports/nostr-server-transport)**: For exposing MCP servers to the Nostr network.

================
File: docs/ts-sdk/transports/nostr-client-transport.md
================
---
title: Nostr Client Transport
description: A client-side component for communicating with MCP servers over Nostr.
---

# Nostr Client Transport

The `NostrClientTransport` is a key component of the `@contextvm/sdk`, enabling MCP clients to communicate with remote MCP servers over the Nostr network. It implements the `Transport` interface from the `@modelcontextprotocol/sdk`, making it a plug-and-play solution for any MCP client.

## Overview

The `NostrClientTransport` handles all the complexities of Nostr-based communication, including:

- Connecting to Nostr relays.
- Subscribing to events from a specific server.
- Sending MCP requests as Nostr events.
- Receiving and processing responses and notifications.
- Handling encryption and decryption of messages.

By using this transport, an MCP client can interact with a Nostr-enabled MCP server without needing to implement any Nostr-specific logic itself.

## `NostrTransportOptions`

To create an instance of `NostrClientTransport`, you must provide a configuration object that implements the `NostrTransportOptions` interface:

```typescript
export interface NostrTransportOptions extends BaseNostrTransportOptions {
  serverPubkey: string;
  isStateless?: boolean;
}
```

- **`serverPubkey`**: The public key of the target MCP server. The transport will only listen for events from this public key.
- **`isStateless`** (optional): When set to `true`, enables stateless mode for the client transport. In stateless mode, the client emulates the server's initialize response without requiring a full server initialization roundtrip. This enables faster startup and reduced network overhead. Default is `false`.

## Usage Example

Here's how you can use the `NostrClientTransport` with an MCP client from the `@modelcontextprotocol/sdk`:

```typescript
import { Client } from "@modelcontextprotocol/sdk/client";
import { NostrClientTransport } from "@contextvm/sdk";
import { EncryptionMode } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";

// 1. Configure the signer and relay handler
const signer = new PrivateKeySigner("your-private-key"); // Replace with your actual private key
const relayPool = new SimpleRelayPool(["wss://relay.damus.io"]);

// 2. Set the public key of the target server
const REMOTE_SERVER_PUBKEY = "remote-server-public-key";

// 3. Create the transport instance
const clientNostrTransport = new NostrClientTransport({
  signer,
  relayHandler: relayPool,
  serverPubkey: REMOTE_SERVER_PUBKEY,
  encryptionMode: EncryptionMode.OPTIONAL,
});

// 4. Create and connect the MCP client
const mcpClient = new Client({
  name: "My Client",
  version: "1.0.0",
});

await mcpClient.connect(clientNostrTransport);

// 5. Use the client to interact with the server
const tools = await mcpClient.listTools();
console.log("Available tools:", tools);

// 6. Close the connection when done
// await mcpClient.close();
```

## How It Works

1.  **`start()`**: When `mcpClient.connect()` is called, it internally calls the transport's `start()` method. This method connects to the relays and subscribes to events targeting the client's public key.
    - In **stateless mode** (`isStateless: true`), the client emulates the server's initialize response without sending it over the network, skipping the `notifications/initialized` message exchange.
    - In **standard mode** (`isStateless: false` or undefined), the client performs the full initialization roundtrip with the server.
2.  **`send(message)`**: When you call an MCP method like `mcpClient.listTools()`, the client creates a JSON-RPC request and passes it to the transport's `send()` method. The transport then:
    - Wraps the message in a Nostr event.
    - Signs the event.
    - Optionally encrypts it.
    - Publishes it to the relays, targeting the `serverPubkey`.
3.  **Event Processing**: The transport listens for incoming events. When an event is received, it is decrypted (if necessary) and converted back into a JSON-RPC message.
    - If the message is a **response** (correlated by the original event ID), it is passed to the MCP client to resolve the pending request.
    - If the message is a **notification**, it is emitted through the `onmessage` handler.

## Stateless Mode

The stateless mode is designed to optimize performance by reducing the initialization overhead:

- **Faster Startup**: By emulating the initialize response, the client can begin operations immediately without waiting for server response.
- **Reduced Network Overhead**: Eliminates the need for the initialization roundtrip.
- **Use Cases**: Ideal for scenarios where the client needs to quickly connect and interact with the server, such as in serverless functions or short-lived processes.

To enable stateless mode, set `isStateless: true` in the transport configuration:

```typescript
const clientNostrTransport = new NostrClientTransport({
  signer,
  relayHandler: relayPool,
  serverPubkey: REMOTE_SERVER_PUBKEY,
  encryptionMode: EncryptionMode.OPTIONAL,
  isStateless: true, // Enable stateless mode
});
```

**Note**: The stateless mode might not work with all servers.

## Next Steps

Next, we will look at the server-side counterpart to this transport:

- **[Nostr Server Transport](/transports/nostr-server-transport)**: For exposing MCP servers to the Nostr network.

================
File: docs/ts-sdk/transports/nostr-server-transport.md
================
---
title: Nostr Server Transport
description: A server-side component for exposing MCP servers over Nostr.
---

# Nostr Server Transport

The `NostrServerTransport` is the server-side counterpart to the [`NostrClientTransport`](/transports/nostr-client-transport). It allows an MCP server to expose its capabilities to the Nostr network, making them discoverable and usable by any Nostr-enabled client. Like the client transport, it implements the `Transport` interface from the `@modelcontextprotocol/sdk`.

## Overview

The `NostrServerTransport` is responsible for:

- Listening for incoming MCP requests from Nostr clients.
- Managing individual client sessions and their state (e.g., initialization, encryption).
- Handling request/response correlation to ensure responses are sent to the correct client.
- Sending responses and notifications back to clients over Nostr.
- Optionally announcing the server and its capabilities to the network for public discovery.

## `NostrServerTransportOptions`

The transport is configured via the `NostrServerTransportOptions` interface:

```typescript
export interface NostrServerTransportOptions extends BaseNostrTransportOptions {
  serverInfo?: ServerInfo;
  isPublicServer?: boolean;
  allowedPublicKeys?: string[];
  /** List of capabilities that are excluded from public key whitelisting requirements */
  excludedCapabilities?: CapabilityExclusion[];
}
```

- **`serverInfo`**: (Optional) Information about the server (`name`, `picture`, `website`) to be used in public announcements.
- **`isPublicServer`**: (Optional) If `true`, the transport will automatically announce the server's capabilities on the Nostr network. Defaults to `false`.
- **`allowedPublicKeys`**: (Optional) A list of client public keys that are allowed to connect. If not provided, any client can connect.
- **`excludedCapabilities`**: (Optional) A list of capabilities that are excluded from public key whitelisting requirements. This allows certain operations from disallowed public keys, enhancing security policy flexibility while maintaining backward compatibility.

### Capability Exclusion

The `CapabilityExclusion` interface allows you to define specific capabilities that bypass the public key whitelisting requirements:

```typescript
/**
 * Represents a capability exclusion pattern that can bypass whitelisting.
 * Can be either a method-only pattern (e.g., 'tools/list') or a method + name pattern (e.g., 'tools/call, get_weather').
 */
export interface CapabilityExclusion {
  /** The JSON-RPC method to exclude from whitelisting (e.g., 'tools/call', 'tools/list') */
  method: string;
  /** Optional capability name to specifically exclude (e.g., 'get_weather') */
  name?: string;
}
```

#### How Capability Exclusion Works

Capability exclusion provides fine-grained control over access by allowing specific operations to be performed even by clients that are not in the `allowedPublicKeys` list. This is useful for:

- Allowing public access to server discovery endpoints like `tools/list`
- Permitting specific tool calls from untrusted clients
- Maintaining backward compatibility with existing clients

#### Exclusion Patterns

- **Method-only exclusion**: `{ method: 'tools/list' }` - Excludes all calls to the `tools/list` method
- **Method + name exclusion**: `{ method: 'tools/call', name: 'add' }` - Excludes only the `add` tool from the `tools/call` method

## Usage Example

Here's how to use the `NostrServerTransport` with an `McpServer` from the `@modelcontextprotocol/sdk`:

```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { NostrServerTransport } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";

// 1. Configure the signer and relay pool
const signer = new PrivateKeySigner("your-server-private-key");
const relayPool = new SimpleRelayPool(["wss://relay.damus.io"]);

// 2. Create the McpServer instance
const mcpServer = new McpServer({
  name: "demo-server",
  version: "1.0.0",
});

// Register your server's tools, resources, etc.
// mcpServer.tool(...);

// 3. Create the NostrServerTransport instance
const serverNostrTransport = new NostrServerTransport({
  signer: signer,
  relayHandler: relayPool,
  serverInfo: {
    name: "My Awesome MCP Server",
    website: "https://example.com",
  },
  allowedPublicKeys: ["trusted-client-key"], // Only allow specific clients
  excludedCapabilities: [
    { method: "tools/list" }, // Allow any client to list available tools
    { method: "tools/call", name: "get_weather" }, // Allow any client to call get_weather tool
  ],
});

// 4. Connect the server
await mcpServer.connect(serverNostrTransport);

console.log("MCP server is running and available on Nostr.");

// Keep the process running...
// To shut down: await mcpServer.close();
```

## How It Works

1.  **`start()`**: When `mcpServer.connect()` is called, the transport connects to the relays and subscribes to events targeting the server's public key. If `isPublicServer` is `true`, it also initiates the announcement process.
2.  **Incoming Events**: The transport listens for events from clients. For each client, it maintains a `ClientSession`.
3.  **Request Handling**: When a valid request is received from an authorized client, the transport forwards it to the `McpServer`'s internal logic via the `onmessage` handler. It replaces the request's original ID with the unique Nostr event ID to prevent ID collisions between different clients.
4.  **Response Handling**: When the `McpServer` sends a response, the transport's `send()` method is called. The transport looks up the original request details from the client's session, restores the original request ID, and sends the response back to the correct client, referencing the original event ID.
5.  **Announcements**: If `isPublicServer` is true, the transport sends requests to its own `McpServer` for `initialize`, `tools/list`, etc. It then formats the responses into the appropriate replaceable Nostr events (kinds 11316-11320) and publishes them.

## Session Management

The `NostrServerTransport` manages a session for each unique client public key. Each session tracks:

- If the client has completed the MCP initialization handshake.
- Whether the session is encrypted.
- A map of pending requests to correlate responses.
- The timestamp of the last activity, used for cleaning up inactive sessions.

## Security and Policy Flexibility

The capability exclusion feature provides enhanced security policy flexibility by allowing you to create a whitelist-based security model with specific exceptions. This approach is particularly useful for:

### Use Cases

1. **Public Discovery**: Allow any client to discover your server's capabilities via `tools/list` while restricting actual tool usage to authorized clients.

2. **Limited Public Access**: Permit specific, safe operations from untrusted clients while maintaining security for sensitive operations.

3. **Backward Compatibility**: Gradually introduce stricter security policies while maintaining compatibility with existing clients.

4. **Tiered Access**: Create different levels of access where certain capabilities are available to all clients, while others require explicit authorization.

## Next Steps

Now that you understand how the transports work, let's dive into the **[Signer](/signer/nostr-signer-interface)**, the component responsible for cryptographic signatures.

================
File: docs/ts-sdk/tutorials/client-server-communication.md
================
---
title: Tutorial Client-Server Communication
description: A step-by-step guide to setting up a basic MCP client and server that communicate directly over the Nostr network using the @contextvm/sdk.
---

# Tutorial: Client-Server Communication

This tutorial provides a complete, step-by-step guide to setting up a basic MCP client and server that communicate directly over the Nostr network using the `@contextvm/sdk`.

## Objective

We will build two separate scripts:

1.  `server.ts`: An MCP server that exposes a simple "echo" tool.
2.  `client.ts`: An MCP client that connects to the server, lists the available tools, and calls the "echo" tool.

## Prerequisites

- You have completed the [Quick Overview](/getting-started/quick-overview/).
- You have two Nostr private keys (one for the server, one for the client). You can generate new keys using various tools, or by running `nostr-tools` commands.

---

## 1. The Server (`server.ts`)

First, let's create the MCP server. This server will use the `NostrServerTransport` to listen for requests on the Nostr network.

Create a new file named `server.ts`:

```typescript
import { NostrServerTransport } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
// --- Configuration ---
// IMPORTANT: Replace with your own private key
const SERVER_PRIVATE_KEY_HEX =
  process.env.SERVER_PRIVATE_KEY || "your-32-byte-server-private-key-in-hex";
const RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];

// --- Main Server Logic ---
async function main() {
  // 1. Setup Signer and Relay Pool
  const signer = new PrivateKeySigner(SERVER_PRIVATE_KEY_HEX);
  const relayPool = new SimpleRelayPool(RELAYS);
  const serverPubkey = await signer.getPublicKey();

  console.log(`Server Public Key: ${serverPubkey}`);
  console.log("Connecting to relays...");

  // 2. Create and Configure the MCP Server
  const mcpServer = new McpServer({
    name: "nostr-echo-server",
    version: "1.0.0",
  });

  // 3. Define a simple "echo" tool
  mcpServer.registerTool(
    "echo",
    {
      title: "Echo Tool",
      description: "Echoes back the provided message",
      inputSchema: { message: z.string() },
    },
    async ({ message }) => ({
      content: [{ type: "text", text: `Tool echo: ${message}` }],
    }),
  );

  // 4. Configure the Nostr Server Transport
  const serverTransport = new NostrServerTransport({
    signer,
    relayHandler: relayPool,
    serverInfo: {
      name: "CTXVM Echo Server",
    },
  });

  // 5. Connect the server
  await mcpServer.connect(serverTransport);

  console.log("Server is running and listening for requests on Nostr...");
  console.log("Press Ctrl+C to exit.");
}

main().catch((error) => {
  console.error("Failed to start server:", error);
  process.exit(1);
});
```

### Running the Server

To run the server, execute the following command in your terminal. Be sure to replace the placeholder private key or set the `SERVER_PRIVATE_KEY` environment variable.

```bash
bun run server.ts
```

The server will start, print its public key, and wait for incoming client connections.

---

## 2. The Client (`client.ts`)

Next, let's create the client that will connect to our server.

Create a new file named `client.ts`:

```typescript
import { Client } from "@modelcontextprotocol/sdk/client";
import { NostrClientTransport } from "@contextvm/sdk";
import { PrivateKeySigner } from "@contextvm/sdk";
import { SimpleRelayPool } from "@contextvm/sdk";

// --- Configuration ---
// IMPORTANT: Replace with the server's public key from the server output
const SERVER_PUBKEY = "the-public-key-printed-by-server.ts";

// IMPORTANT: Replace with your own private key
const CLIENT_PRIVATE_KEY_HEX =
  process.env.CLIENT_PRIVATE_KEY || "your-32-byte-client-private-key-in-hex";
const RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];

// --- Main Client Logic ---
async function main() {
  // 1. Setup Signer and Relay Pool
  const signer = new PrivateKeySigner(CLIENT_PRIVATE_KEY_HEX);
  const relayPool = new SimpleRelayPool(RELAYS);

  console.log("Connecting to relays...");

  // 2. Configure the Nostr Client Transport
  const clientTransport = new NostrClientTransport({
    signer,
    relayHandler: relayPool,
    serverPubkey: SERVER_PUBKEY,
  });

  // 3. Create and connect the MCP Client
  const mcpClient = new Client({
    name: "my-client",
    version: "0.0.1",
  });
  await mcpClient.connect(clientTransport);

  console.log("Connected to server!");

  // 4. List the available tools
  console.log("\nListing available tools...");
  const tools = await mcpClient.listTools();
  console.log("Tools:", tools);

  // 5. Call the "echo" tool
  console.log('\nCalling the "echo" tool...');
  const echoResult = await mcpClient.callTool({
    name: "echo",
    arguments: { message: "Hello, Nostr!" },
  });
  console.log("Echo result:", echoResult);

  // 6. Close the connection
  await mcpClient.close();
  console.log("\nConnection closed.");
}

main().catch((error) => {
  console.error("Client failed:", error);
  process.exit(1);
});
```

### Running the Client

Open a **new terminal window** (leave the server running in the first one). Before running the client, make sure to update the `SERVER_PUBKEY` variable with the public key that your `server.ts` script printed to the console.

Then, run the client:

```bash
bun run client.ts
```

## Expected Output

If everything is configured correctly, you should see the following output in the client's terminal:

```
Connecting to relays...
Connected to server!

Listing available tools...
Tools: {
  tools: [
    {
      name: 'echo',
      description: 'Replies with the input it received.',
      inputSchema: { ... }
    }
  ]
}

Calling the "echo" tool...
Echo result: You said: Hello, Nostr!

Connection closed.
```

And that's it! You've successfully created an MCP client and server that communicate securely and decentrally over the Nostr network.

================
File: docs/ts-sdk/quick-overview.md
================
---
title: Quick Overview
description: An overview of the @contextvm/sdk, including its modules and core concepts.
---

# SDK Quick Overview

This overview introduces the essential modules and core concepts of the `@contextvm/sdk`. Understanding these fundamentals will help you leverage the full power of the ContextVM protocol.

## Installation

`@contextvm/sdk` is distributed as an NPM package, making it easy to integrate into your project.

## Install the SDK

Run the following command in your terminal:

```bash
npm install @contextvm/sdk
```

This will install the SDK and its dependencies into your project.

**Note:** If you are using a different package manager than NPM, just replace `npm` with the appropriate command for your package manager.

## Modules Introduction

The SDK is organized into several modules, each providing a specific set of functionalities:

- **[Core](/core/interfaces)**: Contains fundamental definitions, constants, interfaces, and utilities (e.g., encryption, serialization).
- **[Logging](/core/logging)**: SDK logging conventions, configuration and best practices (Pino-based).
- **[Transports](/transports/base-nostr-transport)**: Critical for communication, this module provides `NostrClientTransport` and `NostrServerTransport` implementations for enabling MCP over Nostr.
- **[Signer](/signer/nostr-signer-interface)**: Provides cryptographic signing capabilities required for Nostr events
- **[Relay](/relay/relay-handler-interface)**: Manages Nostr relay connections, abstracting the complexity of relay interactions.
- **[Proxy](/proxy/overview)**: A client-side MCP server that connects to other servers through Nostr, exposing their capabilities locally, specially useful for clients that don't natively support Nostr transport.
- **[Gateway](/overview)**: An MCP server transport that binds to another MCP server, exposing its capabilities to the Nostr network, specially useful for servers that don't natively support Nostr transport.

## Core Concepts

The `@contextvm/sdk` is built around a few core concepts that enable the bridging of MCP and Nostr.

### Signers and Relay Handlers

At the heart of the SDK are two key interfaces:

- **`NostrSigner`**: An interface for signing Nostr events. The SDK includes a default `PrivateKeySigner`, but you can create a custom implementation to integrate with other signing mechanisms (e.g., Window.nostr for web, remote signers, etc).
- **`RelayHandler`**: An interface for managing connections to Nostr relays. The default `SimpleRelayPool` provides basic relay management, but you can implement your own logic for more sophisticated relay selection and management.

These components are fundamental for creating and broadcasting Nostr events, which are the backbone of ContextVM communication.

### Nostr Transports

The SDK provides two specialized transports to send and receive MCP messages over the Nostr network:

- [`NostrClientTransport`](/transports/nostr-client-transport): Used by MCP clients to connect to remote MCP servers exposed via Nostr.
- [`NostrServerTransport`](/transports/nostr-server-transport): Used by MCP servers to expose their capabilities through Nostr.

These transports handle the serialization of MCP messages into Nostr events and manage the communication flow.

### Bridging Components: Proxy and Gateway

To simplify integration with existing MCP applications, the SDK provides two high-level bridging components:

- [`NostrMCPProxy`](/proxy/overview): A client-side bridge that allows an MCP client to communicate with a remote MCP server over Nostr without requiring native Nostr support in the client.
- [`NostrMCPGateway`](/overview): A server-side bridge that exposes an existing MCP server to the Nostr network, allowing it to be discovered and used by Nostr-native clients.

These components abstract away the underlying transport complexities, making it easy to connect conventional MCP setups with the decentralized Nostr ecosystem.

## Next Steps

Now that you have a basic understanding of the SDK's modules and concepts, you are ready to dive deeper. Explore the **Core Modules** section to learn about the fundamental interfaces and data structures.

================
File: docs/index.md
================
---
title: ContextVM SDK Documentation
description: A comprehensive guide to the ContextVM SDK
---

# @contextvm/sdk: The Official SDK for the ContextVM Protocol

Welcome to the official documentation for the **@contextvm/sdk**, a JavaScript/TypeScript library for the Context Vending Machine (ContextVM) Protocol. This SDK provides the tools to bridge Nostr and the Model Context Protocol (MCP), enabling decentralized discovery, access and exposure of computational services.

## What is ContextVM?

The Context Vending Machine (ContextVM) protocol defines how [Nostr](https://nostr.com/) and Model Context Protocol can be used to expose MCP server capabilities. It enables standardized usage of these resources through a decentralized, cryptographically secure messaging system. By integrating MCP with Nostr, ContextVM offers:

- **Discoverability**: MCP servers can be discovered through the Nostr network without centralized registries.
- **Verifiability**: All messages are cryptographically signed using Nostr's public keys.
- **Authorization**: No complex authorization logic required, just cryptography.
- **Decentralization**: No single point of failure for service discovery or communication.
- **Protocol Interoperability**: Both MCP and ContextVMs utilize JSON-RPC patterns, enabling seamless communication.

This documentation serves as the primary entry point for developers and individuals interested in learning more about ContextVM and its SDK.

## SDK Overview

The `@contextvm/sdk` provides the necessary components to interact with the CTXVM Protocol:

- **Core Module**: Contains fundamental definitions, constants, interfaces, and utilities (e.g., encryption, serialization).
- **Transports**: Critical for communication, providing `NostrClientTransport` and `NostrServerTransport` implementations for enabling MCP over Nostr.
- **Proxy**: A client-side MCP server that connects to other servers through Nostr, exposing server capabilities locally. Particularly useful for clients that don't natively support Nostr transport.
- **Gateway**: Implements Nostr server transport, binding to another MCP server and exposing its capabilities through the Nostr network.
- **Relay**: Functionality for managing Nostr relays, abstracting relay interactions.
- **Signer**: Provides cryptographic signing capabilities required for Nostr events.

Both the Proxy and Gateway leverage Nostr transports, allowing existing MCP servers to maintain their conventional transports while gaining Nostr interoperability.

## How to Use These Docs

This documentation is structured to guide you from initial setup to advanced implementation. We recommend starting with the "Getting Started" section and then exploring the modules most relevant to your use case.

- **Getting Started**: Covers installation and a high-level overview of the SDK.
- **Core Modules**: Details the fundamental interfaces, encryption methods, and constants.
- **Transports, Signer, Relay**: Deep dives into the key components for communication and security.
- **Proxy & Gateway**: Explains how to use the bridging components.
- **Tutorials**: Provides practical, step-by-step examples.

Let's begin by setting up your environment in the [Quick Overview](getting-started/quick-overview/).

================
File: docs/index.mdx
================
---
title: ContextVM
description: The intersection of Nostr and MCP
template: splash
hero:
  tagline: The intersection of Nostr and MCP
  image:
    file: ../../assets/contextvm-logo.svg
  actions:
    - text: Get Started
      link: getting-started/quick-overview/
      icon: right-arrow
    - text: View on GitHub
      link: https://github.com/contextvm/ts-sdk
      icon: external
      variant: minimal
---

import { CardGrid } from "@astrojs/starlight/components";
import IconLinkCard from "../../components/IconLinkCard.astro";

## Core Concepts

<CardGrid stagger>
  <IconLinkCard
    title="Architecture"
    icon="rocket"
    href="https://github.com/ContextVM/sdk/blob/master/docs/ctxvm-draft-spec.md#complete-protocol-flow"
    description="Learn the foundational concepts and architecture of ContextVM"
  />
  <IconLinkCard
    title="SDK Documentation"
    icon="add-document"
    href="ts-sdk/quick-overview/"
    description="Explore our comprehensive documentation and implementation examples"
  />
  <IconLinkCard
    title="Integrations"
    icon="puzzle"
    href="ts-sdk/gateway/overview/#integration-scenarios"
    description="Discover how ContextVM integrates MCP with Nostr"
  />
  <IconLinkCard
    title="Tutorials"
    icon="open-book"
    href="ts-sdk/tutorials/client-server-communication/"
    description="Step-by-step guides to help you build with ContextVM"
  />
</CardGrid>




================================================================
End of Codebase
================================================================