@jackwener/browsermcp 0.0.0-stage → 0.0.32

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 (325) hide show
  1. package/CHANGELOG.md +317 -0
  2. package/LICENSE +202 -0
  3. package/README.md +177 -2
  4. package/adapter-sdk/index.d.ts +94 -0
  5. package/adapter-sdk/index.js +30 -0
  6. package/adapters/bilibili/_shared.js +254 -0
  7. package/adapters/bilibili/comment.js +55 -0
  8. package/adapters/bilibili/comments.js +47 -0
  9. package/adapters/bilibili/download.js +73 -0
  10. package/adapters/bilibili/dynamic.js +29 -0
  11. package/adapters/bilibili/favorite.js +39 -0
  12. package/adapters/bilibili/feed-detail.js +66 -0
  13. package/adapters/bilibili/feed.js +95 -0
  14. package/adapters/bilibili/follow.js +36 -0
  15. package/adapters/bilibili/following.js +29 -0
  16. package/adapters/bilibili/history.js +27 -0
  17. package/adapters/bilibili/hot.js +25 -0
  18. package/adapters/bilibili/me.js +24 -0
  19. package/adapters/bilibili/popular.js +26 -0
  20. package/adapters/bilibili/ranking.js +24 -0
  21. package/adapters/bilibili/search.js +37 -0
  22. package/adapters/bilibili/site.json +3 -0
  23. package/adapters/bilibili/subtitle.js +49 -0
  24. package/adapters/bilibili/summary.js +59 -0
  25. package/adapters/bilibili/unfollow.js +35 -0
  26. package/adapters/bilibili/user-videos.js +32 -0
  27. package/adapters/bilibili/video.js +70 -0
  28. package/adapters/discord/_shared.js +112 -0
  29. package/adapters/discord/channels.js +22 -0
  30. package/adapters/discord/delete.js +22 -0
  31. package/adapters/discord/goto.js +23 -0
  32. package/adapters/discord/members.js +28 -0
  33. package/adapters/discord/read.js +24 -0
  34. package/adapters/discord/search.js +28 -0
  35. package/adapters/discord/send.js +22 -0
  36. package/adapters/discord/servers.js +14 -0
  37. package/adapters/discord/site.json +1 -0
  38. package/adapters/discord/status.js +13 -0
  39. package/adapters/discord/thread-read.js +25 -0
  40. package/adapters/discord/threads.js +42 -0
  41. package/adapters/facebook/_friending.js +64 -0
  42. package/adapters/facebook/_graphql.js +51 -0
  43. package/adapters/facebook/_marketplace.js +31 -0
  44. package/adapters/facebook/_shared.js +148 -0
  45. package/adapters/facebook/add-friend.js +14 -0
  46. package/adapters/facebook/cancel-friend-request.js +14 -0
  47. package/adapters/facebook/events.js +77 -0
  48. package/adapters/facebook/feed.js +146 -0
  49. package/adapters/facebook/friends.js +72 -0
  50. package/adapters/facebook/groups.js +69 -0
  51. package/adapters/facebook/join-group.js +68 -0
  52. package/adapters/facebook/marketplace-inbox.js +71 -0
  53. package/adapters/facebook/marketplace-listings.js +68 -0
  54. package/adapters/facebook/memories.js +38 -0
  55. package/adapters/facebook/notifications.js +82 -0
  56. package/adapters/facebook/posts.js +19 -0
  57. package/adapters/facebook/profile.js +66 -0
  58. package/adapters/facebook/search.js +20 -0
  59. package/adapters/facebook/site.json +1 -0
  60. package/adapters/gmail/_query.js +19 -0
  61. package/adapters/gmail/_shared.js +241 -0
  62. package/adapters/gmail/attachments.js +17 -0
  63. package/adapters/gmail/create-draft.js +13 -0
  64. package/adapters/gmail/delete.js +30 -0
  65. package/adapters/gmail/drafts.js +2 -0
  66. package/adapters/gmail/forward.js +30 -0
  67. package/adapters/gmail/important.js +2 -0
  68. package/adapters/gmail/inbox.js +2 -0
  69. package/adapters/gmail/labels.js +10 -0
  70. package/adapters/gmail/modify.js +44 -0
  71. package/adapters/gmail/reply.js +28 -0
  72. package/adapters/gmail/search.js +21 -0
  73. package/adapters/gmail/send.js +84 -0
  74. package/adapters/gmail/sent.js +2 -0
  75. package/adapters/gmail/site.json +1 -0
  76. package/adapters/gmail/snoozed.js +2 -0
  77. package/adapters/gmail/spam.js +2 -0
  78. package/adapters/gmail/starred.js +2 -0
  79. package/adapters/gmail/thread.js +16 -0
  80. package/adapters/gmail/trash.js +2 -0
  81. package/adapters/gmail/unread.js +2 -0
  82. package/adapters/linkedin/_profile-card.js +42 -0
  83. package/adapters/linkedin/_profile-sections.js +76 -0
  84. package/adapters/linkedin/_profile.js +112 -0
  85. package/adapters/linkedin/_shared.js +50 -0
  86. package/adapters/linkedin/company.js +56 -0
  87. package/adapters/linkedin/connect.js +53 -0
  88. package/adapters/linkedin/connections.js +45 -0
  89. package/adapters/linkedin/inbox.js +102 -0
  90. package/adapters/linkedin/job-detail.js +49 -0
  91. package/adapters/linkedin/jobs-preferences.js +33 -0
  92. package/adapters/linkedin/jobs.js +98 -0
  93. package/adapters/linkedin/people-search.js +52 -0
  94. package/adapters/linkedin/post-analytics.js +38 -0
  95. package/adapters/linkedin/posts.js +21 -0
  96. package/adapters/linkedin/profile-analytics.js +43 -0
  97. package/adapters/linkedin/profile-experience.js +18 -0
  98. package/adapters/linkedin/profile-projects.js +18 -0
  99. package/adapters/linkedin/profile-read.js +32 -0
  100. package/adapters/linkedin/salesnav-inbox.js +52 -0
  101. package/adapters/linkedin/salesnav-message.js +126 -0
  102. package/adapters/linkedin/salesnav-search.js +56 -0
  103. package/adapters/linkedin/salesnav-thread.js +106 -0
  104. package/adapters/linkedin/sent-invitations.js +40 -0
  105. package/adapters/linkedin/services-read.js +81 -0
  106. package/adapters/linkedin/site.json +3 -0
  107. package/adapters/linkedin/timeline.js +45 -0
  108. package/adapters/reddit/_shared.js +115 -0
  109. package/adapters/reddit/comment.js +26 -0
  110. package/adapters/reddit/frontpage.js +22 -0
  111. package/adapters/reddit/home.js +25 -0
  112. package/adapters/reddit/hot.js +25 -0
  113. package/adapters/reddit/popular.js +22 -0
  114. package/adapters/reddit/read.js +156 -0
  115. package/adapters/reddit/reply.js +26 -0
  116. package/adapters/reddit/save.js +21 -0
  117. package/adapters/reddit/saved.js +23 -0
  118. package/adapters/reddit/search.js +31 -0
  119. package/adapters/reddit/site.json +3 -0
  120. package/adapters/reddit/subreddit-info.js +39 -0
  121. package/adapters/reddit/subreddit.js +27 -0
  122. package/adapters/reddit/subscribe.js +20 -0
  123. package/adapters/reddit/subscribed.js +43 -0
  124. package/adapters/reddit/upvote.js +23 -0
  125. package/adapters/reddit/upvoted.js +23 -0
  126. package/adapters/reddit/user-comments.js +25 -0
  127. package/adapters/reddit/user-posts.js +25 -0
  128. package/adapters/reddit/user.js +36 -0
  129. package/adapters/reddit/whoami.js +29 -0
  130. package/adapters/twitter/_shared.js +345 -0
  131. package/adapters/twitter/accept.js +16 -0
  132. package/adapters/twitter/article.js +104 -0
  133. package/adapters/twitter/block.js +16 -0
  134. package/adapters/twitter/bookmark-folder.js +39 -0
  135. package/adapters/twitter/bookmark-folders.js +46 -0
  136. package/adapters/twitter/bookmark.js +14 -0
  137. package/adapters/twitter/bookmarks.js +33 -0
  138. package/adapters/twitter/collection.js +135 -0
  139. package/adapters/twitter/delete.js +14 -0
  140. package/adapters/twitter/device-follow.js +60 -0
  141. package/adapters/twitter/download.js +87 -0
  142. package/adapters/twitter/follow-batch.js +28 -0
  143. package/adapters/twitter/follow.js +16 -0
  144. package/adapters/twitter/followers.js +60 -0
  145. package/adapters/twitter/following.js +65 -0
  146. package/adapters/twitter/hide-reply.js +19 -0
  147. package/adapters/twitter/like.js +14 -0
  148. package/adapters/twitter/likes.js +41 -0
  149. package/adapters/twitter/list-add-batch.js +30 -0
  150. package/adapters/twitter/list-add.js +53 -0
  151. package/adapters/twitter/list-create.js +45 -0
  152. package/adapters/twitter/list-delete.js +15 -0
  153. package/adapters/twitter/list-remove-batch.js +30 -0
  154. package/adapters/twitter/list-remove.js +28 -0
  155. package/adapters/twitter/list-tweets.js +38 -0
  156. package/adapters/twitter/lists.js +18 -0
  157. package/adapters/twitter/mute-word.js +15 -0
  158. package/adapters/twitter/notifications.js +90 -0
  159. package/adapters/twitter/post.js +18 -0
  160. package/adapters/twitter/profile.js +43 -0
  161. package/adapters/twitter/quote.js +23 -0
  162. package/adapters/twitter/reply-dm.js +49 -0
  163. package/adapters/twitter/reply.js +23 -0
  164. package/adapters/twitter/retweet.js +16 -0
  165. package/adapters/twitter/search.js +150 -0
  166. package/adapters/twitter/site.json +3 -0
  167. package/adapters/twitter/thread.js +56 -0
  168. package/adapters/twitter/timeline.js +62 -0
  169. package/adapters/twitter/trending.js +32 -0
  170. package/adapters/twitter/tweets.js +46 -0
  171. package/adapters/twitter/unblock.js +16 -0
  172. package/adapters/twitter/unbookmark.js +14 -0
  173. package/adapters/twitter/unfollow.js +16 -0
  174. package/adapters/twitter/unlike.js +14 -0
  175. package/adapters/twitter/unretweet.js +15 -0
  176. package/cordis.patch.yml +15 -0
  177. package/dist/docs/api-reference.md +288 -0
  178. package/dist/docs/api-use.md +72 -0
  179. package/dist/docs/capabilities/cdp.md +7 -0
  180. package/dist/docs/capabilities/chrome.md +60 -0
  181. package/dist/docs/capabilities/visibility.md +2 -0
  182. package/dist/docs/capabilities/webmcp.md +2 -0
  183. package/dist/docs/define-tools.md +25 -0
  184. package/dist/docs/errors.md +28 -0
  185. package/dist/docs/instructions.md +14 -0
  186. package/dist/docs/js-tool.md +34 -0
  187. package/dist/docs/recon.md +5 -0
  188. package/dist/docs/repl-session.md +23 -0
  189. package/dist/docs/safety.md +8 -0
  190. package/dist/docs/sites.md +22 -0
  191. package/dist/docs/tab-lifecycle.md +15 -0
  192. package/dist/docs/troubleshooting.md +7 -0
  193. package/dist/src/api/action-input.js +165 -0
  194. package/dist/src/api/action-input.js.map +1 -0
  195. package/dist/src/api/agent.js +11 -0
  196. package/dist/src/api/agent.js.map +1 -0
  197. package/dist/src/api/api.js +69 -0
  198. package/dist/src/api/api.js.map +1 -0
  199. package/dist/src/api/browser.js +135 -0
  200. package/dist/src/api/browser.js.map +1 -0
  201. package/dist/src/api/context.js +2 -0
  202. package/dist/src/api/context.js.map +1 -0
  203. package/dist/src/api/diff.js +65 -0
  204. package/dist/src/api/diff.js.map +1 -0
  205. package/dist/src/api/errors.js +24 -0
  206. package/dist/src/api/errors.js.map +1 -0
  207. package/dist/src/api/network.js +33 -0
  208. package/dist/src/api/network.js.map +1 -0
  209. package/dist/src/api/observation.js +95 -0
  210. package/dist/src/api/observation.js.map +1 -0
  211. package/dist/src/api/streams.js +33 -0
  212. package/dist/src/api/streams.js.map +1 -0
  213. package/dist/src/api/tab.js +416 -0
  214. package/dist/src/api/tab.js.map +1 -0
  215. package/dist/src/backends/browser-helpers.js +76 -0
  216. package/dist/src/backends/browser-helpers.js.map +1 -0
  217. package/dist/src/backends/extension-page.js +305 -0
  218. package/dist/src/backends/extension-page.js.map +1 -0
  219. package/dist/src/backends/page-types.js +2 -0
  220. package/dist/src/backends/page-types.js.map +1 -0
  221. package/dist/src/docs/manifest.js +92 -0
  222. package/dist/src/docs/manifest.js.map +1 -0
  223. package/dist/src/docs/surface.js +95 -0
  224. package/dist/src/docs/surface.js.map +1 -0
  225. package/dist/src/host/bridge.js +126 -0
  226. package/dist/src/host/bridge.js.map +1 -0
  227. package/dist/src/host/doctor.js +92 -0
  228. package/dist/src/host/doctor.js.map +1 -0
  229. package/dist/src/host/extension.js +4 -0
  230. package/dist/src/host/extension.js.map +1 -0
  231. package/dist/src/host/host.js +77 -0
  232. package/dist/src/host/host.js.map +1 -0
  233. package/dist/src/host/ipc.js +80 -0
  234. package/dist/src/host/ipc.js.map +1 -0
  235. package/dist/src/host/jsonc-config.js +33 -0
  236. package/dist/src/host/jsonc-config.js.map +1 -0
  237. package/dist/src/host/launch.js +103 -0
  238. package/dist/src/host/launch.js.map +1 -0
  239. package/dist/src/host/native-messaging.js +81 -0
  240. package/dist/src/host/native-messaging.js.map +1 -0
  241. package/dist/src/host/opencode.js +14 -0
  242. package/dist/src/host/opencode.js.map +1 -0
  243. package/dist/src/host/pi.js +11 -0
  244. package/dist/src/host/pi.js.map +1 -0
  245. package/dist/src/host/registration.js +121 -0
  246. package/dist/src/host/registration.js.map +1 -0
  247. package/dist/src/host/setup.js +204 -0
  248. package/dist/src/host/setup.js.map +1 -0
  249. package/dist/src/host/socket.js +99 -0
  250. package/dist/src/host/socket.js.map +1 -0
  251. package/dist/src/host/state.js +124 -0
  252. package/dist/src/host/state.js.map +1 -0
  253. package/dist/src/launcher/stdio.js +153 -0
  254. package/dist/src/launcher/stdio.js.map +1 -0
  255. package/dist/src/lib/sources.js +27 -0
  256. package/dist/src/lib/sources.js.map +1 -0
  257. package/dist/src/main.js +131 -0
  258. package/dist/src/main.js.map +1 -0
  259. package/dist/src/mcp/catalog.js +28 -0
  260. package/dist/src/mcp/catalog.js.map +1 -0
  261. package/dist/src/mcp/js-evaluator.mjs +65 -0
  262. package/dist/src/mcp/js-session.js +292 -0
  263. package/dist/src/mcp/js-session.js.map +1 -0
  264. package/dist/src/mcp/js-worker.mjs +135 -0
  265. package/dist/src/mcp/server.js +221 -0
  266. package/dist/src/mcp/server.js.map +1 -0
  267. package/dist/src/protocol.js +18 -0
  268. package/dist/src/protocol.js.map +1 -0
  269. package/dist/src/recon/analyzer.js +366 -0
  270. package/dist/src/recon/analyzer.js.map +1 -0
  271. package/dist/src/recon/discover.js +130 -0
  272. package/dist/src/recon/discover.js.map +1 -0
  273. package/dist/src/runtime/runtime.js +221 -0
  274. package/dist/src/runtime/runtime.js.map +1 -0
  275. package/dist/src/shared/aria-tree.js +16 -0
  276. package/dist/src/shared/aria-tree.js.map +1 -0
  277. package/dist/src/shared/element-ref.js +7 -0
  278. package/dist/src/shared/element-ref.js.map +1 -0
  279. package/dist/src/shared/engine.js +426 -0
  280. package/dist/src/shared/engine.js.map +1 -0
  281. package/dist/src/shared/injected-source.js +5 -0
  282. package/dist/src/shared/injected-source.js.map +1 -0
  283. package/dist/src/shared/page-contract.js +8 -0
  284. package/dist/src/shared/page-contract.js.map +1 -0
  285. package/dist/src/sites/define.js +110 -0
  286. package/dist/src/sites/define.js.map +1 -0
  287. package/dist/src/sites/drafts.js +134 -0
  288. package/dist/src/sites/drafts.js.map +1 -0
  289. package/dist/src/sites/executor.js +75 -0
  290. package/dist/src/sites/executor.js.map +1 -0
  291. package/dist/src/sites/loader.js +234 -0
  292. package/dist/src/sites/loader.js.map +1 -0
  293. package/dist/src/sites/schema.js +169 -0
  294. package/dist/src/sites/schema.js.map +1 -0
  295. package/docs/api-reference.md +288 -0
  296. package/docs/api-use.md +72 -0
  297. package/docs/capabilities/cdp.md +7 -0
  298. package/docs/capabilities/chrome.md +60 -0
  299. package/docs/capabilities/visibility.md +2 -0
  300. package/docs/capabilities/webmcp.md +2 -0
  301. package/docs/define-tools.md +25 -0
  302. package/docs/errors.md +28 -0
  303. package/docs/guide.zh-CN.md +49 -0
  304. package/docs/instructions.md +14 -0
  305. package/docs/js-tool.md +34 -0
  306. package/docs/observation-design.md +43 -0
  307. package/docs/recon.md +5 -0
  308. package/docs/releasing.md +26 -0
  309. package/docs/repl-session.md +23 -0
  310. package/docs/safety.md +8 -0
  311. package/docs/setup.md +241 -0
  312. package/docs/sites.md +22 -0
  313. package/docs/tab-lifecycle.md +15 -0
  314. package/docs/troubleshooting.md +7 -0
  315. package/extension/dist/background.js +5263 -0
  316. package/extension/dist/chrome-reference.LICENSE.txt +21 -0
  317. package/extension/dist/content/cursor.js +156 -0
  318. package/extension/dist/cursor.svg +4 -0
  319. package/extension/dist/icons/icon-128.png +0 -0
  320. package/extension/dist/icons/icon-16.png +0 -0
  321. package/extension/dist/icons/icon-32.png +0 -0
  322. package/extension/dist/icons/icon-48.png +0 -0
  323. package/extension/dist/manifest.json +48 -0
  324. package/extension/dist/page.js +801 -0
  325. package/package.json +76 -4
