@caspian2026/agent-sdk 0.0.24 → 0.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (362) hide show
  1. package/dist/gateway/index.js +98 -22
  2. package/dist/gateway/worker.js +196 -47
  3. package/dist/sdk/query.cjs +2 -362
  4. package/dist/sdk/query.js +2 -367
  5. package/package.json +4 -6
  6. package/dist/chunk-05kvhzd7.js +0 -3561
  7. package/dist/chunk-07069jq1.js +0 -30
  8. package/dist/chunk-0731m51q.js +0 -8
  9. package/dist/chunk-08bspa4b.js +0 -673
  10. package/dist/chunk-0brkf8q8.js +0 -89
  11. package/dist/chunk-0n843xh7.js +0 -261
  12. package/dist/chunk-0nbp5jwx.js +0 -8583
  13. package/dist/chunk-0nj16az9.js +0 -169
  14. package/dist/chunk-0paqc2yw.js +0 -15
  15. package/dist/chunk-0q6b50ps.js +0 -111
  16. package/dist/chunk-0r5bb9j4.js +0 -477
  17. package/dist/chunk-0rpz1wgn.js +0 -1030
  18. package/dist/chunk-0t81d427.js +0 -41
  19. package/dist/chunk-0vaw02wq.js +0 -24
  20. package/dist/chunk-0vkfrmqm.js +0 -690
  21. package/dist/chunk-0vp3wfab.js +0 -12
  22. package/dist/chunk-0vr10742.js +0 -1809
  23. package/dist/chunk-0xjaqda8.js +0 -1124
  24. package/dist/chunk-13ehyphg.js +0 -223
  25. package/dist/chunk-15jsw9bb.js +0 -349
  26. package/dist/chunk-16m7eyyw.js +0 -1385
  27. package/dist/chunk-1ae3nt9j.js +0 -31
  28. package/dist/chunk-1gq4r3v1.js +0 -308
  29. package/dist/chunk-1gx78081.js +0 -66
  30. package/dist/chunk-1h2famwb.js +0 -49
  31. package/dist/chunk-1n546sfg.js +0 -200
  32. package/dist/chunk-1qg06d60.js +0 -494
  33. package/dist/chunk-1t0rqstn.js +0 -146
  34. package/dist/chunk-1z8p2eqd.js +0 -40
  35. package/dist/chunk-1zjh9cc5.js +0 -266
  36. package/dist/chunk-20ahkkrb.js +0 -132
  37. package/dist/chunk-21pbfch8.js +0 -105
  38. package/dist/chunk-26wtxbdc.js +0 -13870
  39. package/dist/chunk-2fwze72g.js +0 -24
  40. package/dist/chunk-2gcbr1c7.js +0 -107
  41. package/dist/chunk-2grc1yr8.js +0 -654
  42. package/dist/chunk-2gzv8nrw.js +0 -205
  43. package/dist/chunk-2r212cvt.js +0 -253
  44. package/dist/chunk-2s74bt6e.js +0 -317
  45. package/dist/chunk-2v385w7r.js +0 -7422
  46. package/dist/chunk-2wtkvpp2.js +0 -167
  47. package/dist/chunk-31rsspfr.js +0 -418
  48. package/dist/chunk-3c25bcsw.js +0 -17
  49. package/dist/chunk-3jm08aaw.js +0 -91
  50. package/dist/chunk-3mgywd32.js +0 -8
  51. package/dist/chunk-3nk79af8.js +0 -8
  52. package/dist/chunk-3v4sk2py.js +0 -101
  53. package/dist/chunk-3vwft0eh.js +0 -349
  54. package/dist/chunk-3vy1jt9p.js +0 -1010
  55. package/dist/chunk-3wvqzq9w.js +0 -92
  56. package/dist/chunk-3wvv2s8d.js +0 -336
  57. package/dist/chunk-4060b3s2.js +0 -108
  58. package/dist/chunk-434e0vh4.js +0 -275
  59. package/dist/chunk-46dm23zs.js +0 -344
  60. package/dist/chunk-4bh4qs70.js +0 -209
  61. package/dist/chunk-4cxzbqws.js +0 -94
  62. package/dist/chunk-4jm600zv.js +0 -13
  63. package/dist/chunk-4k9d7gxv.js +0 -118
  64. package/dist/chunk-4nc3t6ms.js +0 -396
  65. package/dist/chunk-4pbx3g7s.js +0 -26
  66. package/dist/chunk-4qhh8bpa.js +0 -54
  67. package/dist/chunk-4v63px9y.js +0 -133
  68. package/dist/chunk-4xnnzt3j.js +0 -74
  69. package/dist/chunk-4zchh01h.js +0 -201
  70. package/dist/chunk-5216fha8.js +0 -1163
  71. package/dist/chunk-55raexh7.js +0 -14358
  72. package/dist/chunk-5bffhf64.js +0 -81
  73. package/dist/chunk-5ccdsxgy.js +0 -74
  74. package/dist/chunk-5ddh2hyn.js +0 -91
  75. package/dist/chunk-5e6ncq5j.js +0 -61
  76. package/dist/chunk-5ekyhb1w.js +0 -422
  77. package/dist/chunk-5fy4r8rv.js +0 -52
  78. package/dist/chunk-5h5kx2jd.js +0 -34
  79. package/dist/chunk-5mbgdvyz.js +0 -847
  80. package/dist/chunk-5n1jc02d.js +0 -87
  81. package/dist/chunk-5pysjah8.js +0 -1543
  82. package/dist/chunk-5ssfz438.js +0 -323
  83. package/dist/chunk-5z28bqne.js +0 -6748
  84. package/dist/chunk-603y0mmg.js +0 -50
  85. package/dist/chunk-62v5kkff.js +0 -90
  86. package/dist/chunk-64c1avct.js +0 -13
  87. package/dist/chunk-64r16v22.js +0 -162
  88. package/dist/chunk-64smdx4a.js +0 -418
  89. package/dist/chunk-66zry909.js +0 -11
  90. package/dist/chunk-68ffk5qa.js +0 -14
  91. package/dist/chunk-69n11zng.js +0 -436
  92. package/dist/chunk-6dj5t602.js +0 -341
  93. package/dist/chunk-6dngjwkh.js +0 -63
  94. package/dist/chunk-6nsd9606.js +0 -790
  95. package/dist/chunk-6pkh8frk.js +0 -253
  96. package/dist/chunk-6qcmt5eb.js +0 -251
  97. package/dist/chunk-6ww7451s.js +0 -60
  98. package/dist/chunk-6xgb0kqz.js +0 -90
  99. package/dist/chunk-72ys9m07.js +0 -121
  100. package/dist/chunk-741sgvtx.js +0 -121
  101. package/dist/chunk-7aw745vx.js +0 -40175
  102. package/dist/chunk-7c8b8cfb.js +0 -219
  103. package/dist/chunk-7mwt4e1z.js +0 -234
  104. package/dist/chunk-7sgtxrsc.js +0 -1059
  105. package/dist/chunk-7wm5s02e.js +0 -216
  106. package/dist/chunk-7xyswgjh.js +0 -8
  107. package/dist/chunk-80a197ez.js +0 -1438
  108. package/dist/chunk-83hfzbx3.js +0 -10
  109. package/dist/chunk-8akrsgad.js +0 -55
  110. package/dist/chunk-8g5pe1gr.js +0 -37
  111. package/dist/chunk-8s07t4k7.js +0 -40
  112. package/dist/chunk-8yhf030a.js +0 -69
  113. package/dist/chunk-928tzaa8.js +0 -107
  114. package/dist/chunk-949pjzj9.js +0 -266
  115. package/dist/chunk-9aycd4z9.js +0 -490
  116. package/dist/chunk-9bzqvsz5.js +0 -211
  117. package/dist/chunk-9q3xfy27.js +0 -460
  118. package/dist/chunk-9vzg1360.js +0 -153
  119. package/dist/chunk-9wbh8n1y.js +0 -63
  120. package/dist/chunk-9x5zgy22.js +0 -12
  121. package/dist/chunk-9zdj4ypz.js +0 -206
  122. package/dist/chunk-a0bvcgyd.js +0 -127
  123. package/dist/chunk-a4m3yr2q.js +0 -117
  124. package/dist/chunk-a8jd4gee.js +0 -227
  125. package/dist/chunk-ase86y73.js +0 -15
  126. package/dist/chunk-atfzpm6r.js +0 -325
  127. package/dist/chunk-awqsddp2.js +0 -338
  128. package/dist/chunk-awrgzpk6.js +0 -29
  129. package/dist/chunk-b0kf00ff.js +0 -637
  130. package/dist/chunk-b1kcd3ss.js +0 -27
  131. package/dist/chunk-b4hy21c4.js +0 -140
  132. package/dist/chunk-b9mkm8mg.js +0 -111
  133. package/dist/chunk-bdjx14rd.js +0 -594
  134. package/dist/chunk-bfb41q9h.js +0 -295
  135. package/dist/chunk-bg4x9ex0.js +0 -21
  136. package/dist/chunk-bh5zqvyc.js +0 -36
  137. package/dist/chunk-bn0zv2y2.js +0 -1154
  138. package/dist/chunk-bn7t681c.js +0 -2669
  139. package/dist/chunk-br4wgffc.js +0 -393
  140. package/dist/chunk-brjd9zmk.js +0 -42
  141. package/dist/chunk-byfawrfx.js +0 -121
  142. package/dist/chunk-c6sjhj89.js +0 -1284
  143. package/dist/chunk-c7jwbe76.js +0 -29030
  144. package/dist/chunk-cdef9v7b.js +0 -27
  145. package/dist/chunk-cdz5yb0r.js +0 -57
  146. package/dist/chunk-cevq1787.js +0 -2718
  147. package/dist/chunk-cgfdkzhb.js +0 -12
  148. package/dist/chunk-cgqw4x5z.js +0 -155
  149. package/dist/chunk-cmmmc8e0.js +0 -212
  150. package/dist/chunk-cnsj3vq2.js +0 -35
  151. package/dist/chunk-cxrktb5g.js +0 -51
  152. package/dist/chunk-cyhrb0bk.js +0 -251
  153. package/dist/chunk-d23rmn8r.js +0 -62
  154. package/dist/chunk-d4mdda98.js +0 -94
  155. package/dist/chunk-dcwp94cj.js +0 -152
  156. package/dist/chunk-ddsjkqs4.js +0 -39
  157. package/dist/chunk-ddv56j39.js +0 -148
  158. package/dist/chunk-dfq6pbq7.js +0 -5822
  159. package/dist/chunk-dfzkwynj.js +0 -5368
  160. package/dist/chunk-dkgkd8b7.js +0 -516
  161. package/dist/chunk-dpnmf0pq.js +0 -312
  162. package/dist/chunk-dygx7vcc.js +0 -226
  163. package/dist/chunk-e0abab5b.js +0 -445
  164. package/dist/chunk-e5qhvhjy.js +0 -168
  165. package/dist/chunk-e60y6r1n.js +0 -20
  166. package/dist/chunk-e68kgvcq.js +0 -79
  167. package/dist/chunk-e9w9zc0g.js +0 -392
  168. package/dist/chunk-ecj9w6tm.js +0 -558
  169. package/dist/chunk-ehtwnxpg.js +0 -1591
  170. package/dist/chunk-eqp1rfft.js +0 -17
  171. package/dist/chunk-etdt1xz3.js +0 -19
  172. package/dist/chunk-ewadzrm8.js +0 -103
  173. package/dist/chunk-f03s83vj.js +0 -91
  174. package/dist/chunk-f3kk0p3s.js +0 -150
  175. package/dist/chunk-f3pjerx4.js +0 -4265
  176. package/dist/chunk-f6h5weh6.js +0 -61
  177. package/dist/chunk-fajg8x36.js +0 -8158
  178. package/dist/chunk-fbv4apne.js +0 -51
  179. package/dist/chunk-fcynwjpm.js +0 -1072
  180. package/dist/chunk-fdvaf6nn.js +0 -20
  181. package/dist/chunk-feyzykye.js +0 -10
  182. package/dist/chunk-ff85rwvc.js +0 -180
  183. package/dist/chunk-fqak69ft.js +0 -458
  184. package/dist/chunk-fxdkbabd.js +0 -195
  185. package/dist/chunk-fyc5fepv.js +0 -10
  186. package/dist/chunk-g78c6ztj.js +0 -89
  187. package/dist/chunk-g8ee7yza.js +0 -105
  188. package/dist/chunk-g9f19ttm.js +0 -15
  189. package/dist/chunk-gcktsbxb.js +0 -77
  190. package/dist/chunk-gdwdqewd.js +0 -19
  191. package/dist/chunk-gg55fns0.js +0 -6440
  192. package/dist/chunk-gnpt1t6q.js +0 -209364
  193. package/dist/chunk-gsbw2j2b.js +0 -276
  194. package/dist/chunk-gybt680f.js +0 -9114
  195. package/dist/chunk-gz1e8y1w.js +0 -33
  196. package/dist/chunk-gz7vn2gg.js +0 -114
  197. package/dist/chunk-h0d5eat0.js +0 -101
  198. package/dist/chunk-h27tjbp3.js +0 -33118
  199. package/dist/chunk-h2yy8k4c.js +0 -58
  200. package/dist/chunk-h5acpdqt.js +0 -103
  201. package/dist/chunk-h63r8vps.js +0 -2840
  202. package/dist/chunk-h64x5b04.js +0 -860
  203. package/dist/chunk-h92snc84.js +0 -420
  204. package/dist/chunk-h9n54swm.js +0 -27
  205. package/dist/chunk-hafcrnpc.js +0 -145
  206. package/dist/chunk-hakdhagh.js +0 -16606
  207. package/dist/chunk-hk4phsaw.js +0 -388
  208. package/dist/chunk-hph1bmqw.js +0 -65
  209. package/dist/chunk-hvnztnp3.js +0 -71
  210. package/dist/chunk-hwfknpxv.js +0 -39
  211. package/dist/chunk-j2xxd002.js +0 -1052
  212. package/dist/chunk-j3qbygme.js +0 -105
  213. package/dist/chunk-j5bth84e.js +0 -97
  214. package/dist/chunk-j64ga6ta.js +0 -8035
  215. package/dist/chunk-jbwgyskk.js +0 -385
  216. package/dist/chunk-jd32zbps.js +0 -15
  217. package/dist/chunk-jdhkh2bb.js +0 -618
  218. package/dist/chunk-jeqcwgt7.js +0 -177
  219. package/dist/chunk-jf75p9ap.js +0 -445
  220. package/dist/chunk-jgvk0za1.js +0 -260
  221. package/dist/chunk-jhpaevah.js +0 -565
  222. package/dist/chunk-jmjwrbwd.js +0 -635
  223. package/dist/chunk-jpdbfwvq.js +0 -100
  224. package/dist/chunk-jps4m6sz.js +0 -183
  225. package/dist/chunk-jwf0s51s.js +0 -867
  226. package/dist/chunk-jxge4dgh.js +0 -83
  227. package/dist/chunk-jz71gv95.js +0 -1161
  228. package/dist/chunk-jzthz1bx.js +0 -15
  229. package/dist/chunk-jzvd2ycp.js +0 -120
  230. package/dist/chunk-k0p9w03v.js +0 -4957
  231. package/dist/chunk-k4dcreh0.js +0 -442
  232. package/dist/chunk-k7akhwkn.js +0 -151
  233. package/dist/chunk-k8vp0atq.js +0 -2331
  234. package/dist/chunk-kgd7gfvk.js +0 -407
  235. package/dist/chunk-km5ycg1j.js +0 -87
  236. package/dist/chunk-kvyrxzj8.js +0 -26
  237. package/dist/chunk-kwekc97v.js +0 -18
  238. package/dist/chunk-ky1z78ve.js +0 -119
  239. package/dist/chunk-mcws22k3.js +0 -42
  240. package/dist/chunk-mjazvyd8.js +0 -528
  241. package/dist/chunk-mswx2nma.js +0 -103
  242. package/dist/chunk-mz6a0phh.js +0 -2962
  243. package/dist/chunk-n2tg12hg.js +0 -374
  244. package/dist/chunk-n3fv4ya7.js +0 -146
  245. package/dist/chunk-n4eabmqd.js +0 -93
  246. package/dist/chunk-n4tx7baq.js +0 -193
  247. package/dist/chunk-n6g4jbeh.js +0 -289
  248. package/dist/chunk-n6wzfxf1.js +0 -100
  249. package/dist/chunk-ndcmqfkv.js +0 -244
  250. package/dist/chunk-netzwgv1.js +0 -154
  251. package/dist/chunk-nhcg04jt.js +0 -120
  252. package/dist/chunk-nhsm3ntd.js +0 -439
  253. package/dist/chunk-njev89d1.js +0 -2335
  254. package/dist/chunk-nmgj86tt.js +0 -24
  255. package/dist/chunk-ns7x6xam.js +0 -22820
  256. package/dist/chunk-p7vkh4wx.js +0 -15
  257. package/dist/chunk-p8na2wwp.js +0 -14
  258. package/dist/chunk-p97fd5af.js +0 -684
  259. package/dist/chunk-pe3rkfp2.js +0 -74
  260. package/dist/chunk-pgtnj1mt.js +0 -705
  261. package/dist/chunk-phmnkw9y.js +0 -283
  262. package/dist/chunk-pnds7g1q.js +0 -130
  263. package/dist/chunk-ppwjyveh.js +0 -8
  264. package/dist/chunk-pqqxdk5f.js +0 -543
  265. package/dist/chunk-ps49ymvj.js +0 -43
  266. package/dist/chunk-pwwa7s62.js +0 -11
  267. package/dist/chunk-q3hfrat2.js +0 -313
  268. package/dist/chunk-qajrkk97.js +0 -298
  269. package/dist/chunk-qatfdxvd.js +0 -34
  270. package/dist/chunk-qb5qcctj.js +0 -206
  271. package/dist/chunk-qb6k2afy.js +0 -153
  272. package/dist/chunk-qgk93a75.js +0 -85
  273. package/dist/chunk-qkczt8cr.js +0 -24
  274. package/dist/chunk-qn1be1vf.js +0 -267
  275. package/dist/chunk-qnfx3qtx.js +0 -617
  276. package/dist/chunk-qnwne2m4.js +0 -87
  277. package/dist/chunk-qp2qdcda.js +0 -100
  278. package/dist/chunk-qpp3wwh5.js +0 -697
  279. package/dist/chunk-r0bx1gc7.js +0 -174
  280. package/dist/chunk-radnwk8x.js +0 -107
  281. package/dist/chunk-rkv5jq0y.js +0 -71
  282. package/dist/chunk-rmbbmd3s.js +0 -68
  283. package/dist/chunk-rmgbs5an.js +0 -640
  284. package/dist/chunk-rn0v1hk8.js +0 -34
  285. package/dist/chunk-rnxctq9p.js +0 -1646
  286. package/dist/chunk-rtd39n81.js +0 -95
  287. package/dist/chunk-s8gy4ky9.js +0 -122
  288. package/dist/chunk-s8kj6ajy.js +0 -32
  289. package/dist/chunk-sd36yzx8.js +0 -954
  290. package/dist/chunk-sdenh194.js +0 -121
  291. package/dist/chunk-sdtqp75c.js +0 -55
  292. package/dist/chunk-sedbc8ep.js +0 -212
  293. package/dist/chunk-sfrb15b2.js +0 -321
  294. package/dist/chunk-sgpmpn90.js +0 -35
  295. package/dist/chunk-sh02d2qn.js +0 -38
  296. package/dist/chunk-shd4yhsf.js +0 -32
  297. package/dist/chunk-shkycj1q.js +0 -178
  298. package/dist/chunk-sk7h93je.js +0 -153
  299. package/dist/chunk-sm8g6fsm.js +0 -122
  300. package/dist/chunk-snrjy66h.js +0 -671
  301. package/dist/chunk-sq4a0yjh.js +0 -116
  302. package/dist/chunk-sr3t4thh.js +0 -895
  303. package/dist/chunk-srj6qnf6.js +0 -107
  304. package/dist/chunk-sz62n77p.js +0 -155
  305. package/dist/chunk-szj5wvdy.js +0 -28
  306. package/dist/chunk-t29a6zb5.js +0 -45
  307. package/dist/chunk-t2ecddwj.js +0 -731
  308. package/dist/chunk-t33hmmmm.js +0 -113
  309. package/dist/chunk-t4khqff1.js +0 -16
  310. package/dist/chunk-t9p85zff.js +0 -24
  311. package/dist/chunk-ta3jyvxs.js +0 -984
  312. package/dist/chunk-tkx5eec8.js +0 -54
  313. package/dist/chunk-v1kzp02e.js +0 -785
  314. package/dist/chunk-v4t6dyyh.js +0 -9076
  315. package/dist/chunk-v78fj8by.js +0 -145
  316. package/dist/chunk-v8kjswxt.js +0 -61
  317. package/dist/chunk-v9smspw2.js +0 -4301
  318. package/dist/chunk-vf612n57.js +0 -472
  319. package/dist/chunk-vkhrrvfq.js +0 -44
  320. package/dist/chunk-vt5wm07k.js +0 -74
  321. package/dist/chunk-vvvrv61g.js +0 -875
  322. package/dist/chunk-vyjeh50y.js +0 -2149
  323. package/dist/chunk-w0kxcv73.js +0 -97
  324. package/dist/chunk-w6m6trzq.js +0 -58
  325. package/dist/chunk-wa8yn2p0.js +0 -2007
  326. package/dist/chunk-wb18cecv.js +0 -995
  327. package/dist/chunk-wgk9sxk7.js +0 -329
  328. package/dist/chunk-wh0ev1bw.js +0 -111
  329. package/dist/chunk-wka1647p.js +0 -98
  330. package/dist/chunk-wnwfwyj4.js +0 -90
  331. package/dist/chunk-wpdchyy2.js +0 -97
  332. package/dist/chunk-x3g44n7k.js +0 -114
  333. package/dist/chunk-x47h283a.js +0 -56
  334. package/dist/chunk-x6r4v44b.js +0 -8
  335. package/dist/chunk-x7fdwq3d.js +0 -33
  336. package/dist/chunk-x8d2ehd7.js +0 -19
  337. package/dist/chunk-xbeg2hej.js +0 -257
  338. package/dist/chunk-xeb6075z.js +0 -3435
  339. package/dist/chunk-xhfmdq1y.js +0 -147
  340. package/dist/chunk-xhscn33a.js +0 -138
  341. package/dist/chunk-xv3era3s.js +0 -8
  342. package/dist/chunk-xz5gbhc3.js +0 -93
  343. package/dist/chunk-y1784krc.js +0 -19
  344. package/dist/chunk-y1vyezct.js +0 -123
  345. package/dist/chunk-y45ecntg.js +0 -942
  346. package/dist/chunk-y4ca9kqz.js +0 -3830
  347. package/dist/chunk-y9bhjjdz.js +0 -145
  348. package/dist/chunk-yb3bxv3w.js +0 -30
  349. package/dist/chunk-ye2q9gqj.js +0 -332
  350. package/dist/chunk-yfg3adfq.js +0 -88
  351. package/dist/chunk-yst0wmgw.js +0 -269
  352. package/dist/chunk-ywe9dbnz.js +0 -460
  353. package/dist/chunk-yyex5gsf.js +0 -269
  354. package/dist/chunk-yz2kzqk5.js +0 -439
  355. package/dist/chunk-z263ehpg.js +0 -131
  356. package/dist/chunk-z2dp53wn.js +0 -17
  357. package/dist/chunk-zaq348h2.js +0 -281
  358. package/dist/chunk-zr0qx9q0.js +0 -642
  359. package/dist/chunk-zxh62ved.js +0 -31
  360. package/dist/chunk-zy5vn8sd.js +0 -329
  361. package/dist/chunk-zzm33q8x.js +0 -8
  362. package/dist/cli.js +0 -91
