Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/AGENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,14 @@ Errors: `NO_VIDEO` (no `<video>` on the page), `TAB_HIDDEN` (the tab has never b

## 2. Extension ↔ MCP server (what the MCP uses)

Off by default. The user turns it on in 设置 → MCP → 允许 Agent 使用我的 B站和 YouTube 账号 (`mcpAccess`), the one switch: while it is on every method below is answered, reads and writes alike; there is no switch per kind of data and no code for one. While on, the extension's service worker keeps a WebSocket to `ws://127.0.0.1:47823/` (the MCP server is the listener). When the socket closes it reconnects after 5 s, then backs off to 60 s; it stops when the switch is turned off, and the server then answers every call with `NOT_CONNECTED`. The connection's state is stored as `mcpStatus` (`connected` / `disconnected` / `off`) for the settings page.
Off by default. The user turns it on in 设置 → MCP → 允许 Agent 使用我的 B站和 YouTube 账号 (`mcpAccess`), the one switch: while it is on every method below is answered, reads and writes alike; there is no switch per kind of data and no code for one. While on, the extension's service worker keeps a WebSocket to `ws://127.0.0.1:47823/` (the MCP server is the listener: one shared `moondigest-mcp --hub` process, see below). When the socket closes it reconnects after 5 s, then backs off to 60 s; it stops when the switch is turned off, and the server then answers every call with `NOT_CONNECTED`. The connection's state is stored as `mcpStatus` (`connected` / `disconnected` / `off`) for the settings page.

The switch used to be 允许 MCP 连接 with three switches under it (`mcpEnabled` with `mcpPersonalData`, `mcpWrites`, `mcpCollectionWrite`). The one switch has its own key, so the old connection switch never stands for reading and changing the account. On update (`background.js` `migrateMcpSwitches`) `mcpAccess` starts on only for someone who had all four on, and only while `mcpAccess` was never set; for everyone else it is off until they turn it on. The four old keys are removed, and an older version on another computer writing `mcpEnabled` again turns nothing on.

The server accepts a connection only when its `Origin` header starts with `chrome-extension://` (web pages can open WebSockets to localhost too). Any installed extension passes that check, so an extension the user installed could take the one connection and answer with made-up data; the server trusts the user's own extensions. When a second extension connects, the server keeps the first and closes the second with code 4001.

Every MCP client session runs its own `moondigest-mcp` over stdio; none of them listens. The first one starts a detached `moondigest-mcp --hub`, which holds the port and the extension's socket on `/`, and every session's process dials it on `/client` (refused with 401 when the request carries any `Origin`, so no web page can be a client; any other path is refused too). A session says `{ type: "hello", build }` and the hub answers `{ type: "welcome", build }`, `build` being `{ version, mtime }` of its `server.js`. The hub relays `{ id, method, params }` to the extension under its own ids, so two sessions' ids never collide, and routes each answer back unchanged; it makes `NOT_CONNECTED` and `TIMEOUT` itself. It exits 10 minutes after its last session leaves. A session whose build is strictly newer sends `{ type: "shutdown" }`: the hub frees the port at once, closes the sessions with no call in flight and tells the others `{ type: "stopping" }` (either way their next call dials the new hub), finishes the calls in flight, then exits, and the session starts its own hub. A session whose hub went away before answering gets `NOT_CONNECTED` saying the call may or may not have run; its next call starts a hub again.

Messages are JSON text frames.

Extension → server on open: `{ type: "hello", version, extensionVersion }`. The server counts the extension as connected only after `hello`.
Expand Down Expand Up @@ -138,11 +140,11 @@ Keepalive: the server sends `{ type: "ping" }` every 20 s and the extension answ
- `extension/agent-sync.js` (service worker, after `triage-bg.js` and `triage/fav-records.js`): §2's `sync` and its background job.
- `extension/triage/fav-records.js` (`MdgFavRecords`; loaded by the service worker and by `triage.html`): what the stored records become after a Bilibili write or a full read. `patchSnapshotNow` (a folder's cached list gains or loses videos, and the left trail follows), `movedNow` (videos moved to a folder outside the ticked ones go to 已出分拣范围), `dropRemovedNow` (back in a ticked folder: out of 已出分拣范围), `saveNow` (a full new list replaces the cached one), `patchDecisionsNow` (the 取消收藏 records), `refreshElsewhereNow`, `unfavRecord`, and `lock` (the Web Lock `mdg-triage-records`, so the page's and the worker's read-modify-writes run one at a time). The worker uses them as exported; the 分拣台 page takes its own set with `MdgFavRecords.using(set)`, whose writes go through the page's setter (it notes its own writes and tells the user when storage refuses). What is shared is the record update only. Each side still sequences "Bilibili request, then records" itself: the worker in `agent-writes.js` (`run`), the page in its own run machinery (`fav-writes.js`). And an open 分拣台 page follows another context's write to the open folder's cached list only by dropping the videos that left it; added ones show after its next read: it shows that folder as it last read it until its next read of it (the journal entry does reach it, as a toast and a U step).
- `extension/agent-covers.js` (service worker): §2's `covers`.
- `mcp/server.js`: the MCP server, `npm test` in `mcp/`.
- `mcp/server.js`: the MCP server, both the per-session stdio process (`createBridge`, `createMcpServer`) and the shared hub (`createHub`, `--hub`), `npm test` in `mcp/`.

## 4. Codes

`NOT_VIDEO_PAGE`, `TAB_HIDDEN`, `THROTTLED` (Bilibili 412 / YouTube 429: stop, do not retry soon), `NO_VIDEO`, `SEEK_TIMEOUT`, `AD_PLAYING`, `FRAME_BLOCKED`, `BAD_URL`, `NO_ACCESS` (MoonDigest has no access to that site, §5), `NOT_CONNECTED` (MCP server: no extension connected: the browser is closed, or 设置 → MCP's switch is off), `TIMEOUT` (no answer within the call's time, or the call waited too long behind earlier ones), `BAD_PARAMS` (a parameter is wrong, the error says which; nothing was asked or written), `HIDDEN_ITEMS` (`favWrite` `folder_delete`: Bilibili counts videos it does not list; nothing was deleted, `acceptLoss: true` deletes anyway), `NOT_LOGGED_IN` (not logged in to the site in that browser), `NETWORK` (the site did not answer), `OUTDATED_MCP` (the server asked for a method this extension dropped, `propose`: the MCP server is older than the extension and must be updated, by adding it again with the command 设置 → MCP shows; the other way round, an extension older than the server answers `Unknown method …` and the server adds that the extension must be updated), `PORT_IN_USE` (MCP server: another moondigest-mcp holds the port; it takes over when that one exits), `UNSUPPORTED_KIND` (the site has no such collection, or it is read only).
`NOT_VIDEO_PAGE`, `TAB_HIDDEN`, `THROTTLED` (Bilibili 412 / YouTube 429: stop, do not retry soon), `NO_VIDEO`, `SEEK_TIMEOUT`, `AD_PLAYING`, `FRAME_BLOCKED`, `BAD_URL`, `NO_ACCESS` (MoonDigest has no access to that site, §5), `NOT_CONNECTED` (MCP server: no extension connected: the browser is closed, or 设置 → MCP's switch is off; or the shared moondigest-mcp process stopped before answering, so the call may or may not have run), `TIMEOUT` (no answer within the call's time, or the call waited too long behind earlier ones), `BAD_PARAMS` (a parameter is wrong, the error says which; nothing was asked or written), `HIDDEN_ITEMS` (`favWrite` `folder_delete`: Bilibili counts videos it does not list; nothing was deleted, `acceptLoss: true` deletes anyway), `NOT_LOGGED_IN` (not logged in to the site in that browser), `NETWORK` (the site did not answer), `OUTDATED_MCP` (the server asked for a method this extension dropped, `propose`: the MCP server is older than the extension and must be updated, by adding it again with the command 设置 → MCP shows; the other way round, an extension older than the server answers `Unknown method …` and the server adds that the extension must be updated), `PORT_IN_USE` (MCP server: something that is not a moondigest-mcp hub holds the port, most likely a moondigest-mcp from before the shared hub; the next call after it exits picks the port up), `UNSUPPORTED_KIND` (the site has no such collection, or it is read only).

The port is fixed at 47823 on both sides. The server's `MOONDIGEST_MCP_PORT` is for tests only.

Expand Down
2 changes: 1 addition & 1 deletion docs/RELEASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

## MCP 服务(npm 包 `moondigest-mcp`)

- 改了 `mcp/` 就把 `mcp/package.json` 的 `version` 和 `mcp/server.js` 里 `new Server({ version })` 一起加一号,跟功能改动走同一个 PR。推标签后 `release.yml` 的 `npm` 任务发现这个版本号还不在 npm 上,就跑 `mcp/` 的测试并发布;版本号没变就什么都不发。
- 改了 `mcp/` 就把 `mcp/package.json` 的 `version` 和 `mcp/server.js` 里的 `VERSION` 一起加一号,跟功能改动走同一个 PR。推标签后 `release.yml` 的 `npm` 任务发现这个版本号还不在 npm 上,就跑 `mcp/` 的测试并发布;版本号没变就什么都不发。
- 不用令牌:npm 上这个包的 Settings → Trusted Publisher 里登记了 GitHub 仓库 `PathGao/MoonDigest` 和工作流文件 `release.yml`,npm 只认这个工作流发出的包。
- 第一次要手动发,因为 Trusted Publisher 要等包存在后才能配置:在 `mcp/` 里运行 `npm publish --access public`(要输两步验证码),再到 npm 的包设置页登记上面两项。在那之前 `npm` 任务只打印一行提示,不算失败。
- 3.8.0 起设置页、README 和 skill 给的安装命令都是 `npx -y moondigest-mcp@latest`,所以包要先于插件到用户手里:第一次先手动发 npm,再推标签。之后改了 `mcp/` 的版本,推标签时 npm 先发出去,商店审核要几天,顺序自然是对的。
Expand Down
28 changes: 14 additions & 14 deletions mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
一个可选的 MCP 服务器。装了它,Claude Code、Cursor、Codex 这类 MCP 客户端就能借你自己的浏览器和登录:搜索和读 B站、YouTube 视频(搜索结果、字幕、章节、热评、任意时刻的一帧画面),读你的 B站 收藏夹、关注、历史和 YouTube 的收藏,并且直接改 B站 收藏夹和分拣台的结果。每次修改都有记录,可以撤销。真正读和改的是浏览器里的 MoonDigest 扩展,这个服务器只负责转发。

```
MCP 客户端 ──stdio──> moondigest-mcp ──ws://127.0.0.1:47823──> 扩展的 service worker ──> B站 / YouTube
MCP 客户端 ──stdio──> moondigest-mcp ──> 共用的 moondigest-mcp 后台进程 ──ws://127.0.0.1:47823──> 扩展的 service worker ──> B站 / YouTube
```

搜索和读视频:
Expand Down Expand Up @@ -112,13 +112,13 @@ args = ["-y", "moondigest-mcp@latest"]
- 字幕、简介和评论是别人写的文字,里面可能夹着写给 AI 的指令。服务器给 Agent 的说明要求把这些文字当作数据,不照着做,只改你要求改的。这一条由 Agent 遵守,扩展检查不了;被诱导做出的修改同样有记录,可以撤销。
- B站 的收藏夹和稍后再看由扩展后台直接改,发的是分拣台自己用的那些请求。YouTube 的读和改都在扩展自己的后台标签页里、YouTube 网页自己的环境中发出,和 YouTube 网页自己发的请求一样,不碰你开着的标签页。

### 两个 MCP 客户端同时开着
### 多个 MCP 客户端同时开着

每个 MCP 客户端都会启动自己的 moondigest-mcp,但端口只有一个。做法是:
每个 MCP 客户端的每个会话都会启动自己的 moondigest-mcp,它们共用一个后台进程,所以同时开着的会话都能用这些工具:

- 先启动的那个占住端口,正常工作。
- 后启动的不会崩溃。它的工具调用返回 `PORT_IN_USE`,说明端口被另一个 moondigest-mcp 占着。
- 每次工具调用它都会再试一次占端口。先启动的那个退出后(它的客户端关掉时会跟着退出),下一次调用就会接管端口,扩展最多一分钟内连过来。
- 后台进程占着端口,连着扩展,把每个会话的调用转给扩展。它由第一个会话自己启动,不用手动开。
- 最后一个 MCP 客户端断开 10 分钟后,后台进程自己退出。下一个会话再启动它,扩展最多一分钟内连过来。
- 升级 moondigest-mcp 后,新版本的会话会换掉旧版本的后台进程:旧进程先答完手上的调用再退出。

没有扩展连着时,调用立刻返回 `NOT_CONNECTED`,提示打开「允许 Agent 使用我的 B站和 YouTube 账号」。扩展每分钟重连一次,所以开关刚打开、或服务刚启动时,等一分钟再调用。

Expand All @@ -127,7 +127,7 @@ args = ["-y", "moondigest-mcp@latest"]
### 排查

- `NOT_CONNECTED`:浏览器没开、没装 MoonDigest、或「设置 → MCP」的「允许 Agent 使用我的 B站和 YouTube 账号」没开。刚打开开关的话,等一分钟扩展连上再试。设置页的 MCP 一节写着现在是否已连接。
- `PORT_IN_USE`:另一个 MCP 客户端的 moondigest-mcp 占着端口,见上一节。也可以用 `lsof -nP -iTCP:47823 -sTCP:LISTEN` 看是谁。
- `PORT_IN_USE`:端口被别的程序占着,多半是还在跑的旧版 moondigest-mcp(共用后台进程之前的版本)。关掉那个 MCP 客户端会话,或结束那个进程(`lsof -nP -iTCP:47823 -sTCP:LISTEN` 能看到是谁),下一次调用就会接上。
- `THROTTLED`:B站或 YouTube 在限流。停下来,过一阵再试,不要连续重试。
- `TIMEOUT`:60 秒内没有回答。常见原因是页面加载太慢,或后台标签页被浏览器冻结。切到那个标签页看一眼再试。
- 字幕说要登录(`Subtitle note`):在这个浏览器里登录 B站。
Expand All @@ -149,7 +149,7 @@ cd mcp && npm test
An optional MCP server. It lets MCP clients such as Claude Code, Cursor and Codex work through your own browser and login: search and read Bilibili and YouTube videos (search results, transcript, chapters, hot comments, a frame at any time), read your Bilibili favorites, follows and history and your YouTube collections, and change your Bilibili favorites and 分拣台 results directly. Every change is recorded and can be undone. The MoonDigest extension in your browser does the reading and the changing. This server only relays.

```
MCP client ──stdio──> moondigest-mcp ──ws://127.0.0.1:47823──> extension service worker ──> Bilibili / YouTube
MCP client ──stdio──> moondigest-mcp ──> shared moondigest-mcp background process ──ws://127.0.0.1:47823──> extension service worker ──> Bilibili / YouTube
```

Search and read videos:
Expand Down Expand Up @@ -252,13 +252,13 @@ Then turn on 允许 Agent 使用我的 B站和 YouTube 账号 in MoonDigest's
- Transcripts, descriptions and comments are text other people wrote, and may contain instructions aimed at an AI. The server's instructions tell the AI tool to treat that text as data, not to act on it, and to change only what you asked for. The AI tool has to follow this; the extension cannot check it. A change it was talked into is recorded like any other and can be undone.
- Bilibili favorites and 稍后再看 are changed by the extension's background directly, with the requests the 分拣台 itself uses. YouTube reads and writes are sent from the extension's own background tab, in the YouTube page's own context, the same requests the YouTube page sends; your open tabs are not used.

### Two MCP clients at once
### Several MCP clients at once

Each MCP client starts its own moondigest-mcp, and there is only one port:
Each session of each MCP client starts its own moondigest-mcp. They all share one background process, so every open session can use the tools:

- The first one to start holds the port and works.
- The later one does not crash. Its tool calls return `PORT_IN_USE`, saying another moondigest-mcp holds the port.
- It retries the port on every tool call. Once the first one exits (it exits when its client closes), the next call takes the port over, and the extension reconnects within a minute.
- The background process holds the port, keeps the extension's connection and passes each session's calls to it. The first session starts it; you do not.
- It exits 10 minutes after the last MCP client disconnects. The next session starts it again, and the extension reconnects within a minute.
- After an upgrade, a session of the newer moondigest-mcp replaces an older background process: the old one answers the calls it has in hand, then exits.

With no extension connected, a call returns `NOT_CONNECTED` at once, asking for 允许 Agent 使用我的 B站和 YouTube 账号 to be turned on. The extension reconnects once a minute, so right after turning the switch on or starting the server, wait a minute and call again.

Expand All @@ -267,7 +267,7 @@ With no extension connected, a call returns `NOT_CONNECTED` at once, asking for
### Troubleshooting

- `NOT_CONNECTED`: the browser is not open, MoonDigest is not installed, or 允许 Agent 使用我的 B站和 YouTube 账号 in 设置 → MCP is off. Right after turning it on, wait a minute for the extension to connect. The MCP section of the settings page says whether it is connected.
- `PORT_IN_USE`: another MCP client's moondigest-mcp holds the port, see above. `lsof -nP -iTCP:47823 -sTCP:LISTEN` shows which process.
- `PORT_IN_USE`: another program holds the port, most likely an old moondigest-mcp (from before the shared background process) that some MCP client session is still running. Close that session or stop that process (`lsof -nP -iTCP:47823 -sTCP:LISTEN` shows it); the next call picks the port up.
- `THROTTLED`: Bilibili or YouTube is rate limiting. Stop and try later. Do not retry in a loop.
- `TIMEOUT`: no answer in 60 s. Usually the page loaded too slowly or the browser froze the background tab. Look at that tab and try again.
- The subtitle says log in (`Subtitle note`): log in to Bilibili in that browser.
Expand Down
4 changes: 2 additions & 2 deletions mcp/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion mcp/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "moondigest-mcp",
"version": "0.1.2",
"version": "0.2.0",
"description": "MCP server that lets AI agents read Bilibili and YouTube videos through the MoonDigest browser extension.",
"keywords": [
"mcp",
Expand Down
Loading
Loading