package/README.md CHANGED
@@ -1,3 +1,178 @@
1
- # Temporary Holding Version
1
+ # BrowserMCP
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **A browser service for MCP agents, connected to the Chrome you're already logged into.**
4
+
5
+ BrowserMCP lets MCP clients observe and operate your Chrome tabs through a local extension and host. Optional site adapters package verified workflows as reusable tools.
6
+
7
+ [![npm](https://img.shields.io/npm/v/@jackwener/browsermcp)](https://www.npmjs.com/package/@jackwener/browsermcp)
8
+ [![Chrome Web Store](https://img.shields.io/badge/Chrome_Web_Store-Install_extension-4285F4?logo=googlechrome&logoColor=white)](https://chromewebstore.google.com/detail/opencli-mcp/lnaoghmfcdnbhgcihkakfobckmfhllkg)
9
+ [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D22-339933)](package.json)
10
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
11
+
12
+ [Quick start](#quick-start) · [Usage](#usage) · [Documentation](#documentation) · [中文指南](docs/guide.zh-CN.md)
13
+
14
+ ## What you can do
15
+
16
+ - **Work with logged-in websites.** Search, read pages, fill forms, and navigate through your existing browser session.
17
+ - **Use optional site commands.** Discover built-in adapters for Twitter/X, Bilibili, and Reddit when a site-specific command helps.
18
+ - **Add site adapters.** Inspect a site's requests, verify an API, and define an explicit reusable MCP tool.
19
+ - **Keep browser work organized.** Agent-created tabs live in named groups and are cleaned up after use. Tabs borrowed from the user are never closed by session cleanup.
20
+
21
+ Works with MCP clients including Claude Code, Codex, OpenCode, Cursor, Claude Desktop, DeepSeek Harness (`dsh`), and Pi (with `pi-mcp-adapter`). Agents use a persistent JavaScript REPL for browser work and structured site tools for verified workflows.
22
+
23
+ The npm package is `@jackwener/browsermcp`; the command is `browsermcp`.
24
+
25
+ ## Quick start
26
+
27
+ You need **Node.js 22 or newer**, **Google Chrome**, and an **MCP client**. The local host also supports Chromium-based browsers such as Edge and Brave; see [installation details](docs/setup.md).
28
+
29
+ ### 1. Install the Chrome extension
30
+
31
+ [**Install BrowserMCP Connector from the Chrome Web Store →**](https://chromewebstore.google.com/detail/opencli-mcp/lnaoghmfcdnbhgcihkakfobckmfhllkg)
32
+
33
+ For an extension version ahead of the Web Store, download the **manual-install zip** from [GitHub Releases](https://github.com/jackwener/browsermcp/releases) and follow the [manual installation steps](docs/setup.md#manual-extension-installation).
34
+
35
+ ### 2. Install the npm package and set up the connection
36
+
37
+ ```bash
38
+ npm install -g @jackwener/browsermcp
39
+ browsermcp setup
40
+ ```
41
+
42
+ Keep Chrome open. `setup` connects the extension to the local program, asks which MCP clients to configure, registers only your selection, and checks the browser connection. If you have not installed the extension yet, it opens the Chrome Web Store for you.
43
+
44
+ For **Cursor, Claude Desktop, and other MCP clients**, choose `manual` and copy the configuration printed by `setup` into your client's MCP settings. It uses absolute paths so desktop apps can find the program.
45
+
46
+ For **OpenCode**, run `browsermcp setup --clients opencode`. It adds a global MCP entry while preserving your other settings.
47
+
48
+ For **DeepSeek Harness (`dsh`)**, run `browsermcp setup --clients none`, then add the same npm package to your dsh profile:
49
+
50
+ ```bash
51
+ dsh plugin --profile web add @jackwener/browsermcp
52
+ ```
53
+
54
+ Restart `dsh web`. The package's dsh bundle uses dsh's MCP client to connect to the browser service. See the [dsh setup details](docs/setup.md#deepseek-harness-dsh).
55
+
56
+ For **Pi**, install `pi-mcp-adapter`, then run `browsermcp setup --clients pi`. See the [Pi setup steps](docs/setup.md#pi).
57
+
58
+ ### 3. Start using it
59
+
60
+ Restart or reconnect your MCP client, then ask:
61
+
62
+ > Use browsermcp to read the top five Hacker News stories and summarize them with links.
63
+
64
+ You can rerun `browsermcp setup` to repair the browser registration or select newly installed clients to configure. Selected clients have their `browsermcp` entry updated to a stable launcher; other server entries are preserved. The launcher follows Homebrew upgrades within the same formula. If Node or the package moves, rerun setup. For a read-only startup and connection check, run `browsermcp doctor`.
65
+
66
+ Connection issues? See [troubleshooting](docs/setup.md#troubleshooting).
67
+
68
+ ## Upgrading from opencli-mcp
69
+
70
+ Install `@jackwener/browsermcp` and rerun `browsermcp setup`, selecting the MCP clients you want to update. Setup replaces their old `opencli-mcp` entry with `browsermcp`. For manually configured clients, update the entry yourself. The extension is now named **BrowserMCP Connector** and keeps its existing Web Store ID.
71
+
72
+ Existing data in `~/.opencli-mcp`, the stable launcher, and the Native Messaging host identity are retained for compatibility. Existing adapters can still import `opencli-mcp/adapter-sdk`; new adapters use `@jackwener/browsermcp/adapter-sdk`. `BROWSERMCP_BROWSER` and `BROWSERMCP_BIN` take precedence over their legacy `OPENCLI_MCP_*` equivalents.
73
+
74
+ ## Usage
75
+
76
+ Tell your agent what you want to do; it discovers and calls the MCP tools. For example:
77
+
78
+ - “Open Hacker News, read the newest stories, and keep the most useful page open for me.”
79
+ - “Search for site commands that work with Bilibili.”
80
+ - “Explore this website's search, then create a reusable tool for the same query workflow.”
81
+
82
+ For integrations and custom workflows, the main tools are:
83
+
84
+ | Task | Tools |
85
+ |---|---|
86
+ | Browser workspace | `js`, `js_reset` |
87
+ | Discover and run site commands | `sites_search`, `site_run` |
88
+ | Learn the API | `docs_get` (quickstart, topics, or an exact API member) |
89
+ | Diagnose connection and execution | `doctor` |
90
+ | Finish a browser session | `session_finalize` |
91
+
92
+ The browser workflow is **observe → act → verify → finalize**, expressed in `js` using the same object model as adapters:
93
+
94
+ ```js
95
+ let tab = await browser.tabs.new('https://example.com/');
96
+ await tab.observe();
97
+ ```
98
+
99
+ Variables, functions, classes and Tab handles persist across calls. After inspecting the result, use `await tab.act(...)` and `await tab.expect(...)` or observe again. Keep working data in variables and return only relevant evidence. `docs_get {}` provides a compact quickstart; `{name:"api-reference",member:"Tab.act"}` provides exact types. No repository documentation access is required.
100
+
101
+ Use `browser.user.openTabs({query,limit})` and `browser.user.claimTab(...)` for user tabs. The lookup returns up to 20 recent matches by default. `tab.release()` leaves a tab open; `tab.close()` closes it. `session_finalize` closes agent tabs not kept and releases borrowed tabs. `js_reset` stops JavaScript and clears bindings while leaving tabs open; already dispatched operations may still complete. All API methods are awaited.
102
+
103
+ Inside the `js` tool, you can also call site commands directly:
104
+
105
+ ```js
106
+ await sites.enable('reddit');
107
+ const posts = await sites.reddit.hot({ subreddit: 'programming', limit: 5 });
108
+ posts;
109
+ ```
110
+
111
+ See the [JavaScript guide](docs/js-tool.md), [API reference](docs/api-reference.md), and [tool authoring guide](docs/define-tools.md) for complete examples.
112
+
113
+ ## How it works
114
+
115
+ ```text
116
+ MCP client → browsermcp launcher → local host ⇄ Chrome extension → website
117
+ stdio Native Messaging your session
118
+ ```
119
+
120
+ Chrome starts the local host through Native Messaging. The extension operates browser tabs using Chrome's debugger APIs and Playwright's injected locator engine. The host exposes browser operations, site commands, and tool authoring through MCP.
121
+ Each MCP client connection has its own tab and JavaScript session, so one client's cleanup does not close another client's tabs.
122
+
123
+ The MCP launcher can start before Chrome. It keeps the client connection open and reconnects when the Chrome-owned host appears or restarts. Browser operations and site adapters use that host; run `browsermcp doctor` if it stays unavailable.
124
+
125
+ Connections are local-only: standard MCP stdio to the launcher, then Unix domain socket (macOS/Linux) or named pipe (Windows) to the host. No port or token configuration. See [browser selection and configuration](docs/setup.md#local-connections-and-browser-selection).
126
+
127
+ ## Browser access and permissions
128
+
129
+ The extension requests browser permissions including `debugger`, `cookies`, and access to all URLs so it can operate logged-in sites. Connected agents can act with the access available in your browser session.
130
+
131
+ Site commands execute directly without additional approval prompts. The read/write classification describes their effects. See [configuration](docs/setup.md#configuration).
132
+
133
+ ## Documentation
134
+
135
+ | Guide | Contents |
136
+ |---|---|
137
+ | [Installation and configuration](docs/setup.md) | Source installs, browser profiles, local connections, settings, troubleshooting |
138
+ | [中文指南](docs/guide.zh-CN.md) | Chinese project overview and detailed usage |
139
+ | [Site commands](docs/sites.md) | Discovering, enabling, and running adapters |
140
+ | [JavaScript guide](docs/js-tool.md) | Persistent sessions and the object API |
141
+ | [API reference](docs/api-reference.md) | Generated reference for browser and tool APIs |
142
+ | [Creating tools](docs/define-tools.md) | Define and verify reusable site adapters |
143
+ | [Tab lifecycle](docs/tab-lifecycle.md) | Claiming tabs, grouping, and cleanup |
144
+ | [Errors](docs/errors.md) | Error codes and recovery |
145
+
146
+ ## Development
147
+
148
+ ```bash
149
+ git clone https://github.com/jackwener/browsermcp.git browsermcp
150
+ cd browsermcp
151
+ npm install
152
+ npm run typecheck
153
+ ```
154
+
155
+ `npm install` builds the project through its `prepare` script. To connect a development build to Chrome, follow [the unpacked-extension instructions](docs/setup.md#from-source).
156
+
157
+ ```bash
158
+ npm run build:ext # rebuild the extension
159
+ npm test # core regression tests
160
+ npm run smoke:setup # isolated setup and Native Messaging end-to-end check
161
+ npm run smoke:browser # end-to-end check with a connected Chrome extension
162
+ ```
163
+
164
+ Keep the automated suite focused on MCP browser flow, REPL persistence and interruption, connection recovery, session isolation, tab cleanup, and adapter execution. Prefer these integration checks over per-adapter mapping tests and implementation-detail assertions. Run the tests relevant to your change. `npm run check` runs typecheck, build, and the full test suite when a broader check is needed. For browser changes, use the browser smoke test. `docs/api-reference.md` is generated during the build; update its TypeScript source rather than editing the generated file.
165
+
166
+ Maintainers: use the [release workflow](docs/releasing.md) to publish the npm package and GitHub Release.
167
+
168
+ Found a bug or have a feature request? [Open an issue](https://github.com/jackwener/browsermcp/issues). See [CHANGELOG.md](CHANGELOG.md) for release history.
169
+
170
+ ## License and credits
171
+
172
+ [Apache-2.0](LICENSE). Some browser helpers and adapters were adapted from [OpenCLI](https://github.com/jackwener/OpenCLI); no OpenCLI dependency or compatibility layer is required. Uses [Playwright](https://github.com/microsoft/playwright)'s injected locator engine. Endpoint analysis is inspired by [jsluice](https://github.com/BishopFox/jsluice).
173
+
174
+ ### Native browser APIs
175
+
176
+ The REPL also exposes `browser.chrome.call(method, argsArray)` for native Chrome APIs, `tab.cdp.send(method, params)` for an explicit Tab, and writable Main World `tab.evaluate(script, {arg, timeoutMs})`. Use `browser.chrome.describe("tabs.query")` for on-demand signatures and runtime availability. Chrome/CDP events and page/extension logs support bounded subscriptions with explicit loss/reset information. Read `docs_get {name:"capabilities/chrome"}` inside MCP for examples and lifecycle rules, or [the native capabilities guide](docs/capabilities/chrome.md).
177
+
178
+ For development, `npm run smoke:native` runs the new flows in a disposable Chromium profile after a build. Set `OPENCLI_SMOKE_CHROME` to a Chromium executable when it is not available in the local Playwright cache. It does not modify the everyday browser profile or native-host registration.
@@ -0,0 +1,94 @@
1
+ // browsermcp/adapter-sdk — the adapter contract (types). This file is the source of truth for what an adapter may use.
2
+
3
+ export type Access = 'read' | 'write';
4
+
5
+ export interface ArgValue {
6
+ type?: 'string' | 'int' | 'number' | 'boolean' | 'array' | 'object';
7
+ nullable?: boolean;
8
+ choices?: Array<string | number | boolean>;
9
+ items?: ArgValue;
10
+ properties?: Record<string, ArgValue & { required?: boolean; help?: string }>;
11
+ min?: number;
12
+ max?: number;
13
+ minLength?: number;
14
+ maxLength?: number;
15
+ /** One representative value, shown to the agent; not used as a default. */
16
+ example?: unknown;
17
+ }
18
+
19
+ export interface Arg extends ArgValue {
20
+ /** snake_case, agent-native JSON key */
21
+ name: string;
22
+ required?: boolean;
23
+ default?: unknown;
24
+ /** one line, agent-facing, no CLI grammar */
25
+ help?: string;
26
+ }
27
+
28
+ /** Cursor-paged network read (pass `afterSequence` from the previous result). */
29
+ export interface NetworkReadResult { cursor: number; entries: unknown[]; hasMore: boolean }
30
+
31
+ /**
32
+ * The tab object model — the SAME surface an agent drives in the `js` tool. An adapter's `run` gets one bound to the
33
+ * site's page. This interface is the adapter-visible subset; the core's Tab satisfies it structurally.
34
+ */
35
+ export interface Tab {
36
+ readonly id: string;
37
+ goto(url: string, opts?: { waitUntil?: 'load' | 'none'; settleMs?: number }): Promise<{ url: string | null; title: string | null }>;
38
+ url(): Promise<string | null>;
39
+ reload(): Promise<void>;
40
+ title(): Promise<string | null>;
41
+ observe(opts?: Record<string, unknown>): Promise<Record<string, unknown>>;
42
+ act(opts: Record<string, unknown>): Promise<Record<string, unknown>>;
43
+ find(target: Record<string, unknown>): Promise<unknown>;
44
+ expect(what: Record<string, unknown>, opts?: { timeoutMs?: number }): Promise<unknown>;
45
+ evaluate(js: string | ((arg: any) => any), opts?: { arg?: unknown; frame?: number; timeoutMs?: number }): Promise<unknown>;
46
+ /** Fetch JSON through the page (its cookies, its origin) — the network-first way to call a site's own API. */
47
+ fetchJson(url: string, opts?: Record<string, unknown>): Promise<unknown>;
48
+ /** Read one cookie's value at run time (e.g. a csrf token). */
49
+ cookie(name: string, opts?: { domain?: string }): Promise<string | undefined>;
50
+ cookies(domain: string): Promise<unknown[]>;
51
+ screenshot(opts?: { fullPage?: boolean; annotate?: boolean; format?: 'png' | 'jpeg'; quality?: number }): Promise<unknown>;
52
+ readonly network: {
53
+ start(pattern?: string): Promise<boolean>;
54
+ list(opts?: { filter?: string; limit?: number; afterSequence?: number }): Promise<{ cursor: number; entries: unknown[]; hasMore: boolean }>;
55
+ detail(opts: { seq?: number; requestId?: string; part?: 'request' | 'response'; start?: number; maxChars?: number }): Promise<unknown>;
56
+ read(opts?: { pattern?: string; limit?: number; includeStatic?: boolean; afterSequence?: number }): Promise<NetworkReadResult>;
57
+ };
58
+ }
59
+
60
+ export interface Sites { [site: string]: Record<string, (args?: Record<string, unknown>) => Promise<unknown>> | unknown }
61
+ export interface Recon { discover(tab: Tab): Promise<unknown> }
62
+
63
+ /** What `run` receives. `tab` is the object model; `sites`/`recon` let an adapter reuse siblings + discovery. */
64
+ export interface AdapterContext {
65
+ args: Record<string, unknown>;
66
+ tab: Tab;
67
+ sites: Sites;
68
+ recon: Recon;
69
+ signal?: AbortSignal;
70
+ }
71
+
72
+ export interface AdapterDescriptor {
73
+ description: string;
74
+ access: Access;
75
+ /** Agent-facing result shape. `rows` may include nextCursor; `value` is one object/scalar. */
76
+ result?: { kind: 'rows' | 'value'; description: string; fields?: Record<string, string>; paginated?: boolean };
77
+ /** Site metadata and tool icon host; the adapter navigates explicitly when needed. */
78
+ domain?: string;
79
+ args?: Arg[];
80
+ /** aliases resolve to this command */
81
+ aliases?: string[];
82
+ run(ctx: AdapterContext): Promise<unknown>;
83
+ }
84
+
85
+ /** Validate + return an adapter descriptor. Pure: no registration, no side effects. */
86
+ export function defineAdapter(descriptor: AdapterDescriptor): AdapterDescriptor;
87
+
88
+ export class AdapterError extends Error { code: string; hint?: string; constructor(code: string, message: string, hint?: string); }
89
+ export const errors: {
90
+ auth(message?: string, hint?: string): AdapterError;
91
+ empty(message?: string): AdapterError;
92
+ argument(message: string, hint?: string): AdapterError;
93
+ upstream(message: string, hint?: string): AdapterError;
94
+ };
@@ -0,0 +1,30 @@
1
+ // browsermcp/adapter-sdk — the adapter contract (runtime). Pure: validate + return a descriptor, never register.
2
+
3
+ const ACCESS = new Set(['read', 'write']);
4
+
5
+ /** Validate an adapter descriptor and return it unchanged. No global state, no side effects. */
6
+ export function defineAdapter(descriptor) {
7
+ const d = descriptor ?? {};
8
+ if (typeof d.description !== 'string' || !d.description.trim()) throw new Error('adapter: `description` (non-empty string) is required');
9
+ if (!ACCESS.has(d.access)) throw new Error("adapter: `access` must be 'read' or 'write'");
10
+ if (typeof d.run !== 'function') throw new Error('adapter: `run` must be a function (ctx) => data');
11
+ if (d.result !== undefined && (!['rows', 'value'].includes(d.result?.kind) || typeof d.result?.description !== 'string' || !d.result.description.trim() || d.result.fields !== undefined && (!d.result.fields || typeof d.result.fields !== 'object' || Object.values(d.result.fields).some((v) => typeof v !== 'string')) || d.result.paginated && d.result.kind !== 'rows')) throw new Error('adapter: `result` needs kind rows|value and a description; fields must be text and paginated applies to rows');
12
+ if (d.args !== undefined) {
13
+ if (!Array.isArray(d.args)) throw new Error('adapter: `args` must be an array');
14
+ for (const a of d.args) if (!a || typeof a.name !== 'string' || !/^[a-z][a-z0-9_]*$/.test(a.name)) throw new Error(`adapter: arg name "${a?.name}" must be snake_case (agent-native)`);
15
+ }
16
+ return d;
17
+ }
18
+
19
+ /** A coded, agent-facing error an adapter can throw; the runtime surfaces { code, message, hint }. */
20
+ export class AdapterError extends Error {
21
+ constructor(code, message, hint) { super(message); this.name = 'AdapterError'; this.code = code; this.hint = hint; }
22
+ }
23
+
24
+ /** Common coded failures, so adapters branch on one vocabulary. */
25
+ export const errors = {
26
+ auth: (message = 'Not logged in', hint = 'Open the site and sign in, then retry.') => new AdapterError('auth_required', message, hint),
27
+ empty: (message = 'No results') => new AdapterError('empty_result', message),
28
+ argument: (message, hint) => new AdapterError('invalid_args', message, hint),
29
+ upstream: (message, hint) => new AdapterError('upstream_error', message, hint),
30
+ };
@@ -0,0 +1,254 @@
1
+ // Shared helpers for the Bilibili adapters. Files starting with `_` are not commands.
2
+ import { errors } from '@jackwener/browsermcp/adapter-sdk';
3
+ import { createHash } from 'node:crypto';
4
+ import https from 'node:https';
5
+
6
+ /** Be on bilibili.com so page-context fetches to api.bilibili.com carry the .bilibili.com session cookies. */
7
+ export async function ensureOnBili(tab) {
8
+ const u = await tab.url().catch(() => null);
9
+ if (!u || !/^https?:\/\/([a-z0-9-]+\.)?bilibili\.com/i.test(u)) await tab.goto('https://www.bilibili.com', { waitUntil: 'load' });
10
+ }
11
+
12
+ /** Bilibili treats these codes / messages as auth/permission failures rather than app errors. */
13
+ function isAuthLike(code, message) {
14
+ return code === -101 || code === -111 || code === -400 || code === -403 || /csrf|登录|账号|权限|forbidden|permission|login/i.test(String(message ?? ''));
15
+ }
16
+
17
+ /** Unwrap a Bilibili `{ code, message, data }` envelope, routing auth failures to errors.auth. */
18
+ function unwrap(res, label) {
19
+ if (!res || typeof res !== 'object') throw errors.upstream(`Bilibili ${label || ''} returned no JSON`.trim());
20
+ if (res.code !== 0) {
21
+ if (isAuthLike(res.code, res.message)) throw errors.auth(`Bilibili: ${res.message || 'not logged in'} (${res.code})`);
22
+ throw errors.upstream(`Bilibili error ${res.code}: ${res.message || 'unknown'}`);
23
+ }
24
+ return res.data;
25
+ }
26
+
27
+ /** GET a Bilibili web-interface JSON endpoint through the logged-in page; unwrap { code, message, data }. */
28
+ export async function biliGet(tab, url) {
29
+ return unwrap(await tab.fetchJson(url), '');
30
+ }
31
+
32
+ /** Build an api.bilibili.com URL with query params (spaces as %20, per Bilibili's WBI expectations). */
33
+ function buildUrl(path, params) {
34
+ const entries = Object.entries(params).map(([k, v]) => [k, String(v)]);
35
+ const qs = new URLSearchParams(Object.fromEntries(entries)).toString().replace(/\+/g, '%20');
36
+ return `https://api.bilibili.com${path}${qs ? `?${qs}` : ''}`;
37
+ }
38
+
39
+ /** GET an api.bilibili.com path with unsigned params. */
40
+ export async function biliApi(tab, path, params = {}) {
41
+ return biliGet(tab, buildUrl(path, params));
42
+ }
43
+
44
+ /** GET an api.bilibili.com path with WBI-signed params. */
45
+ export async function biliApiSigned(tab, path, params = {}) {
46
+ const signed = await wbiSign(tab, params);
47
+ return biliGet(tab, buildUrl(path, signed));
48
+ }
49
+
50
+ /** POST form-encoded params to an api.bilibili.com path; auto-attaches the bili_jct CSRF token. */
51
+ export async function biliPost(tab, path, params = {}) {
52
+ const csrf = await tab.cookie('bili_jct');
53
+ const body = new URLSearchParams(Object.fromEntries(Object.entries(params).map(([k, v]) => [k, String(v)])));
54
+ body.set('csrf', csrf || '');
55
+ const res = await tab.fetchJson(`https://api.bilibili.com${path}`, {
56
+ method: 'POST',
57
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
58
+ body: body.toString(),
59
+ });
60
+ return unwrap(res, 'write');
61
+ }
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // WBI signing — many read endpoints reject unsigned requests with 403/-403.
65
+ // Ported faithfully from the corpus utils.js.
66
+ // ---------------------------------------------------------------------------
67
+ const MIXIN_KEY_ENC_TAB = [
68
+ 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
69
+ 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40,
70
+ 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11,
71
+ 36, 20, 34, 44, 52,
72
+ ];
73
+
74
+ /** Raw nav payload (not unwrapped: nav returns code -101 when logged out but still carries wbi_img). */
75
+ async function getNavData(tab) {
76
+ const res = await tab.fetchJson('https://api.bilibili.com/x/web-interface/nav');
77
+ return res && typeof res === 'object' ? res : {};
78
+ }
79
+
80
+ async function getWbiKeys(tab) {
81
+ const nav = await getNavData(tab);
82
+ const wbiImg = nav?.data?.wbi_img ?? {};
83
+ const imgKey = (wbiImg.img_url ?? '').split('/').pop()?.split('.')[0] ?? '';
84
+ const subKey = (wbiImg.sub_url ?? '').split('/').pop()?.split('.')[0] ?? '';
85
+ return { imgKey, subKey };
86
+ }
87
+
88
+ function getMixinKey(imgKey, subKey) {
89
+ const raw = imgKey + subKey;
90
+ return MIXIN_KEY_ENC_TAB.map((i) => raw[i] || '').join('').slice(0, 32);
91
+ }
92
+
93
+ /** Sign a params object with Bilibili's WBI scheme; returns a new params object incl. wts + w_rid. */
94
+ export async function wbiSign(tab, params) {
95
+ const { imgKey, subKey } = await getWbiKeys(tab);
96
+ const mixinKey = getMixinKey(imgKey, subKey);
97
+ const wts = Math.floor(Date.now() / 1000);
98
+ const sorted = {};
99
+ const allParams = { ...params, wts: String(wts) };
100
+ for (const key of Object.keys(allParams).sort()) {
101
+ sorted[key] = String(allParams[key]).replace(/[!'()*]/g, '');
102
+ }
103
+ // Bilibili WBI verification expects %20 for spaces, not + (URLSearchParams default).
104
+ const query = new URLSearchParams(sorted).toString().replace(/\+/g, '%20');
105
+ sorted.w_rid = createHash('md5').update(query + mixinKey).digest('hex');
106
+ return sorted;
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // Identity / resolution helpers
111
+ // ---------------------------------------------------------------------------
112
+
113
+ /** The logged-in user's mid; throws auth if not logged in. */
114
+ export async function getSelfUid(tab) {
115
+ const nav = await getNavData(tab);
116
+ const mid = nav?.data?.mid;
117
+ if (!mid) throw errors.auth('Not logged in to Bilibili');
118
+ return String(mid);
119
+ }
120
+
121
+ /** Resolve a bare uid, or search a username → mid. */
122
+ export async function resolveUid(tab, input) {
123
+ const s = String(input ?? '').trim();
124
+ if (/^\d+$/.test(s)) return s;
125
+ const data = await biliApiSigned(tab, '/x/web-interface/wbi/search/type', { search_type: 'bili_user', keyword: s });
126
+ const results = data?.result;
127
+ if (!Array.isArray(results)) throw errors.upstream(`Bilibili user search returned malformed result for ${s}`);
128
+ const mid = String(results[0]?.mid ?? '').trim();
129
+ if (!mid) throw errors.empty(`No Bilibili user found for: ${s}`);
130
+ return mid;
131
+ }
132
+
133
+ /** Resolve a BV id, bilibili.com video URL, or b23.tv short link → a BV id. */
134
+ export function resolveBvid(input) {
135
+ const trimmed = String(input).trim();
136
+ if (/^BV[A-Za-z0-9]+$/i.test(trimmed)) return Promise.resolve(trimmed);
137
+ try {
138
+ const parsed = new URL(trimmed);
139
+ if (/(\.|^)bilibili\.com$/i.test(parsed.hostname)) {
140
+ const match = parsed.pathname.match(/\/(?:video|bangumi\/play)\/(BV[A-Za-z0-9]+)/i);
141
+ if (match) return Promise.resolve(match[1]);
142
+ }
143
+ } catch {
144
+ // Non-URL inputs fall through to b23.tv short-code resolution.
145
+ }
146
+ const shortCode = trimmed.replace(/^https?:\/\//, '').replace(/^(www\.)?b23\.tv\//, '');
147
+ if (!/^[A-Za-z0-9]+$/.test(shortCode)) {
148
+ return Promise.reject(errors.argument(`Cannot resolve BV ID from invalid input: ${trimmed}`));
149
+ }
150
+ const url = 'https://b23.tv/' + shortCode;
151
+ return new Promise((resolve, reject) => {
152
+ const req = https.get(url, (res) => {
153
+ const location = res.headers.location;
154
+ const match = location && location.match(/\/video\/(BV[A-Za-z0-9]+)/);
155
+ res.resume();
156
+ if (match) resolve(match[1]);
157
+ else reject(errors.argument(`Cannot resolve BV ID from short URL: ${trimmed}`));
158
+ });
159
+ req.on('error', reject);
160
+ req.setTimeout(4000, () => { req.destroy(); reject(errors.upstream(`Timeout resolving short URL: ${trimmed}`)); });
161
+ });
162
+ }
163
+
164
+ // ---------------------------------------------------------------------------
165
+ // Multi-part (分P) selection — used by video / download / subtitle / summary.
166
+ // ---------------------------------------------------------------------------
167
+
168
+ /** Parse a 1-based --page selector; '' / null → null (no drill-down). */
169
+ export function parsePageArg(value) {
170
+ if (value == null || value === '') return null;
171
+ if (typeof value === 'number') {
172
+ if (Number.isSafeInteger(value) && value >= 1) return value;
173
+ throw errors.argument(`page must be a positive integer, got: ${value}`);
174
+ }
175
+ if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) {
176
+ throw errors.argument(`page must be a positive integer, got: ${String(value)}`);
177
+ }
178
+ const n = Number(value);
179
+ if (!Number.isSafeInteger(n)) throw errors.argument(`page is too large: ${value}`);
180
+ return n;
181
+ }
182
+
183
+ function readApiPositiveInteger(value, label) {
184
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 1) return value;
185
+ if (typeof value === 'string' && /^[1-9]\d*$/.test(value)) {
186
+ const n = Number(value);
187
+ if (Number.isSafeInteger(n)) return n;
188
+ }
189
+ throw errors.upstream(`Bilibili view API returned a malformed ${label}`);
190
+ }
191
+
192
+ /** Pick the Nth (1-based) entry from view API data.pages[]. Fails closed on missing/duplicate/malformed. */
193
+ export function selectVideoPart(viewData, pageNum) {
194
+ const pages = Array.isArray(viewData?.pages) ? viewData.pages : null;
195
+ if (!pages || pages.length === 0) throw errors.upstream('Bilibili view API did not return pages[] for page selection');
196
+ const matches = [];
197
+ for (const entry of pages) {
198
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw errors.upstream('Bilibili view API returned a malformed pages[] entry');
199
+ if (readApiPositiveInteger(entry.page, 'page number') === pageNum) matches.push(entry);
200
+ }
201
+ if (matches.length > 1) throw errors.upstream(`Bilibili view API returned duplicate page entries for p=${pageNum}`);
202
+ const part = matches[0];
203
+ if (!part) {
204
+ const total = pages.length || viewData?.videos || 1;
205
+ throw errors.argument(`Page out of range: p=${pageNum} (this video has ${total} part(s))`);
206
+ }
207
+ readApiPositiveInteger(part.cid, `cid for p=${pageNum}`);
208
+ return part;
209
+ }
210
+
211
+ // ---------------------------------------------------------------------------
212
+ // Relation helpers — used by follow / unfollow.
213
+ // ---------------------------------------------------------------------------
214
+ const RELATION_VERIFY_TIMEOUT_MS = 5000;
215
+ const RELATION_VERIFY_POLL_MS = 500;
216
+
217
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
218
+
219
+ /** Extract a mid from a space.bilibili.com/<uid> URL, else ''. */
220
+ export function parseSpaceMidUrl(raw) {
221
+ const trimmed = String(raw ?? '').trim();
222
+ if (!trimmed) return '';
223
+ const candidate = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
224
+ let parsed;
225
+ try { parsed = new URL(candidate); } catch { return ''; }
226
+ if (parsed.hostname.toLowerCase() !== 'space.bilibili.com') return '';
227
+ const match = parsed.pathname.match(/^\/(\d+)\/?$/);
228
+ return match ? match[1] : '';
229
+ }
230
+
231
+ /** Current relation attribute toward a user (2=following, 6=mutual, 128=blocked, ...). */
232
+ export async function fetchRelationAttribute(tab, mid) {
233
+ const data = await biliGet(tab, `https://api.bilibili.com/x/relation?fid=${mid}`);
234
+ const attribute = data?.attribute;
235
+ if (typeof attribute !== 'number') throw errors.upstream('Bilibili relation query returned a malformed attribute');
236
+ return attribute;
237
+ }
238
+
239
+ /** Poll the relation until `predicate(attribute)` holds, or throw. */
240
+ export async function waitForRelation(tab, mid, predicate, expectedLabel) {
241
+ const deadline = Date.now() + RELATION_VERIFY_TIMEOUT_MS;
242
+ let lastAttribute;
243
+ while (Date.now() <= deadline) {
244
+ lastAttribute = await fetchRelationAttribute(tab, mid);
245
+ if (predicate(lastAttribute)) return lastAttribute;
246
+ await sleep(RELATION_VERIFY_POLL_MS);
247
+ }
248
+ throw errors.upstream(`Bilibili relation modify did not verify ${expectedLabel}; last attribute=${lastAttribute}`);
249
+ }
250
+
251
+ /** Strip HTML tags / entities from a search-result snippet. */
252
+ export function stripHtml(s) {
253
+ return String(s ?? '').replace(/<[^>]+>/g, '').replace(/&[a-z]+;/gi, ' ').trim();
254
+ }
@@ -0,0 +1,55 @@
1
+ import { defineAdapter, errors } from '@jackwener/browsermcp/adapter-sdk';
2
+ import { ensureOnBili, biliApi, biliPost, resolveBvid, resolveUid } from './_shared.js';
3
+
4
+ export default defineAdapter({
5
+ description: 'Post a comment or reply on a Bilibili video. Any @username in the message is resolved to a real mention. Accepts a BV id, URL, or b23.tv link.',
6
+ access: 'write',
7
+ domain: 'bilibili.com',
8
+ args: [
9
+ { name: 'bvid', type: 'string', required: true, help: 'BV id, video URL, or b23.tv short link' },
10
+ { name: 'message', type: 'string', required: true, help: 'Comment text; @username in it is turned into a real mention' },
11
+ { name: 'parent', type: 'int', help: 'Root rpid to reply under (omit for a top-level comment)' },
12
+ ],
13
+ async run({ tab, args }) {
14
+ await ensureOnBili(tab);
15
+ const message = String(args.message ?? '').trim();
16
+ if (!message) throw errors.argument('Comment message cannot be empty');
17
+ const parent = args.parent != null ? Number(args.parent) : null;
18
+ const bvid = await resolveBvid(args.bvid);
19
+
20
+ const viewData = await biliApi(tab, '/x/web-interface/view', { bvid });
21
+ const oid = viewData?.aid;
22
+ if (!oid) throw errors.upstream(`Cannot resolve aid for bvid: ${bvid}`);
23
+
24
+ // Resolve @username mentions → uids so they notify the mentioned user.
25
+ const atNameToMid = {};
26
+ for (const match of message.matchAll(/@([^\s@]+)/g)) {
27
+ const name = match[1];
28
+ if (name in atNameToMid) continue;
29
+ try {
30
+ const mid = Number(await resolveUid(tab, name));
31
+ if (Number.isInteger(mid) && mid > 0) atNameToMid[name] = mid;
32
+ } catch (err) {
33
+ if (err?.code !== 'empty_result') throw err;
34
+ // Unresolvable @name — leave it as plain text.
35
+ }
36
+ }
37
+
38
+ const params = {
39
+ oid, type: 1, message, plat: 1,
40
+ ...(parent != null ? { root: parent, parent } : {}),
41
+ ...(Object.keys(atNameToMid).length > 0 ? { at_name_to_mid: JSON.stringify(atNameToMid) } : {}),
42
+ };
43
+ const postData = await biliPost(tab, '/x/v2/reply/add', params);
44
+ const rpid = postData?.rpid;
45
+ if (!rpid) throw errors.upstream('Bilibili reply/add did not return an rpid');
46
+ return {
47
+ posted: true,
48
+ rpid: String(rpid),
49
+ bvid,
50
+ oid: String(oid),
51
+ message,
52
+ url: `https://www.bilibili.com/video/${bvid}#reply${rpid}`,
53
+ };
54
+ },
55
+ });
@@ -0,0 +1,47 @@
1
+ import { defineAdapter, errors } from '@jackwener/browsermcp/adapter-sdk';
2
+ import { ensureOnBili, biliApi, biliApiSigned, resolveBvid } from './_shared.js';
3
+
4
+ const MAX_LIMIT = 50;
5
+
6
+ function formatReplyRow(reply, index) {
7
+ const rpid = String(reply?.rpid ?? '').trim();
8
+ const ctime = Number(reply?.ctime);
9
+ return {
10
+ rank: index + 1,
11
+ rpid,
12
+ author: String(reply?.member?.uname ?? ''),
13
+ text: String(reply?.content?.message ?? '').replace(/\n/g, ' ').trim(),
14
+ likes: reply?.like ?? 0,
15
+ replies: reply?.rcount ?? 0,
16
+ time: Number.isFinite(ctime) ? new Date(ctime * 1000).toISOString() : '',
17
+ };
18
+ }
19
+
20
+ export default defineAdapter({
21
+ description: 'Comments on a Bilibili video. With parent set, fetches the replies nested under that comment instead of top-level comments.',
22
+ access: 'read',
23
+ domain: 'bilibili.com',
24
+ args: [
25
+ { name: 'bvid', type: 'string', required: true, help: 'BV id, video URL, or b23.tv short link' },
26
+ { name: 'parent', type: 'int', help: 'rpid of a comment — fetch replies under it instead of top-level comments' },
27
+ { name: 'limit', type: 'int', default: 20, help: 'How many comments to return (max 50)' },
28
+ ],
29
+ async run({ tab, args }) {
30
+ await ensureOnBili(tab);
31
+ const bvid = await resolveBvid(args.bvid);
32
+ const limit = Math.min(Math.max(1, Number(args.limit) || 20), MAX_LIMIT);
33
+ const parent = args.parent != null ? Number(args.parent) : null;
34
+
35
+ const viewData = await biliApi(tab, '/x/web-interface/view', { bvid });
36
+ const aid = viewData?.aid;
37
+ if (!aid) throw errors.upstream(`Cannot resolve aid for bvid: ${bvid}`);
38
+
39
+ const data = parent != null
40
+ ? await biliApi(tab, '/x/v2/reply/reply', { oid: aid, type: 1, root: parent, pn: 1, ps: limit })
41
+ : await biliApiSigned(tab, '/x/v2/reply/main', { oid: aid, type: 1, mode: 3, ps: limit });
42
+
43
+ const replies = Array.isArray(data?.replies) ? data.replies : [];
44
+ if (replies.length === 0) throw errors.empty(parent != null ? `No replies under comment ${parent}` : `No comments on ${bvid}`);
45
+ return replies.slice(0, limit).map(formatReplyRow);
46
+ },
47
+ });