@@ -1,2007 +0,0 @@
1
- // @bun
2
- import {
3
- CallToolRequestSchema,
4
- ListToolsRequestSchema,
5
- Server,
6
- init_server,
7
- init_types
8
- } from "./chunk-v4t6dyyh.js";
9
- import {
10
- __esm,
11
- __require
12
- } from "./chunk-qp2qdcda.js";
13
-
14
- // packages/@ant/claude-for-chrome-mcp/src/mcpSocketClient.ts
15
- import { promises as fsPromises } from "fs";
16
- import { createConnection } from "net";
17
- import { platform } from "os";
18
- import { dirname } from "path";
19
- function isToolResponse(message) {
20
- return "result" in message || "error" in message;
21
- }
22
- function isNotification(message) {
23
- return "method" in message && typeof message.method === "string";
24
- }
25
-
26
- class McpSocketClient {
27
- socket = null;
28
- connected = false;
29
- connecting = false;
30
- responseCallback = null;
31
- notificationHandler = null;
32
- responseBuffer = Buffer.alloc(0);
33
- reconnectAttempts = 0;
34
- maxReconnectAttempts = 10;
35
- reconnectDelay = 1000;
36
- reconnectTimer = null;
37
- context;
38
- disableAutoReconnect = false;
39
- constructor(context) {
40
- this.context = context;
41
- }
42
- async connect() {
43
- const { serverName, logger } = this.context;
44
- if (this.connecting) {
45
- logger.info(`[${serverName}] Already connecting, skipping duplicate attempt`);
46
- return;
47
- }
48
- this.closeSocket();
49
- this.connecting = true;
50
- const socketPath = this.context.getSocketPath?.() ?? this.context.socketPath;
51
- logger.info(`[${serverName}] Attempting to connect to: ${socketPath}`);
52
- try {
53
- await this.validateSocketSecurity(socketPath);
54
- } catch (error) {
55
- this.connecting = false;
56
- logger.info(`[${serverName}] Security validation failed:`, error);
57
- return;
58
- }
59
- this.socket = createConnection(socketPath);
60
- const connectTimeout = setTimeout(() => {
61
- if (!this.connected) {
62
- logger.info(`[${serverName}] Connection attempt timed out after 5000ms`);
63
- this.closeSocket();
64
- this.scheduleReconnect();
65
- }
66
- }, 5000);
67
- this.socket.on("connect", () => {
68
- clearTimeout(connectTimeout);
69
- this.connected = true;
70
- this.connecting = false;
71
- this.reconnectAttempts = 0;
72
- logger.info(`[${serverName}] Successfully connected to bridge server`);
73
- });
74
- this.socket.on("data", (data) => {
75
- this.responseBuffer = Buffer.concat([this.responseBuffer, data]);
76
- while (this.responseBuffer.length >= 4) {
77
- const length = this.responseBuffer.readUInt32LE(0);
78
- if (this.responseBuffer.length < 4 + length) {
79
- break;
80
- }
81
- const messageBytes = this.responseBuffer.slice(4, 4 + length);
82
- this.responseBuffer = this.responseBuffer.slice(4 + length);
83
- try {
84
- const message = JSON.parse(messageBytes.toString("utf-8"));
85
- if (isNotification(message)) {
86
- logger.info(`[${serverName}] Received notification: ${message.method}`);
87
- if (this.notificationHandler) {
88
- this.notificationHandler(message);
89
- }
90
- } else if (isToolResponse(message)) {
91
- logger.info(`[${serverName}] Received tool response: ${message}`);
92
- this.handleResponse(message);
93
- } else {
94
- logger.info(`[${serverName}] Received unknown message: ${message}`);
95
- }
96
- } catch (error) {
97
- logger.info(`[${serverName}] Failed to parse message:`, error);
98
- }
99
- }
100
- });
101
- this.socket.on("error", (error) => {
102
- clearTimeout(connectTimeout);
103
- logger.info(`[${serverName}] Socket error (code: ${error.code}):`, error);
104
- this.connected = false;
105
- this.connecting = false;
106
- if (error.code && [
107
- "ECONNREFUSED",
108
- "ECONNRESET",
109
- "EPIPE",
110
- "ENOENT",
111
- "EOPNOTSUPP",
112
- "ECONNABORTED"
113
- ].includes(error.code)) {
114
- this.scheduleReconnect();
115
- }
116
- });
117
- this.socket.on("close", () => {
118
- clearTimeout(connectTimeout);
119
- this.connected = false;
120
- this.connecting = false;
121
- this.scheduleReconnect();
122
- });
123
- }
124
- scheduleReconnect() {
125
- const { serverName, logger } = this.context;
126
- if (this.disableAutoReconnect) {
127
- return;
128
- }
129
- if (this.reconnectTimer) {
130
- logger.info(`[${serverName}] Reconnect already scheduled, skipping`);
131
- return;
132
- }
133
- this.reconnectAttempts++;
134
- const maxTotalAttempts = 100;
135
- if (this.reconnectAttempts > maxTotalAttempts) {
136
- logger.info(`[${serverName}] Giving up after ${maxTotalAttempts} attempts. Will retry on next tool call.`);
137
- this.reconnectAttempts = 0;
138
- return;
139
- }
140
- const delay = Math.min(this.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1), 30000);
141
- if (this.reconnectAttempts <= this.maxReconnectAttempts) {
142
- logger.info(`[${serverName}] Reconnecting in ${Math.round(delay)}ms (attempt ${this.reconnectAttempts})`);
143
- } else if (this.reconnectAttempts % 10 === 0) {
144
- logger.info(`[${serverName}] Still polling for native host (attempt ${this.reconnectAttempts})`);
145
- }
146
- this.reconnectTimer = setTimeout(() => {
147
- this.reconnectTimer = null;
148
- this.connect();
149
- }, delay);
150
- }
151
- handleResponse(response) {
152
- if (this.responseCallback) {
153
- const callback = this.responseCallback;
154
- this.responseCallback = null;
155
- callback(response);
156
- }
157
- }
158
- setNotificationHandler(handler) {
159
- this.notificationHandler = handler;
160
- }
161
- async ensureConnected() {
162
- const { serverName } = this.context;
163
- if (this.connected && this.socket) {
164
- return true;
165
- }
166
- if (!this.socket && !this.connecting) {
167
- await this.connect();
168
- }
169
- return new Promise((resolve, reject) => {
170
- let checkTimeoutId = null;
171
- const timeout = setTimeout(() => {
172
- if (checkTimeoutId) {
173
- clearTimeout(checkTimeoutId);
174
- }
175
- reject(new SocketConnectionError(`[${serverName}] Connection attempt timed out after 5000ms`));
176
- }, 5000);
177
- const checkConnection = () => {
178
- if (this.connected) {
179
- clearTimeout(timeout);
180
- resolve(true);
181
- } else {
182
- checkTimeoutId = setTimeout(checkConnection, 500);
183
- }
184
- };
185
- checkConnection();
186
- });
187
- }
188
- async sendRequest(request, timeoutMs = 30000) {
189
- const { serverName } = this.context;
190
- if (!this.socket) {
191
- throw new SocketConnectionError(`[${serverName}] Cannot send request: not connected`);
192
- }
193
- const socket = this.socket;
194
- return new Promise((resolve, reject) => {
195
- const timeout = setTimeout(() => {
196
- this.responseCallback = null;
197
- reject(new SocketConnectionError(`[${serverName}] Tool request timed out after ${timeoutMs}ms`));
198
- }, timeoutMs);
199
- this.responseCallback = (response) => {
200
- clearTimeout(timeout);
201
- resolve(response);
202
- };
203
- const requestJson = JSON.stringify(request);
204
- const requestBytes = Buffer.from(requestJson, "utf-8");
205
- const lengthPrefix = Buffer.allocUnsafe(4);
206
- lengthPrefix.writeUInt32LE(requestBytes.length, 0);
207
- const message = Buffer.concat([lengthPrefix, requestBytes]);
208
- socket.write(message);
209
- });
210
- }
211
- async callTool(name, args, _permissionOverrides) {
212
- const request = {
213
- method: "execute_tool",
214
- params: {
215
- client_id: this.context.clientTypeId,
216
- tool: name,
217
- args
218
- }
219
- };
220
- return this.sendRequestWithRetry(request);
221
- }
222
- async sendRequestWithRetry(request) {
223
- const { serverName, logger } = this.context;
224
- try {
225
- return await this.sendRequest(request);
226
- } catch (error) {
227
- if (!(error instanceof SocketConnectionError)) {
228
- throw error;
229
- }
230
- logger.info(`[${serverName}] Connection error, forcing reconnect and retrying: ${error.message}`);
231
- this.closeSocket();
232
- await this.ensureConnected();
233
- return await this.sendRequest(request);
234
- }
235
- }
236
- async setPermissionMode(_mode, _allowedDomains) {}
237
- isConnected() {
238
- return this.connected;
239
- }
240
- closeSocket() {
241
- if (this.socket) {
242
- this.socket.removeAllListeners();
243
- this.socket.end();
244
- this.socket.destroy();
245
- this.socket = null;
246
- }
247
- this.connected = false;
248
- this.connecting = false;
249
- }
250
- cleanup() {
251
- if (this.reconnectTimer) {
252
- clearTimeout(this.reconnectTimer);
253
- this.reconnectTimer = null;
254
- }
255
- this.closeSocket();
256
- this.reconnectAttempts = 0;
257
- this.responseBuffer = Buffer.alloc(0);
258
- this.responseCallback = null;
259
- }
260
- disconnect() {
261
- this.cleanup();
262
- }
263
- async validateSocketSecurity(socketPath) {
264
- const { serverName, logger } = this.context;
265
- if (platform() === "win32") {
266
- return;
267
- }
268
- try {
269
- const dirPath = dirname(socketPath);
270
- const dirBasename = dirPath.split("/").pop() || "";
271
- const isSocketDir = dirBasename.startsWith("claude-mcp-browser-bridge-");
272
- if (isSocketDir) {
273
- try {
274
- const dirStats = await fsPromises.stat(dirPath);
275
- if (dirStats.isDirectory()) {
276
- const dirMode = dirStats.mode & 511;
277
- if (dirMode !== 448) {
278
- throw new Error(`[${serverName}] Insecure socket directory permissions: ${dirMode.toString(8)} (expected 0700). Directory may have been tampered with.`);
279
- }
280
- const currentUid2 = process.getuid?.();
281
- if (currentUid2 !== undefined && dirStats.uid !== currentUid2) {
282
- throw new Error(`Socket directory not owned by current user (uid: ${currentUid2}, dir uid: ${dirStats.uid}). ` + `Potential security risk.`);
283
- }
284
- }
285
- } catch (dirError) {
286
- if (dirError.code !== "ENOENT") {
287
- throw dirError;
288
- }
289
- }
290
- }
291
- const stats = await fsPromises.stat(socketPath);
292
- if (!stats.isSocket()) {
293
- throw new Error(`[${serverName}] Path exists but it's not a socket: ${socketPath}`);
294
- }
295
- const mode = stats.mode & 511;
296
- if (mode !== 384) {
297
- throw new Error(`[${serverName}] Insecure socket permissions: ${mode.toString(8)} (expected 0600). Socket may have been tampered with.`);
298
- }
299
- const currentUid = process.getuid?.();
300
- if (currentUid !== undefined && stats.uid !== currentUid) {
301
- throw new Error(`Socket not owned by current user (uid: ${currentUid}, socket uid: ${stats.uid}). ` + `Potential security risk.`);
302
- }
303
- logger.info(`[${serverName}] Socket security validation passed`);
304
- } catch (error) {
305
- if (error.code === "ENOENT") {
306
- logger.info(`[${serverName}] Socket not found, will be created by server`);
307
- return;
308
- }
309
- throw error;
310
- }
311
- }
312
- }
313
- function createMcpSocketClient(context) {
314
- return new McpSocketClient(context);
315
- }
316
- var SocketConnectionError;
317
- var init_mcpSocketClient = __esm(() => {
318
- SocketConnectionError = class SocketConnectionError extends Error {
319
- constructor(message) {
320
- super(message);
321
- this.name = "SocketConnectionError";
322
- }
323
- };
324
- });
325
-
326
- // packages/@ant/claude-for-chrome-mcp/src/types.ts
327
- function localPlatformLabel() {
328
- return process.platform === "darwin" ? "macOS" : process.platform === "win32" ? "Windows" : "Linux";
329
- }
330
- var init_types2 = () => {};
331
-
332
- // packages/@ant/claude-for-chrome-mcp/src/bridgeClient.ts
333
- class BridgeClient {
334
- ws = null;
335
- connected = false;
336
- authenticated = false;
337
- connecting = false;
338
- reconnectTimer = null;
339
- reconnectAttempts = 0;
340
- pendingCalls = new Map;
341
- notificationHandler = null;
342
- context;
343
- permissionMode = "ask";
344
- allowedDomains;
345
- tabsContextCollectionTimeoutMs = 2000;
346
- toolCallTimeoutMs = 120000;
347
- connectionStartTime = null;
348
- connectionEstablishedTime = null;
349
- selectedDeviceId;
350
- discoveryComplete = false;
351
- discoveryPromise = null;
352
- pendingDiscovery = null;
353
- previousSelectedDeviceId;
354
- peerConnectedWaiters = [];
355
- pendingPairingRequestId;
356
- pairingInProgress = false;
357
- persistedDeviceId;
358
- pendingSwitchResolve = null;
359
- constructor(context) {
360
- this.context = context;
361
- if (context.initialPermissionMode) {
362
- this.permissionMode = context.initialPermissionMode;
363
- }
364
- }
365
- async ensureConnected() {
366
- const { logger, serverName } = this.context;
367
- logger.info(`[${serverName}] ensureConnected called, connected=${this.connected}, authenticated=${this.authenticated}, wsState=${this.ws?.readyState}`);
368
- if (this.connected && this.authenticated && this.ws?.readyState === WS_OPEN) {
369
- logger.info(`[${serverName}] Already connected and authenticated`);
370
- return true;
371
- }
372
- if (!this.connecting) {
373
- logger.info(`[${serverName}] Not connecting, starting connection...`);
374
- await this.connect();
375
- } else {
376
- logger.info(`[${serverName}] Already connecting, waiting...`);
377
- }
378
- return new Promise((resolve) => {
379
- const timeout = setTimeout(() => {
380
- logger.info(`[${serverName}] Connection timeout, connected=${this.connected}, authenticated=${this.authenticated}`);
381
- resolve(false);
382
- }, 1e4);
383
- const check = () => {
384
- if (this.connected && this.authenticated) {
385
- logger.info(`[${serverName}] Connection successful`);
386
- clearTimeout(timeout);
387
- resolve(true);
388
- } else if (!this.connecting) {
389
- logger.info(`[${serverName}] No longer connecting, giving up`);
390
- clearTimeout(timeout);
391
- resolve(false);
392
- } else {
393
- setTimeout(check, 200);
394
- }
395
- };
396
- check();
397
- });
398
- }
399
- async callTool(name, args, permissionOverrides) {
400
- const { logger, serverName, trackEvent } = this.context;
401
- if (!this.ws || this.ws.readyState !== WS_OPEN) {
402
- throw new SocketConnectionError(`[${serverName}] Bridge not connected`);
403
- }
404
- if (!this.selectedDeviceId && !this.discoveryComplete) {
405
- this.discoveryPromise ??= this.discoverAndSelectExtension().finally(() => {
406
- this.discoveryPromise = null;
407
- });
408
- await this.discoveryPromise;
409
- }
410
- const toolUseId = crypto.randomUUID();
411
- const isTabsContext = name === "tabs_context_mcp";
412
- const startTime = Date.now();
413
- const timeoutMs = isTabsContext ? this.tabsContextCollectionTimeoutMs : this.toolCallTimeoutMs;
414
- trackEvent?.("chrome_bridge_tool_call_started", {
415
- tool_name: name,
416
- tool_use_id: toolUseId
417
- });
418
- const effectivePermissionMode = permissionOverrides?.permissionMode ?? this.permissionMode;
419
- const effectiveAllowedDomains = permissionOverrides?.allowedDomains ?? this.allowedDomains;
420
- return new Promise((resolve, reject) => {
421
- const timer = setTimeout(() => {
422
- const pending = this.pendingCalls.get(toolUseId);
423
- if (pending) {
424
- this.pendingCalls.delete(toolUseId);
425
- const durationMs = Date.now() - pending.startTime;
426
- if (isTabsContext && pending.results.length > 0) {
427
- trackEvent?.("chrome_bridge_tool_call_completed", {
428
- tool_name: name,
429
- tool_use_id: toolUseId,
430
- duration_ms: durationMs
431
- });
432
- resolve(this.mergeTabsResults(pending.results));
433
- } else {
434
- logger.warn(`[${serverName}] Tool call timeout: ${name} (${toolUseId.slice(0, 8)}) after ${durationMs}ms, pending calls: ${this.pendingCalls.size}`);
435
- trackEvent?.("chrome_bridge_tool_call_timeout", {
436
- tool_name: name,
437
- tool_use_id: toolUseId,
438
- duration_ms: durationMs,
439
- timeout_ms: timeoutMs
440
- });
441
- reject(new SocketConnectionError(`[${serverName}] Tool call timed out: ${name}`));
442
- }
443
- }
444
- }, timeoutMs);
445
- this.pendingCalls.set(toolUseId, {
446
- resolve,
447
- reject,
448
- timer,
449
- results: [],
450
- isTabsContext,
451
- onPermissionRequest: permissionOverrides?.onPermissionRequest,
452
- startTime,
453
- toolName: name
454
- });
455
- const message = {
456
- type: "tool_call",
457
- tool_use_id: toolUseId,
458
- client_type: this.context.clientTypeId,
459
- tool: name,
460
- args
461
- };
462
- if (this.selectedDeviceId) {
463
- message.target_device_id = this.selectedDeviceId;
464
- }
465
- if (effectivePermissionMode) {
466
- message.permission_mode = effectivePermissionMode;
467
- }
468
- if (effectiveAllowedDomains?.length) {
469
- message.allowed_domains = effectiveAllowedDomains;
470
- }
471
- if (permissionOverrides?.onPermissionRequest) {
472
- message.handle_permission_prompts = true;
473
- }
474
- logger.debug(`[${serverName}] Sending tool_call: ${name} (${toolUseId.slice(0, 8)})`);
475
- this.ws.send(JSON.stringify(message));
476
- });
477
- }
478
- isConnected() {
479
- return this.connected && this.authenticated && this.ws?.readyState === WS_OPEN;
480
- }
481
- disconnect() {
482
- this.cleanup();
483
- }
484
- setNotificationHandler(handler) {
485
- this.notificationHandler = handler;
486
- }
487
- async setPermissionMode(mode, allowedDomains) {
488
- this.permissionMode = mode;
489
- this.allowedDomains = allowedDomains;
490
- }
491
- async discoverAndSelectExtension() {
492
- const { logger, serverName } = this.context;
493
- this.persistedDeviceId ??= this.context.getPersistedDeviceId?.();
494
- let extensions = await this.queryBridgeExtensions();
495
- if (extensions.length === 0) {
496
- logger.info(`[${serverName}] No extensions connected, waiting up to ${PEER_WAIT_TIMEOUT_MS}ms for peer_connected`);
497
- const peerArrived = await this.waitForPeerConnected(PEER_WAIT_TIMEOUT_MS);
498
- if (peerArrived) {
499
- extensions = await this.queryBridgeExtensions();
500
- }
501
- }
502
- this.discoveryComplete = true;
503
- if (extensions.length === 0) {
504
- logger.info(`[${serverName}] No extensions found after waiting`);
505
- return;
506
- }
507
- if (extensions.length === 1) {
508
- const ext = extensions[0];
509
- if (!this.isLocalExtension(ext)) {
510
- this.context.onRemoteExtensionWarning?.(ext);
511
- }
512
- this.selectExtension(ext.deviceId);
513
- return;
514
- }
515
- if (this.persistedDeviceId) {
516
- const persisted = extensions.find((e) => e.deviceId === this.persistedDeviceId);
517
- if (persisted) {
518
- logger.info(`[${serverName}] Auto-connecting to persisted extension: ${persisted.name || persisted.deviceId.slice(0, 8)}`);
519
- this.selectExtension(persisted.deviceId);
520
- return;
521
- }
522
- }
523
- this.broadcastPairingRequest();
524
- this.pairingInProgress = true;
525
- }
526
- async queryBridgeExtensions() {
527
- const raw = await new Promise((resolve) => {
528
- const timeout = setTimeout(() => {
529
- this.pendingDiscovery = null;
530
- resolve([]);
531
- }, DISCOVERY_TIMEOUT_MS);
532
- this.pendingDiscovery = { resolve, timeout };
533
- this.ws?.send(JSON.stringify({ type: "list_extensions" }));
534
- });
535
- const byDeviceId = new Map;
536
- for (const ext of raw) {
537
- const existing = byDeviceId.get(ext.deviceId);
538
- if (!existing || ext.connectedAt > existing.connectedAt) {
539
- byDeviceId.set(ext.deviceId, ext);
540
- }
541
- }
542
- return [...byDeviceId.values()];
543
- }
544
- selectExtension(deviceId) {
545
- const { logger, serverName } = this.context;
546
- this.selectedDeviceId = deviceId;
547
- this.previousSelectedDeviceId = undefined;
548
- logger.info(`[${serverName}] Selected Chrome extension: ${deviceId.slice(0, 8)}...`);
549
- }
550
- isLocalExtension(ext) {
551
- if (!ext.osPlatform)
552
- return false;
553
- return ext.osPlatform === localPlatformLabel();
554
- }
555
- waitForPeerConnected(timeoutMs) {
556
- return new Promise((resolve) => {
557
- const timer = setTimeout(() => {
558
- this.peerConnectedWaiters = this.peerConnectedWaiters.filter((w) => w !== onPeer);
559
- resolve(false);
560
- }, timeoutMs);
561
- const onPeer = (arrived) => {
562
- clearTimeout(timer);
563
- resolve(arrived);
564
- };
565
- this.peerConnectedWaiters.push(onPeer);
566
- });
567
- }
568
- broadcastPairingRequest() {
569
- const requestId = crypto.randomUUID();
570
- this.pendingPairingRequestId = requestId;
571
- this.ws?.send(JSON.stringify({
572
- type: "pairing_request",
573
- request_id: requestId,
574
- client_type: this.context.clientTypeId
575
- }));
576
- }
577
- async switchBrowser() {
578
- const extensions = await this.queryBridgeExtensions();
579
- const currentDeviceId = this.selectedDeviceId ?? this.previousSelectedDeviceId;
580
- if (extensions.length === 0 || extensions.length === 1 && (!currentDeviceId || extensions[0].deviceId === currentDeviceId)) {
581
- return "no_other_browsers";
582
- }
583
- this.previousSelectedDeviceId = this.selectedDeviceId;
584
- this.selectedDeviceId = undefined;
585
- this.discoveryComplete = false;
586
- this.pairingInProgress = false;
587
- const requestId = crypto.randomUUID();
588
- this.pendingPairingRequestId = requestId;
589
- if (this.ws?.readyState !== WS_OPEN) {
590
- return null;
591
- }
592
- this.ws.send(JSON.stringify({
593
- type: "pairing_request",
594
- request_id: requestId,
595
- client_type: this.context.clientTypeId
596
- }));
597
- if (this.pendingSwitchResolve) {
598
- this.pendingSwitchResolve(null);
599
- }
600
- return new Promise((resolve) => {
601
- const timer = setTimeout(() => {
602
- if (this.pendingPairingRequestId === requestId) {
603
- this.pendingPairingRequestId = undefined;
604
- }
605
- this.pendingSwitchResolve = null;
606
- resolve(null);
607
- }, 120000);
608
- this.pendingSwitchResolve = (result) => {
609
- clearTimeout(timer);
610
- this.pendingSwitchResolve = null;
611
- resolve(result);
612
- };
613
- });
614
- }
615
- async connect() {
616
- const { logger, serverName, bridgeConfig, trackEvent } = this.context;
617
- if (!bridgeConfig) {
618
- logger.error(`[${serverName}] No bridge config provided`);
619
- return;
620
- }
621
- if (this.connecting) {
622
- return;
623
- }
624
- this.connecting = true;
625
- this.authenticated = false;
626
- this.connectionStartTime = Date.now();
627
- this.closeSocket();
628
- let userId;
629
- let token;
630
- if (bridgeConfig.devUserId) {
631
- userId = bridgeConfig.devUserId;
632
- logger.debug(`[${serverName}] Using dev user ID for bridge connection`);
633
- } else {
634
- logger.debug(`[${serverName}] Fetching user ID for bridge connection`);
635
- const fetchedUserId = await bridgeConfig.getUserId();
636
- if (!fetchedUserId) {
637
- const durationMs = Date.now() - this.connectionStartTime;
638
- logger.error(`[${serverName}] No user ID available after ${durationMs}ms`);
639
- trackEvent?.("chrome_bridge_connection_failed", {
640
- duration_ms: durationMs,
641
- error_type: "no_user_id",
642
- reconnect_attempt: this.reconnectAttempts
643
- });
644
- this.connecting = false;
645
- this.context.onAuthenticationError?.();
646
- return;
647
- }
648
- userId = fetchedUserId;
649
- logger.debug(`[${serverName}] Fetching OAuth token for bridge connection`);
650
- token = await bridgeConfig.getOAuthToken();
651
- if (!token) {
652
- const durationMs = Date.now() - this.connectionStartTime;
653
- logger.error(`[${serverName}] No OAuth token available after ${durationMs}ms`);
654
- trackEvent?.("chrome_bridge_connection_failed", {
655
- duration_ms: durationMs,
656
- error_type: "no_oauth_token",
657
- reconnect_attempt: this.reconnectAttempts
658
- });
659
- this.connecting = false;
660
- this.context.onAuthenticationError?.();
661
- return;
662
- }
663
- }
664
- const wsUrl = `${bridgeConfig.url}/chrome/${userId}`;
665
- logger.info(`[${serverName}] Connecting to bridge: ${wsUrl}`);
666
- trackEvent?.("chrome_bridge_connection_started", {
667
- bridge_url: wsUrl
668
- });
669
- try {
670
- const { default: WS } = await import("ws");
671
- this.ws = new WS(wsUrl);
672
- } catch (error) {
673
- const durationMs = Date.now() - this.connectionStartTime;
674
- logger.error(`[${serverName}] Failed to create WebSocket after ${durationMs}ms:`, error);
675
- trackEvent?.("chrome_bridge_connection_failed", {
676
- duration_ms: durationMs,
677
- error_type: "websocket_error",
678
- reconnect_attempt: this.reconnectAttempts
679
- });
680
- this.connecting = false;
681
- this.scheduleReconnect();
682
- return;
683
- }
684
- this.ws.on("open", () => {
685
- logger.info(`[${serverName}] WebSocket connected, sending connect message`);
686
- const connectMessage = {
687
- type: "connect",
688
- client_type: this.context.clientTypeId
689
- };
690
- if (bridgeConfig.devUserId) {
691
- connectMessage.dev_user_id = bridgeConfig.devUserId;
692
- } else {
693
- connectMessage.oauth_token = token;
694
- }
695
- this.ws?.send(JSON.stringify(connectMessage));
696
- });
697
- this.ws.on("message", (data) => {
698
- try {
699
- const message = JSON.parse(data.toString());
700
- logger.debug(`[${serverName}] Bridge received: ${JSON.stringify(message)}`);
701
- this.handleMessage(message);
702
- } catch (error) {
703
- logger.error(`[${serverName}] Failed to parse bridge message:`, error);
704
- }
705
- });
706
- this.ws.on("close", (code) => {
707
- const durationSinceConnect = this.connectionEstablishedTime ? Date.now() - this.connectionEstablishedTime : 0;
708
- logger.info(`[${serverName}] Bridge connection closed (code: ${code}, duration: ${durationSinceConnect}ms)`);
709
- trackEvent?.("chrome_bridge_disconnected", {
710
- close_code: code,
711
- duration_since_connect_ms: durationSinceConnect,
712
- reconnect_attempt: this.reconnectAttempts + 1
713
- });
714
- this.connected = false;
715
- this.authenticated = false;
716
- this.connecting = false;
717
- this.connectionEstablishedTime = null;
718
- this.scheduleReconnect();
719
- });
720
- this.ws.on("error", (error) => {
721
- const durationMs = this.connectionStartTime ? Date.now() - this.connectionStartTime : 0;
722
- logger.error(`[${serverName}] Bridge WebSocket error after ${durationMs}ms: ${error.message}`);
723
- trackEvent?.("chrome_bridge_connection_failed", {
724
- duration_ms: durationMs,
725
- error_type: "websocket_error",
726
- reconnect_attempt: this.reconnectAttempts
727
- });
728
- this.connected = false;
729
- this.authenticated = false;
730
- this.connecting = false;
731
- });
732
- }
733
- handleMessage(message) {
734
- const { logger, serverName, trackEvent } = this.context;
735
- switch (message.type) {
736
- case "paired": {
737
- const durationMs = this.connectionStartTime ? Date.now() - this.connectionStartTime : 0;
738
- logger.info(`[${serverName}] Paired with Chrome extension (duration: ${durationMs}ms)`);
739
- this.connected = true;
740
- this.authenticated = true;
741
- this.connecting = false;
742
- this.reconnectAttempts = 0;
743
- this.connectionEstablishedTime = Date.now();
744
- trackEvent?.("chrome_bridge_connection_succeeded", {
745
- duration_ms: durationMs,
746
- status: "paired"
747
- });
748
- break;
749
- }
750
- case "waiting": {
751
- const durationMs = this.connectionStartTime ? Date.now() - this.connectionStartTime : 0;
752
- logger.info(`[${serverName}] Waiting for Chrome extension to connect (duration: ${durationMs}ms)`);
753
- this.connected = true;
754
- this.authenticated = true;
755
- this.connecting = false;
756
- this.reconnectAttempts = 0;
757
- this.connectionEstablishedTime = Date.now();
758
- trackEvent?.("chrome_bridge_connection_succeeded", {
759
- duration_ms: durationMs,
760
- status: "waiting"
761
- });
762
- break;
763
- }
764
- case "peer_connected":
765
- logger.info(`[${serverName}] Chrome extension connected to bridge`);
766
- trackEvent?.("chrome_bridge_peer_connected", null);
767
- if (!this.selectedDeviceId) {
768
- this.discoveryComplete = false;
769
- }
770
- if (this.previousSelectedDeviceId && message.deviceId === this.previousSelectedDeviceId && !this.pendingSwitchResolve) {
771
- logger.info(`[${serverName}] Previously selected extension reconnected, auto-reselecting`);
772
- this.selectExtension(this.previousSelectedDeviceId);
773
- this.previousSelectedDeviceId = undefined;
774
- }
775
- if (this.peerConnectedWaiters.length > 0) {
776
- const waiters = this.peerConnectedWaiters;
777
- this.peerConnectedWaiters = [];
778
- for (const waiter of waiters) {
779
- waiter(true);
780
- }
781
- }
782
- break;
783
- case "peer_disconnected":
784
- logger.info(`[${serverName}] Chrome extension disconnected from bridge`);
785
- trackEvent?.("chrome_bridge_peer_disconnected", null);
786
- if (message.deviceId && message.deviceId === this.selectedDeviceId) {
787
- logger.info(`[${serverName}] Selected extension disconnected, clearing selection`);
788
- this.previousSelectedDeviceId = this.selectedDeviceId;
789
- this.selectedDeviceId = undefined;
790
- this.discoveryComplete = false;
791
- }
792
- break;
793
- case "extensions_list":
794
- if (this.pendingDiscovery) {
795
- clearTimeout(this.pendingDiscovery.timeout);
796
- this.pendingDiscovery.resolve(message.extensions ?? []);
797
- this.pendingDiscovery = null;
798
- }
799
- break;
800
- case "pairing_response": {
801
- const requestId = message.request_id;
802
- const responseDeviceId = message.device_id;
803
- const responseName = message.name;
804
- if (this.pendingPairingRequestId === requestId && responseDeviceId && responseName) {
805
- this.pendingPairingRequestId = undefined;
806
- this.pairingInProgress = false;
807
- this.selectExtension(responseDeviceId);
808
- this.context.onExtensionPaired?.(responseDeviceId, responseName);
809
- logger.info(`[${serverName}] Paired with "${responseName}" (${responseDeviceId.slice(0, 8)})`);
810
- if (this.pendingSwitchResolve) {
811
- this.pendingSwitchResolve({
812
- deviceId: responseDeviceId,
813
- name: responseName
814
- });
815
- this.pendingSwitchResolve = null;
816
- }
817
- }
818
- break;
819
- }
820
- case "ping":
821
- this.ws?.send(JSON.stringify({ type: "pong" }));
822
- break;
823
- case "pong":
824
- break;
825
- case "tool_result":
826
- this.handleToolResult(message);
827
- break;
828
- case "permission_request":
829
- this.handlePermissionRequest(message);
830
- break;
831
- case "notification":
832
- if (this.notificationHandler) {
833
- this.notificationHandler({
834
- method: message.method,
835
- params: message.params
836
- });
837
- }
838
- break;
839
- case "error":
840
- logger.warn(`[${serverName}] Bridge error: ${message.error}`);
841
- if (this.selectedDeviceId) {
842
- this.selectedDeviceId = undefined;
843
- this.discoveryComplete = false;
844
- }
845
- break;
846
- default:
847
- logger.warn(`[${serverName}] Unrecognized bridge message type: ${message.type}`);
848
- }
849
- }
850
- async handlePermissionRequest(message) {
851
- const { logger, serverName } = this.context;
852
- const toolUseId = message.tool_use_id;
853
- const requestId = message.request_id;
854
- if (!toolUseId || !requestId) {
855
- logger.warn(`[${serverName}] permission_request missing tool_use_id or request_id`);
856
- return;
857
- }
858
- const pending = this.pendingCalls.get(toolUseId);
859
- if (!pending?.onPermissionRequest) {
860
- logger.debug(`[${serverName}] Ignoring permission_request for unknown tool_use_id ${toolUseId.slice(0, 8)} (not our call)`);
861
- return;
862
- }
863
- const request = {
864
- toolUseId,
865
- requestId,
866
- toolType: message.tool_type ?? "unknown",
867
- url: message.url ?? "",
868
- actionData: message.action_data
869
- };
870
- try {
871
- const allowed = await pending.onPermissionRequest(request);
872
- this.sendPermissionResponse(requestId, allowed);
873
- } catch (error) {
874
- logger.error(`[${serverName}] Error handling permission request:`, error);
875
- this.sendPermissionResponse(requestId, false);
876
- }
877
- }
878
- sendPermissionResponse(requestId, allowed) {
879
- if (this.ws?.readyState === WS_OPEN) {
880
- const message = {
881
- type: "permission_response",
882
- request_id: requestId,
883
- allowed
884
- };
885
- if (this.selectedDeviceId) {
886
- message.target_device_id = this.selectedDeviceId;
887
- }
888
- this.ws.send(JSON.stringify(message));
889
- }
890
- }
891
- handleToolResult(message) {
892
- const { logger, serverName, trackEvent } = this.context;
893
- const toolUseId = message.tool_use_id;
894
- if (!toolUseId) {
895
- logger.warn(`[${serverName}] Received tool_result without tool_use_id`);
896
- return;
897
- }
898
- const pending = this.pendingCalls.get(toolUseId);
899
- if (!pending) {
900
- logger.debug(`[${serverName}] Received tool_result for unknown call: ${toolUseId.slice(0, 8)}`);
901
- return;
902
- }
903
- const durationMs = Date.now() - pending.startTime;
904
- const normalized = this.normalizeBridgeResponse(message);
905
- const isError = Boolean(message.is_error) || "error" in normalized;
906
- if (pending.isTabsContext && !this.selectedDeviceId) {
907
- pending.results.push(normalized);
908
- } else {
909
- clearTimeout(pending.timer);
910
- this.pendingCalls.delete(toolUseId);
911
- if (isError) {
912
- const errorContent = normalized.error?.content;
913
- let errorMessage = "Unknown error";
914
- if (Array.isArray(errorContent)) {
915
- const textItem = errorContent.find((item) => typeof item === "object" && item !== null && ("text" in item));
916
- if (textItem?.text) {
917
- errorMessage = textItem.text.slice(0, 200);
918
- }
919
- }
920
- logger.warn(`[${serverName}] Tool call error: ${pending.toolName} (${toolUseId.slice(0, 8)}) after ${durationMs}ms`);
921
- trackEvent?.("chrome_bridge_tool_call_error", {
922
- tool_name: pending.toolName,
923
- tool_use_id: toolUseId,
924
- duration_ms: durationMs,
925
- error_message: errorMessage
926
- });
927
- } else {
928
- logger.debug(`[${serverName}] Tool call completed: ${pending.toolName} (${toolUseId.slice(0, 8)}) in ${durationMs}ms`);
929
- trackEvent?.("chrome_bridge_tool_call_completed", {
930
- tool_name: pending.toolName,
931
- tool_use_id: toolUseId,
932
- duration_ms: durationMs
933
- });
934
- }
935
- pending.resolve(normalized);
936
- }
937
- }
938
- normalizeBridgeResponse(message) {
939
- if (message.result || message.error) {
940
- return message;
941
- }
942
- if (message.content) {
943
- if (message.is_error) {
944
- return { error: { content: message.content } };
945
- }
946
- return { result: { content: message.content } };
947
- }
948
- return message;
949
- }
950
- mergeTabsResults(results) {
951
- const mergedTabs = [];
952
- for (const result of results) {
953
- const msg = result;
954
- const resultData = msg.result;
955
- const content = resultData?.content;
956
- if (!content || !Array.isArray(content))
957
- continue;
958
- for (const item of content) {
959
- if (item.type === "text" && item.text) {
960
- try {
961
- const parsed = JSON.parse(item.text);
962
- if (Array.isArray(parsed)) {
963
- mergedTabs.push(...parsed);
964
- } else if (parsed?.availableTabs && Array.isArray(parsed.availableTabs)) {
965
- mergedTabs.push(...parsed.availableTabs);
966
- }
967
- } catch {}
968
- }
969
- }
970
- }
971
- if (mergedTabs.length > 0) {
972
- const tabListText = mergedTabs.map((t) => {
973
- const tab = t;
974
- return ` \u2022 tabId ${tab.tabId}: "${tab.title}" (${tab.url})`;
975
- }).join(`
976
- `);
977
- return {
978
- result: {
979
- content: [
980
- {
981
- type: "text",
982
- text: JSON.stringify({ availableTabs: mergedTabs })
983
- },
984
- {
985
- type: "text",
986
- text: `
987
-
988
- Tab Context:
989
- - Available tabs:
990
- ${tabListText}`
991
- }
992
- ]
993
- }
994
- };
995
- }
996
- return results[0];
997
- }
998
- scheduleReconnect() {
999
- const { logger, serverName, trackEvent } = this.context;
1000
- if (this.reconnectTimer)
1001
- return;
1002
- this.reconnectAttempts++;
1003
- if (this.reconnectAttempts > 100) {
1004
- logger.warn(`[${serverName}] Giving up bridge reconnection after 100 attempts`);
1005
- trackEvent?.("chrome_bridge_reconnect_exhausted", {
1006
- total_attempts: 100
1007
- });
1008
- this.reconnectAttempts = 0;
1009
- return;
1010
- }
1011
- const delay = Math.min(2000 * Math.pow(1.5, this.reconnectAttempts - 1), 30000);
1012
- if (this.reconnectAttempts <= 10 || this.reconnectAttempts % 10 === 0) {
1013
- logger.info(`[${serverName}] Bridge reconnecting in ${Math.round(delay)}ms (attempt ${this.reconnectAttempts})`);
1014
- }
1015
- this.reconnectTimer = setTimeout(() => {
1016
- this.reconnectTimer = null;
1017
- this.connect();
1018
- }, delay);
1019
- }
1020
- closeSocket() {
1021
- if (this.ws) {
1022
- this.ws.removeAllListeners();
1023
- this.ws.close();
1024
- this.ws = null;
1025
- }
1026
- this.connected = false;
1027
- this.authenticated = false;
1028
- this.selectedDeviceId = undefined;
1029
- this.discoveryComplete = false;
1030
- this.pendingPairingRequestId = undefined;
1031
- this.pairingInProgress = false;
1032
- if (this.pendingSwitchResolve) {
1033
- this.pendingSwitchResolve(null);
1034
- this.pendingSwitchResolve = null;
1035
- }
1036
- if (this.pendingDiscovery) {
1037
- clearTimeout(this.pendingDiscovery.timeout);
1038
- this.pendingDiscovery.resolve([]);
1039
- this.pendingDiscovery = null;
1040
- }
1041
- if (this.peerConnectedWaiters.length > 0) {
1042
- const waiters = this.peerConnectedWaiters;
1043
- this.peerConnectedWaiters = [];
1044
- for (const waiter of waiters) {
1045
- waiter(false);
1046
- }
1047
- }
1048
- }
1049
- cleanup() {
1050
- if (this.reconnectTimer) {
1051
- clearTimeout(this.reconnectTimer);
1052
- this.reconnectTimer = null;
1053
- }
1054
- for (const [id, pending] of this.pendingCalls) {
1055
- clearTimeout(pending.timer);
1056
- pending.reject(new SocketConnectionError("Bridge client disconnected"));
1057
- this.pendingCalls.delete(id);
1058
- }
1059
- this.closeSocket();
1060
- this.reconnectAttempts = 0;
1061
- }
1062
- }
1063
- function createBridgeClient(context) {
1064
- return new BridgeClient(context);
1065
- }
1066
- var WS_OPEN = 1, DISCOVERY_TIMEOUT_MS = 5000, PEER_WAIT_TIMEOUT_MS = 1e4;
1067
- var init_bridgeClient = __esm(() => {
1068
- init_mcpSocketClient();
1069
- init_types2();
1070
- });
1071
-
1072
- // packages/@ant/claude-for-chrome-mcp/src/browserTools.ts
1073
- var BROWSER_TOOLS;
1074
- var init_browserTools = __esm(() => {
1075
- BROWSER_TOOLS = [
1076
- {
1077
- name: "javascript_tool",
1078
- description: "Execute JavaScript code in the context of the current page. The code runs in the page's context and can interact with the DOM, window object, and page variables. Returns the result of the last expression or any thrown errors. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
1079
- inputSchema: {
1080
- type: "object",
1081
- properties: {
1082
- action: {
1083
- type: "string",
1084
- description: "Must be set to 'javascript_exec'"
1085
- },
1086
- text: {
1087
- type: "string",
1088
- description: "The JavaScript code to execute. The code will be evaluated in the page context. The result of the last expression will be returned automatically. Do NOT use 'return' statements - just write the expression you want to evaluate (e.g., 'window.myData.value' not 'return window.myData.value'). You can access and modify the DOM, call page functions, and interact with page variables."
1089
- },
1090
- tabId: {
1091
- type: "number",
1092
- description: "Tab ID to execute the code in. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1093
- }
1094
- },
1095
- required: ["action", "text", "tabId"]
1096
- }
1097
- },
1098
- {
1099
- name: "read_page",
1100
- description: "Get an accessibility tree representation of elements on the page. By default returns all elements including non-visible ones. Output is limited to 50000 characters by default. If the output exceeds this limit, you will receive an error asking you to specify a smaller depth or focus on a specific element using ref_id. Optionally filter for only interactive elements. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
1101
- inputSchema: {
1102
- type: "object",
1103
- properties: {
1104
- filter: {
1105
- type: "string",
1106
- enum: ["interactive", "all"],
1107
- description: 'Filter elements: "interactive" for buttons/links/inputs only, "all" for all elements including non-visible ones (default: all elements)'
1108
- },
1109
- tabId: {
1110
- type: "number",
1111
- description: "Tab ID to read from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1112
- },
1113
- depth: {
1114
- type: "number",
1115
- description: "Maximum depth of the tree to traverse (default: 15). Use a smaller depth if output is too large."
1116
- },
1117
- ref_id: {
1118
- type: "string",
1119
- description: "Reference ID of a parent element to read. Will return the specified element and all its children. Use this to focus on a specific part of the page when output is too large."
1120
- },
1121
- max_chars: {
1122
- type: "number",
1123
- description: "Maximum characters for output (default: 50000). Set to a higher value if your client can handle large outputs."
1124
- }
1125
- },
1126
- required: ["tabId"]
1127
- }
1128
- },
1129
- {
1130
- name: "find",
1131
- description: `Find elements on the page using natural language. Can search for elements by their purpose (e.g., "search bar", "login button") or by text content (e.g., "organic mango product"). Returns up to 20 matching elements with references that can be used with other tools. If more than 20 matches exist, you'll be notified to use a more specific query. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.`,
1132
- inputSchema: {
1133
- type: "object",
1134
- properties: {
1135
- query: {
1136
- type: "string",
1137
- description: 'Natural language description of what to find (e.g., "search bar", "add to cart button", "product title containing organic")'
1138
- },
1139
- tabId: {
1140
- type: "number",
1141
- description: "Tab ID to search in. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1142
- }
1143
- },
1144
- required: ["query", "tabId"]
1145
- }
1146
- },
1147
- {
1148
- name: "form_input",
1149
- description: "Set values in form elements using element reference ID from the read_page tool. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
1150
- inputSchema: {
1151
- type: "object",
1152
- properties: {
1153
- ref: {
1154
- type: "string",
1155
- description: 'Element reference ID from the read_page tool (e.g., "ref_1", "ref_2")'
1156
- },
1157
- value: {
1158
- type: ["string", "boolean", "number"],
1159
- description: "The value to set. For checkboxes use boolean, for selects use option value or text, for other inputs use appropriate string/number"
1160
- },
1161
- tabId: {
1162
- type: "number",
1163
- description: "Tab ID to set form value in. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1164
- }
1165
- },
1166
- required: ["ref", "value", "tabId"]
1167
- }
1168
- },
1169
- {
1170
- name: "computer",
1171
- description: `Use a mouse and keyboard to interact with a web browser, and take screenshots. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.
1172
- * Whenever you intend to click on an element like an icon, you should consult a screenshot to determine the coordinates of the element before moving the cursor.
1173
- * If you tried clicking on a program or link but it failed to load, even after waiting, try adjusting your click location so that the tip of the cursor visually falls on the element that you want to click.
1174
- * Make sure to click any buttons, links, icons, etc with the cursor tip in the center of the element. Don't click boxes on their edges unless asked.`,
1175
- inputSchema: {
1176
- type: "object",
1177
- properties: {
1178
- action: {
1179
- type: "string",
1180
- enum: [
1181
- "left_click",
1182
- "right_click",
1183
- "type",
1184
- "screenshot",
1185
- "wait",
1186
- "scroll",
1187
- "key",
1188
- "left_click_drag",
1189
- "double_click",
1190
- "triple_click",
1191
- "zoom",
1192
- "scroll_to",
1193
- "hover"
1194
- ],
1195
- description: "The action to perform:\n* `left_click`: Click the left mouse button at the specified coordinates.\n* `right_click`: Click the right mouse button at the specified coordinates to open context menus.\n* `double_click`: Double-click the left mouse button at the specified coordinates.\n* `triple_click`: Triple-click the left mouse button at the specified coordinates.\n* `type`: Type a string of text.\n* `screenshot`: Take a screenshot of the screen.\n* `wait`: Wait for a specified number of seconds.\n* `scroll`: Scroll up, down, left, or right at the specified coordinates.\n* `key`: Press a specific keyboard key.\n* `left_click_drag`: Drag from start_coordinate to coordinate.\n* `zoom`: Take a screenshot of a specific region for closer inspection.\n* `scroll_to`: Scroll an element into view using its element reference ID from read_page or find tools.\n* `hover`: Move the mouse cursor to the specified coordinates or element without clicking. Useful for revealing tooltips, dropdown menus, or triggering hover states."
1196
- },
1197
- coordinate: {
1198
- type: "array",
1199
- items: { type: "number" },
1200
- minItems: 2,
1201
- maxItems: 2,
1202
- description: "(x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates. Required for `left_click`, `right_click`, `double_click`, `triple_click`, and `scroll`. For `left_click_drag`, this is the end position."
1203
- },
1204
- text: {
1205
- type: "string",
1206
- description: 'The text to type (for `type` action) or the key(s) to press (for `key` action). For `key` action: Provide space-separated keys (e.g., "Backspace Backspace Delete"). Supports keyboard shortcuts using the platform\'s modifier key (use "cmd" on Mac, "ctrl" on Windows/Linux, e.g., "cmd+a" or "ctrl+a" for select all).'
1207
- },
1208
- duration: {
1209
- type: "number",
1210
- minimum: 0,
1211
- maximum: 30,
1212
- description: "The number of seconds to wait. Required for `wait`. Maximum 30 seconds."
1213
- },
1214
- scroll_direction: {
1215
- type: "string",
1216
- enum: ["up", "down", "left", "right"],
1217
- description: "The direction to scroll. Required for `scroll`."
1218
- },
1219
- scroll_amount: {
1220
- type: "number",
1221
- minimum: 1,
1222
- maximum: 10,
1223
- description: "The number of scroll wheel ticks. Optional for `scroll`, defaults to 3."
1224
- },
1225
- start_coordinate: {
1226
- type: "array",
1227
- items: { type: "number" },
1228
- minItems: 2,
1229
- maxItems: 2,
1230
- description: "(x, y): The starting coordinates for `left_click_drag`."
1231
- },
1232
- region: {
1233
- type: "array",
1234
- items: { type: "number" },
1235
- minItems: 4,
1236
- maxItems: 4,
1237
- description: "(x0, y0, x1, y1): The rectangular region to capture for `zoom`. Coordinates define a rectangle from top-left (x0, y0) to bottom-right (x1, y1) in pixels from the viewport origin. Required for `zoom` action. Useful for inspecting small UI elements like icons, buttons, or text."
1238
- },
1239
- repeat: {
1240
- type: "number",
1241
- minimum: 1,
1242
- maximum: 100,
1243
- description: "Number of times to repeat the key sequence. Only applicable for `key` action. Must be a positive integer between 1 and 100. Default is 1. Useful for navigation tasks like pressing arrow keys multiple times."
1244
- },
1245
- ref: {
1246
- type: "string",
1247
- description: 'Element reference ID from read_page or find tools (e.g., "ref_1", "ref_2"). Required for `scroll_to` action. Can be used as alternative to `coordinate` for click actions.'
1248
- },
1249
- modifiers: {
1250
- type: "string",
1251
- description: 'Modifier keys for click actions. Supports: "ctrl", "shift", "alt", "cmd" (or "meta"), "win" (or "windows"). Can be combined with "+" (e.g., "ctrl+shift", "cmd+alt"). Optional.'
1252
- },
1253
- tabId: {
1254
- type: "number",
1255
- description: "Tab ID to execute the action on. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1256
- }
1257
- },
1258
- required: ["action", "tabId"]
1259
- }
1260
- },
1261
- {
1262
- name: "navigate",
1263
- description: "Navigate to a URL, or go forward/back in browser history. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
1264
- inputSchema: {
1265
- type: "object",
1266
- properties: {
1267
- url: {
1268
- type: "string",
1269
- description: 'The URL to navigate to. Can be provided with or without protocol (defaults to https://). Use "forward" to go forward in history or "back" to go back in history.'
1270
- },
1271
- tabId: {
1272
- type: "number",
1273
- description: "Tab ID to navigate. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1274
- }
1275
- },
1276
- required: ["url", "tabId"]
1277
- }
1278
- },
1279
- {
1280
- name: "resize_window",
1281
- description: "Resize the current browser window to specified dimensions. Useful for testing responsive designs or setting up specific screen sizes. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
1282
- inputSchema: {
1283
- type: "object",
1284
- properties: {
1285
- width: {
1286
- type: "number",
1287
- description: "Target window width in pixels"
1288
- },
1289
- height: {
1290
- type: "number",
1291
- description: "Target window height in pixels"
1292
- },
1293
- tabId: {
1294
- type: "number",
1295
- description: "Tab ID to get the window for. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1296
- }
1297
- },
1298
- required: ["width", "height", "tabId"]
1299
- }
1300
- },
1301
- {
1302
- name: "gif_creator",
1303
- description: "Manage GIF recording and export for browser automation sessions. Control when to start/stop recording browser actions (clicks, scrolls, navigation), then export as an animated GIF with visual overlays (click indicators, action labels, progress bar, watermark). All operations are scoped to the tab's group. When starting recording, take a screenshot immediately after to capture the initial state as the first frame. When stopping recording, take a screenshot immediately before to capture the final state as the last frame. For export, either provide 'coordinate' to drag/drop upload to a page element, or set 'download: true' to download the GIF.",
1304
- inputSchema: {
1305
- type: "object",
1306
- properties: {
1307
- action: {
1308
- type: "string",
1309
- enum: ["start_recording", "stop_recording", "export", "clear"],
1310
- description: "Action to perform: 'start_recording' (begin capturing), 'stop_recording' (stop capturing but keep frames), 'export' (generate and export GIF), 'clear' (discard frames)"
1311
- },
1312
- tabId: {
1313
- type: "number",
1314
- description: "Tab ID to identify which tab group this operation applies to"
1315
- },
1316
- download: {
1317
- type: "boolean",
1318
- description: "Always set this to true for the 'export' action only. This causes the gif to be downloaded in the browser."
1319
- },
1320
- filename: {
1321
- type: "string",
1322
- description: "Optional filename for exported GIF (default: 'recording-[timestamp].gif'). For 'export' action only."
1323
- },
1324
- options: {
1325
- type: "object",
1326
- description: "Optional GIF enhancement options for 'export' action. Properties: showClickIndicators (bool), showDragPaths (bool), showActionLabels (bool), showProgressBar (bool), showWatermark (bool), quality (number 1-30). All default to true except quality (default: 10).",
1327
- properties: {
1328
- showClickIndicators: {
1329
- type: "boolean",
1330
- description: "Show orange circles at click locations (default: true)"
1331
- },
1332
- showDragPaths: {
1333
- type: "boolean",
1334
- description: "Show red arrows for drag actions (default: true)"
1335
- },
1336
- showActionLabels: {
1337
- type: "boolean",
1338
- description: "Show black labels describing actions (default: true)"
1339
- },
1340
- showProgressBar: {
1341
- type: "boolean",
1342
- description: "Show orange progress bar at bottom (default: true)"
1343
- },
1344
- showWatermark: {
1345
- type: "boolean",
1346
- description: "Show Claude logo watermark (default: true)"
1347
- },
1348
- quality: {
1349
- type: "number",
1350
- description: "GIF compression quality, 1-30 (lower = better quality, slower encoding). Default: 10"
1351
- }
1352
- }
1353
- }
1354
- },
1355
- required: ["action", "tabId"]
1356
- }
1357
- },
1358
- {
1359
- name: "upload_image",
1360
- description: "Upload a previously captured screenshot or user-uploaded image to a file input or drag & drop target. Supports two approaches: (1) ref - for targeting specific elements, especially hidden file inputs, (2) coordinate - for drag & drop to visible locations like Google Docs. Provide either ref or coordinate, not both.",
1361
- inputSchema: {
1362
- type: "object",
1363
- properties: {
1364
- imageId: {
1365
- type: "string",
1366
- description: "ID of a previously captured screenshot (from the computer tool's screenshot action) or a user-uploaded image"
1367
- },
1368
- ref: {
1369
- type: "string",
1370
- description: 'Element reference ID from read_page or find tools (e.g., "ref_1", "ref_2"). Use this for file inputs (especially hidden ones) or specific elements. Provide either ref or coordinate, not both.'
1371
- },
1372
- coordinate: {
1373
- type: "array",
1374
- items: {
1375
- type: "number"
1376
- },
1377
- description: "Viewport coordinates [x, y] for drag & drop to a visible location. Use this for drag & drop targets like Google Docs. Provide either ref or coordinate, not both."
1378
- },
1379
- tabId: {
1380
- type: "number",
1381
- description: "Tab ID where the target element is located. This is where the image will be uploaded to."
1382
- },
1383
- filename: {
1384
- type: "string",
1385
- description: 'Optional filename for the uploaded file (default: "image.png")'
1386
- }
1387
- },
1388
- required: ["imageId", "tabId"]
1389
- }
1390
- },
1391
- {
1392
- name: "get_page_text",
1393
- description: "Extract raw text content from the page, prioritizing article content. Ideal for reading articles, blog posts, or other text-heavy pages. Returns plain text without HTML formatting. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
1394
- inputSchema: {
1395
- type: "object",
1396
- properties: {
1397
- tabId: {
1398
- type: "number",
1399
- description: "Tab ID to extract text from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1400
- }
1401
- },
1402
- required: ["tabId"]
1403
- }
1404
- },
1405
- {
1406
- name: "tabs_context_mcp",
1407
- title: "Tabs Context",
1408
- description: "Get context information about the current MCP tab group. Returns all tab IDs inside the group if it exists. CRITICAL: You must get the context at least once before using other browser automation tools so you know what tabs exist. Each new conversation should create its own new tab (using tabs_create_mcp) rather than reusing existing tabs, unless the user explicitly asks to use an existing tab.",
1409
- inputSchema: {
1410
- type: "object",
1411
- properties: {
1412
- createIfEmpty: {
1413
- type: "boolean",
1414
- description: "Creates a new MCP tab group if none exists, creates a new Window with a new tab group containing an empty tab (which can be used for this conversation). If a MCP tab group already exists, this parameter has no effect."
1415
- }
1416
- },
1417
- required: []
1418
- }
1419
- },
1420
- {
1421
- name: "tabs_create_mcp",
1422
- title: "Tabs Create",
1423
- description: "Creates a new empty tab in the MCP tab group. CRITICAL: You must get the context using tabs_context_mcp at least once before using other browser automation tools so you know what tabs exist.",
1424
- inputSchema: {
1425
- type: "object",
1426
- properties: {},
1427
- required: []
1428
- }
1429
- },
1430
- {
1431
- name: "update_plan",
1432
- description: "Present a plan to the user for approval before taking actions. The user will see the domains you intend to visit and your approach. Once approved, you can proceed with actions on the approved domains without additional permission prompts.",
1433
- inputSchema: {
1434
- type: "object",
1435
- properties: {
1436
- domains: {
1437
- type: "array",
1438
- items: { type: "string" },
1439
- description: "List of domains you will visit (e.g., ['github.com', 'stackoverflow.com']). These domains will be approved for the session when the user accepts the plan."
1440
- },
1441
- approach: {
1442
- type: "array",
1443
- items: { type: "string" },
1444
- description: "High-level description of what you will do. Focus on outcomes and key actions, not implementation details. Be concise - aim for 3-7 items."
1445
- }
1446
- },
1447
- required: ["domains", "approach"]
1448
- }
1449
- },
1450
- {
1451
- name: "read_console_messages",
1452
- description: "Read browser console messages (console.log, console.error, console.warn, etc.) from a specific tab. Useful for debugging JavaScript errors, viewing application logs, or understanding what's happening in the browser console. Returns console messages from the current domain only. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs. IMPORTANT: Always provide a pattern to filter messages - without a pattern, you may get too many irrelevant messages.",
1453
- inputSchema: {
1454
- type: "object",
1455
- properties: {
1456
- tabId: {
1457
- type: "number",
1458
- description: "Tab ID to read console messages from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1459
- },
1460
- onlyErrors: {
1461
- type: "boolean",
1462
- description: "If true, only return error and exception messages. Default is false (return all message types)."
1463
- },
1464
- clear: {
1465
- type: "boolean",
1466
- description: "If true, clear the console messages after reading to avoid duplicates on subsequent calls. Default is false."
1467
- },
1468
- pattern: {
1469
- type: "string",
1470
- description: "Regex pattern to filter console messages. Only messages matching this pattern will be returned (e.g., 'error|warning' to find errors and warnings, 'MyApp' to filter app-specific logs). You should always provide a pattern to avoid getting too many irrelevant messages."
1471
- },
1472
- limit: {
1473
- type: "number",
1474
- description: "Maximum number of messages to return. Defaults to 100. Increase only if you need more results."
1475
- }
1476
- },
1477
- required: ["tabId"]
1478
- }
1479
- },
1480
- {
1481
- name: "read_network_requests",
1482
- description: "Read HTTP network requests (XHR, Fetch, documents, images, etc.) from a specific tab. Useful for debugging API calls, monitoring network activity, or understanding what requests a page is making. Returns all network requests made by the current page, including cross-origin requests. Requests are automatically cleared when the page navigates to a different domain. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
1483
- inputSchema: {
1484
- type: "object",
1485
- properties: {
1486
- tabId: {
1487
- type: "number",
1488
- description: "Tab ID to read network requests from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1489
- },
1490
- urlPattern: {
1491
- type: "string",
1492
- description: "Optional URL pattern to filter requests. Only requests whose URL contains this string will be returned (e.g., '/api/' to filter API calls, 'example.com' to filter by domain)."
1493
- },
1494
- clear: {
1495
- type: "boolean",
1496
- description: "If true, clear the network requests after reading to avoid duplicates on subsequent calls. Default is false."
1497
- },
1498
- limit: {
1499
- type: "number",
1500
- description: "Maximum number of requests to return. Defaults to 100. Increase only if you need more results."
1501
- }
1502
- },
1503
- required: ["tabId"]
1504
- }
1505
- },
1506
- {
1507
- name: "shortcuts_list",
1508
- description: "List all available shortcuts and workflows (shortcuts and workflows are interchangeable). Returns shortcuts with their commands, descriptions, and whether they are workflows. Use shortcuts_execute to run a shortcut or workflow.",
1509
- inputSchema: {
1510
- type: "object",
1511
- properties: {
1512
- tabId: {
1513
- type: "number",
1514
- description: "Tab ID to list shortcuts from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1515
- }
1516
- },
1517
- required: ["tabId"]
1518
- }
1519
- },
1520
- {
1521
- name: "shortcuts_execute",
1522
- description: "Execute a shortcut or workflow by running it in a new sidepanel window using the current tab (shortcuts and workflows are interchangeable). Use shortcuts_list first to see available shortcuts. This starts the execution and returns immediately - it does not wait for completion.",
1523
- inputSchema: {
1524
- type: "object",
1525
- properties: {
1526
- tabId: {
1527
- type: "number",
1528
- description: "Tab ID to execute the shortcut on. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID."
1529
- },
1530
- shortcutId: {
1531
- type: "string",
1532
- description: "The ID of the shortcut to execute"
1533
- },
1534
- command: {
1535
- type: "string",
1536
- description: "The command name of the shortcut to execute (e.g., 'debug', 'summarize'). Do not include the leading slash."
1537
- }
1538
- },
1539
- required: ["tabId"]
1540
- }
1541
- },
1542
- {
1543
- name: "switch_browser",
1544
- description: "Switch which Chrome browser is used for browser automation. Call this when the user wants to connect to a different Chrome browser. Broadcasts a connection request to all Chrome browsers with the extension installed \u2014 the user clicks 'Connect' in the desired browser.",
1545
- inputSchema: {
1546
- type: "object",
1547
- properties: {},
1548
- required: []
1549
- }
1550
- }
1551
- ];
1552
- });
1553
-
1554
- // packages/@ant/claude-for-chrome-mcp/src/mcpSocketPool.ts
1555
- class McpSocketPool {
1556
- clients = new Map;
1557
- tabRoutes = new Map;
1558
- context;
1559
- notificationHandler = null;
1560
- constructor(context) {
1561
- this.context = context;
1562
- }
1563
- setNotificationHandler(handler) {
1564
- this.notificationHandler = handler;
1565
- for (const client of this.clients.values()) {
1566
- client.setNotificationHandler(handler);
1567
- }
1568
- }
1569
- async ensureConnected() {
1570
- const { logger, serverName } = this.context;
1571
- this.refreshClients();
1572
- const connectPromises = [];
1573
- for (const client of this.clients.values()) {
1574
- if (!client.isConnected()) {
1575
- connectPromises.push(client.ensureConnected().catch(() => false));
1576
- }
1577
- }
1578
- if (connectPromises.length > 0) {
1579
- await Promise.all(connectPromises);
1580
- }
1581
- const connectedCount = this.getConnectedClients().length;
1582
- if (connectedCount === 0) {
1583
- logger.info(`[${serverName}] No connected sockets in pool`);
1584
- return false;
1585
- }
1586
- logger.info(`[${serverName}] Socket pool: ${connectedCount} connected`);
1587
- return true;
1588
- }
1589
- async callTool(name, args, _permissionOverrides) {
1590
- if (name === "tabs_context_mcp") {
1591
- return this.callTabsContext(args);
1592
- }
1593
- const tabId = args.tabId;
1594
- if (tabId !== undefined) {
1595
- const socketPath = this.tabRoutes.get(tabId);
1596
- if (socketPath) {
1597
- const client = this.clients.get(socketPath);
1598
- if (client?.isConnected()) {
1599
- return client.callTool(name, args);
1600
- }
1601
- }
1602
- }
1603
- const connected = this.getConnectedClients();
1604
- if (connected.length === 0) {
1605
- throw new SocketConnectionError(`[${this.context.serverName}] No connected sockets available`);
1606
- }
1607
- return connected[0].callTool(name, args);
1608
- }
1609
- async setPermissionMode(mode, allowedDomains) {
1610
- const connected = this.getConnectedClients();
1611
- await Promise.all(connected.map((client) => client.setPermissionMode(mode, allowedDomains)));
1612
- }
1613
- isConnected() {
1614
- return this.getConnectedClients().length > 0;
1615
- }
1616
- disconnect() {
1617
- for (const client of this.clients.values()) {
1618
- client.disconnect();
1619
- }
1620
- this.clients.clear();
1621
- this.tabRoutes.clear();
1622
- }
1623
- getConnectedClients() {
1624
- return [...this.clients.values()].filter((c) => c.isConnected());
1625
- }
1626
- async callTabsContext(args) {
1627
- const { logger, serverName } = this.context;
1628
- const connected = this.getConnectedClients();
1629
- if (connected.length === 0) {
1630
- throw new SocketConnectionError(`[${serverName}] No connected sockets available`);
1631
- }
1632
- if (connected.length === 1) {
1633
- const result = await connected[0].callTool("tabs_context_mcp", args);
1634
- this.updateTabRoutes(result, this.getSocketPathForClient(connected[0]));
1635
- return result;
1636
- }
1637
- const results = await Promise.allSettled(connected.map(async (client) => {
1638
- const result = await client.callTool("tabs_context_mcp", args);
1639
- const socketPath = this.getSocketPathForClient(client);
1640
- return { result, socketPath };
1641
- }));
1642
- const mergedTabs = [];
1643
- this.tabRoutes.clear();
1644
- for (const settledResult of results) {
1645
- if (settledResult.status !== "fulfilled") {
1646
- logger.info(`[${serverName}] tabs_context_mcp failed on one socket: ${settledResult.reason}`);
1647
- continue;
1648
- }
1649
- const { result, socketPath } = settledResult.value;
1650
- this.updateTabRoutes(result, socketPath);
1651
- const tabs = this.extractTabs(result);
1652
- if (tabs) {
1653
- mergedTabs.push(...tabs);
1654
- }
1655
- }
1656
- if (mergedTabs.length > 0) {
1657
- const tabListText = mergedTabs.map((t) => {
1658
- const tab = t;
1659
- return ` \u2022 tabId ${tab.tabId}: "${tab.title}" (${tab.url})`;
1660
- }).join(`
1661
- `);
1662
- return {
1663
- result: {
1664
- content: [
1665
- {
1666
- type: "text",
1667
- text: JSON.stringify({ availableTabs: mergedTabs })
1668
- },
1669
- {
1670
- type: "text",
1671
- text: `
1672
-
1673
- Tab Context:
1674
- - Available tabs:
1675
- ${tabListText}`
1676
- }
1677
- ]
1678
- }
1679
- };
1680
- }
1681
- for (const settledResult of results) {
1682
- if (settledResult.status === "fulfilled") {
1683
- return settledResult.value.result;
1684
- }
1685
- }
1686
- throw new SocketConnectionError(`[${serverName}] All sockets failed for tabs_context_mcp`);
1687
- }
1688
- updateTabRoutes(result, socketPath) {
1689
- const tabs = this.extractTabs(result);
1690
- if (!tabs)
1691
- return;
1692
- for (const tab of tabs) {
1693
- if (typeof tab === "object" && tab !== null && "tabId" in tab) {
1694
- const tabId = tab.tabId;
1695
- this.tabRoutes.set(tabId, socketPath);
1696
- }
1697
- }
1698
- }
1699
- extractTabs(result) {
1700
- if (!result || typeof result !== "object")
1701
- return null;
1702
- const asResponse = result;
1703
- const content = asResponse.result?.content;
1704
- if (!content || !Array.isArray(content))
1705
- return null;
1706
- for (const item of content) {
1707
- if (item.type === "text" && item.text) {
1708
- try {
1709
- const parsed = JSON.parse(item.text);
1710
- if (Array.isArray(parsed))
1711
- return parsed;
1712
- if (parsed && Array.isArray(parsed.availableTabs)) {
1713
- return parsed.availableTabs;
1714
- }
1715
- } catch {}
1716
- }
1717
- }
1718
- return null;
1719
- }
1720
- getSocketPathForClient(client) {
1721
- for (const [path, c] of this.clients.entries()) {
1722
- if (c === client)
1723
- return path;
1724
- }
1725
- return "";
1726
- }
1727
- refreshClients() {
1728
- const socketPaths = this.getAvailableSocketPaths();
1729
- const { logger, serverName } = this.context;
1730
- for (const path of socketPaths) {
1731
- if (!this.clients.has(path)) {
1732
- logger.info(`[${serverName}] Adding socket to pool: ${path}`);
1733
- const clientContext = {
1734
- ...this.context,
1735
- socketPath: path,
1736
- getSocketPath: undefined,
1737
- getSocketPaths: undefined
1738
- };
1739
- const client = createMcpSocketClient(clientContext);
1740
- client.disableAutoReconnect = true;
1741
- if (this.notificationHandler) {
1742
- client.setNotificationHandler(this.notificationHandler);
1743
- }
1744
- this.clients.set(path, client);
1745
- }
1746
- }
1747
- for (const [path, client] of this.clients.entries()) {
1748
- if (!socketPaths.includes(path)) {
1749
- logger.info(`[${serverName}] Removing stale socket from pool: ${path}`);
1750
- client.disconnect();
1751
- this.clients.delete(path);
1752
- for (const [tabId, socketPath] of this.tabRoutes.entries()) {
1753
- if (socketPath === path) {
1754
- this.tabRoutes.delete(tabId);
1755
- }
1756
- }
1757
- }
1758
- }
1759
- }
1760
- getAvailableSocketPaths() {
1761
- return this.context.getSocketPaths?.() ?? [];
1762
- }
1763
- }
1764
- function createMcpSocketPool(context) {
1765
- return new McpSocketPool(context);
1766
- }
1767
- var init_mcpSocketPool = __esm(() => {
1768
- init_mcpSocketClient();
1769
- });
1770
-
1771
- // packages/@ant/claude-for-chrome-mcp/src/toolCalls.ts
1772
- async function handleToolCallConnected(context, socketClient, name, args, permissionOverrides) {
1773
- const response = await socketClient.callTool(name, args, permissionOverrides);
1774
- context.logger.silly(`[${context.serverName}] Received result from socket bridge: ${JSON.stringify(response)}`);
1775
- if (response === null || response === undefined) {
1776
- return {
1777
- content: [{ type: "text", text: "Tool execution completed" }]
1778
- };
1779
- }
1780
- const { result, error } = response;
1781
- const contentData = error || result;
1782
- const isError = !!error;
1783
- if (!contentData) {
1784
- return {
1785
- content: [{ type: "text", text: "Tool execution completed" }]
1786
- };
1787
- }
1788
- if (isError && isAuthenticationError(contentData.content)) {
1789
- context.onAuthenticationError();
1790
- }
1791
- const { content } = contentData;
1792
- if (content && Array.isArray(content)) {
1793
- if (isError) {
1794
- return {
1795
- content: content.map((item) => {
1796
- if (typeof item === "object" && item !== null && "type" in item) {
1797
- return item;
1798
- }
1799
- return { type: "text", text: String(item) };
1800
- }),
1801
- isError: true
1802
- };
1803
- }
1804
- const convertedContent = content.map((item) => {
1805
- if (typeof item === "object" && item !== null && "type" in item && "source" in item) {
1806
- const typedItem = item;
1807
- if (typedItem.type === "image" && typeof typedItem.source === "object" && typedItem.source !== null && "data" in typedItem.source) {
1808
- return {
1809
- type: "image",
1810
- data: typedItem.source.data,
1811
- mimeType: "media_type" in typedItem.source ? typedItem.source.media_type || "image/png" : "image/png"
1812
- };
1813
- }
1814
- }
1815
- if (typeof item === "object" && item !== null && "type" in item) {
1816
- return item;
1817
- }
1818
- return { type: "text", text: String(item) };
1819
- });
1820
- return {
1821
- content: convertedContent,
1822
- isError
1823
- };
1824
- }
1825
- if (typeof content === "string") {
1826
- return {
1827
- content: [{ type: "text", text: content }],
1828
- isError
1829
- };
1830
- }
1831
- context.logger.warn(`[${context.serverName}] Unexpected result format from socket bridge`, response);
1832
- return {
1833
- content: [{ type: "text", text: JSON.stringify(response) }],
1834
- isError
1835
- };
1836
- }
1837
- function handleToolCallDisconnected(context) {
1838
- const text = context.onToolCallDisconnected();
1839
- return {
1840
- content: [{ type: "text", text }]
1841
- };
1842
- }
1843
- async function handleSetPermissionMode(socketClient, args) {
1844
- const validModes = [
1845
- "ask",
1846
- "skip_all_permission_checks",
1847
- "follow_a_plan"
1848
- ];
1849
- const mode = args.mode;
1850
- const permissionMode = mode && validModes.includes(mode) ? mode : "ask";
1851
- if (socketClient.setPermissionMode) {
1852
- await socketClient.setPermissionMode(permissionMode, args.allowed_domains);
1853
- }
1854
- return {
1855
- content: [
1856
- { type: "text", text: `Permission mode set to: ${permissionMode}` }
1857
- ]
1858
- };
1859
- }
1860
- async function handleSwitchBrowser(context, socketClient) {
1861
- if (!context.bridgeConfig) {
1862
- return {
1863
- content: [
1864
- {
1865
- type: "text",
1866
- text: "Browser switching is only available with bridge connections."
1867
- }
1868
- ],
1869
- isError: true
1870
- };
1871
- }
1872
- const isConnected = await socketClient.ensureConnected();
1873
- if (!isConnected) {
1874
- return handleToolCallDisconnected(context);
1875
- }
1876
- const result = await socketClient.switchBrowser?.() ?? null;
1877
- if (result === "no_other_browsers") {
1878
- return {
1879
- content: [
1880
- {
1881
- type: "text",
1882
- text: "No other browsers available to switch to. Open Chrome with the Claude extension in another browser to switch."
1883
- }
1884
- ],
1885
- isError: true
1886
- };
1887
- }
1888
- if (result) {
1889
- return {
1890
- content: [
1891
- { type: "text", text: `Connected to browser "${result.name}".` }
1892
- ]
1893
- };
1894
- }
1895
- return {
1896
- content: [
1897
- {
1898
- type: "text",
1899
- text: "No browser responded within the timeout. Make sure Chrome is open with the Claude extension installed, then try again."
1900
- }
1901
- ],
1902
- isError: true
1903
- };
1904
- }
1905
- function isAuthenticationError(content) {
1906
- const errorText = Array.isArray(content) ? content.map((item) => {
1907
- if (typeof item === "string")
1908
- return item;
1909
- if (typeof item === "object" && item !== null && "text" in item && typeof item.text === "string") {
1910
- return item.text;
1911
- }
1912
- return "";
1913
- }).join(" ") : String(content);
1914
- return errorText.toLowerCase().includes("re-authenticated");
1915
- }
1916
- var handleToolCall = async (context, socketClient, name, args, permissionOverrides) => {
1917
- if (name === "set_permission_mode") {
1918
- return handleSetPermissionMode(socketClient, args);
1919
- }
1920
- if (name === "switch_browser") {
1921
- return handleSwitchBrowser(context, socketClient);
1922
- }
1923
- try {
1924
- const isConnected = await socketClient.ensureConnected();
1925
- context.logger.silly(`[${context.serverName}] Server is connected: ${isConnected}. Received tool call: ${name} with args: ${JSON.stringify(args)}.`);
1926
- if (isConnected) {
1927
- return await handleToolCallConnected(context, socketClient, name, args, permissionOverrides);
1928
- }
1929
- return handleToolCallDisconnected(context);
1930
- } catch (error) {
1931
- context.logger.info(`[${context.serverName}] Error calling tool:`, error);
1932
- if (error instanceof SocketConnectionError) {
1933
- return handleToolCallDisconnected(context);
1934
- }
1935
- return {
1936
- content: [
1937
- {
1938
- type: "text",
1939
- text: `Error calling tool, please try again. : ${error instanceof Error ? error.message : String(error)}`
1940
- }
1941
- ],
1942
- isError: true
1943
- };
1944
- }
1945
- };
1946
- var init_toolCalls = __esm(() => {
1947
- init_mcpSocketClient();
1948
- });
1949
-
1950
- // packages/@ant/claude-for-chrome-mcp/src/mcpServer.ts
1951
- function createChromeSocketClient(context) {
1952
- return context.bridgeConfig ? createBridgeClient(context) : context.getSocketPaths ? createMcpSocketPool(context) : createMcpSocketClient(context);
1953
- }
1954
- function createClaudeForChromeMcpServer(context, existingSocketClient) {
1955
- const { serverName, logger } = context;
1956
- const socketClient = existingSocketClient ?? createChromeSocketClient(context);
1957
- const server = new Server({
1958
- name: serverName,
1959
- version: "1.0.0"
1960
- }, {
1961
- capabilities: {
1962
- tools: {},
1963
- logging: {}
1964
- }
1965
- });
1966
- server.setRequestHandler(ListToolsRequestSchema, async () => {
1967
- if (context.isDisabled?.()) {
1968
- return { tools: [] };
1969
- }
1970
- return {
1971
- tools: context.bridgeConfig ? BROWSER_TOOLS : BROWSER_TOOLS.filter((t) => t.name !== "switch_browser")
1972
- };
1973
- });
1974
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
1975
- logger.info(`[${serverName}] Executing tool: ${request.params.name}`);
1976
- return handleToolCall(context, socketClient, request.params.name, request.params.arguments || {});
1977
- });
1978
- socketClient.setNotificationHandler((notification) => {
1979
- logger.info(`[${serverName}] Forwarding MCP notification: ${notification.method}`);
1980
- server.notification({
1981
- method: notification.method,
1982
- params: notification.params
1983
- }).catch((error) => {
1984
- logger.info(`[${serverName}] Failed to forward MCP notification: ${error.message}`);
1985
- });
1986
- });
1987
- return server;
1988
- }
1989
- var init_mcpServer = __esm(() => {
1990
- init_server();
1991
- init_types();
1992
- init_bridgeClient();
1993
- init_browserTools();
1994
- init_mcpSocketClient();
1995
- init_mcpSocketPool();
1996
- init_toolCalls();
1997
- });
1998
-
1999
- // packages/@ant/claude-for-chrome-mcp/src/index.ts
2000
- var init_src = __esm(() => {
2001
- init_bridgeClient();
2002
- init_browserTools();
2003
- init_mcpServer();
2004
- init_types2();
2005
- });
2006
-
2007
- export { localPlatformLabel, BridgeClient, createBridgeClient, BROWSER_TOOLS, createChromeSocketClient, createClaudeForChromeMcpServer, init_src };