222wcnm Bilistalkermcp
БесплатноНе проверенTrack Bilibili creators and get the latest updates on videos, dynamics, and articles. Fetch user p…
Описание
Track Bilibili creators and get the latest updates on videos, dynamics, and articles. Fetch user p…
README
Python MCP PyPI version PyPI Total Downloads
Bilibili MCP Server for Specific User Analysis
BiliStalkerMCP is a Bilibili MCP server and command-line tool built on Model Context Protocol (MCP), designed for AI agents that need to analyze a specific Bilibili user or creator.
It is optimized for workflows that start from a target uid or username, then retrieve that user's profile, videos, dynamics, articles, subtitles, and followings with structured tools.
If you are searching for a Bilibili MCP server, a Bilibili Model Context Protocol server, or an MCP server for tracking and analyzing a specific Bilibili user, this repository is designed for that use case.
English | 中文说明
🚀 Quick Start
🤖 Method 1: Let your AI Agent configure it (Recommended)
Copy and send the following to Claude Code, Codex, or other AI agents:
Check the current client environment's MCP configuration standards, then configure 222wcnm/BiliStalkerMCP as an available MCP server. If needed, ask whether to configure it globally or per-project, and prompt me for required Bilibili environment variables (e.g. SESSDATA).
🛠️ Method 2: Manual Configuration (MCP Clients)
Configuration paths and syntax may vary across different clients.
1. Run the PyPI release directly
{
"mcpServers": {
"bilistalker": {
"command": "uvx",
"args": ["bili-stalker-mcp"],
"env": {
"SESSDATA": "required_sessdata",
"BILI_JCT": "optional_jct",
"BUVID3": "optional_buvid3"
}
}
}
}
2. Run from cloned source
git clone https://github.com/222wcnm/BiliStalkerMCP.git
cd BiliStalkerMCP
Then replace /path/to/BiliStalkerMCP below with your actual absolute path:
{
"mcpServers": {
"bilistalker": {
"command": "uv",
"args": ["run", "--directory", "/path/to/BiliStalkerMCP", "bili-stalker-mcp"],
"env": {
"SESSDATA": "required_sessdata",
"BILI_JCT": "optional_jct",
"BUVID3": "optional_buvid3"
}
}
}
}
Prefer
uv run --directory ...for faster local updates when PyPI release propagation is delayed. You can still useuvx bili-stalker-mcpfor quick one-off usage.
Auth: Provide
SESSDATAdirectly, or put it inBILI_COOKIE_FILE. Obtain it from Browser DevTools (F12) > Application > Cookies >.bilibili.com.
Method 3: Command-line queries
Native FastMCP CLI (recommended)
Use native FastMCP for terminal queries; the legacy CLI remains compatible.
Reuse an existing .mcp.json, or customize the absolute paths in the
connection template and save a local copy.
Configure credentials and proxies on the server subprocess explicitly.
The template's /absolute/path/to/... values are placeholders. Replace them with
absolute paths on the server machine; Windows paths such as C:/path/to/... are
valid too. JSON paths do not expand shell variables such as $HOME.
Enable UTF-8 for the current shell (PowerShell examples target PowerShell 7):
Bash / Linux:
export PYTHONUTF8=1
PowerShell:
$env:PYTHONUTF8 = "1"
These query commands work in either shell:
uv run fastmcp list .mcp.json
uv run fastmcp list .mcp.json --json
uv run fastmcp call .mcp.json search_users "keyword=中文 用户" limit=5 --json
Successful JSON responses contain structured_content; failures may be JSON with
is_error or plain text. Inspect the exit code and partial-result errors.
See native CLI guide for UTF-8,
.env loading, complex arguments, saved results and error recovery.
Native calls start a subprocess each time; this migration does not promise faster queries.
Legacy CLI
From this checkout, use the CLI to query any of the 12 tools without configuring an MCP client or starting a persistent server:
uv run bili-stalker-mcp --help
uv run bili-stalker-mcp doctor
uv run bili-stalker-mcp doctor --network
uv run bili-stalker-mcp tools
uv run bili-stalker-mcp tools --schema
uv run bili-stalker-mcp tools get_user_snapshot --pretty
uv run bili-stalker-mcp call search_users --args '{"keyword":"username","limit":5}'
uv run bili-stalker-mcp call get_user_snapshot --args '{"user_id_or_username":"12345","video_limit":5,"dynamic_limit":5,"article_limit":0}' --pretty
uv run bili-stalker-mcp call get_video_detail --args '{"bvid":"BV1xx411c7mD","fetch_subtitles":true,"subtitle_max_chars":12000}'
uv run bili-stalker-mcp call get_video_detail --args '{"bvid":"https://www.bilibili.com/video/BV16cj96FEmw?p=2","fetch_subtitles":true}'
uv run bili-stalker-mcp call get_video_detail --args '{"bvid":"BV1xx411c7mD","fetch_subtitles":true,"subtitle_scope":"all","subtitle_mode":"full"}'
tools lists names and descriptions; tools --schema returns every tool's input
schema, including required arguments, defaults, and limits, in one reusable catalog.
tools TOOL keeps the full MCP schema; add --schema to omit output schemas.
call TOOL accepts the same
names and JSON arguments as the MCP tools. IDs declared as strings in the schema
must remain quoted, including numeric UIDs and long article/dynamic IDs.
doctor prints JSON diagnostics for credential sources, refresh configuration,
proxy settings, and dependency versions. By default it does not use the network,
change credential files, or print credential values. doctor --network adds a TCP
connectivity check; it does not verify login or an API response. Proxy fields
tcp_reachable and expected_route report the probe and expected proxy/direct
fallback route. The server probes the configured proxy on its first runtime use,
then reuses that routing decision until the process restarts.
For larger arguments or to avoid shell quoting issues, read a UTF-8 JSON file or pipe a JSON object through stdin:
uv run bili-stalker-mcp call get_user_snapshot --args-file args.json --pretty
Bash / Linux:
printf '%s\n' '{"user_id_or_username":"12345","limit":5}' | uv run bili-stalker-mcp call get_user_videos --args-file -
PowerShell:
@{ user_id_or_username = "12345"; limit = 5 } | ConvertTo-Json -Compress | uv run bili-stalker-mcp call get_user_videos --args-file -
Set the environment variables below in the calling shell. Replace this example with the credential file path on the machine running the server:
Bash / Linux:
export BILI_COOKIE_FILE="$HOME/.config/bili-stalker/bili-cookie.txt"
PowerShell:
$env:BILI_COOKIE_FILE = "$HOME/.config/bili-stalker/bili-cookie.txt"
An MCP client's env configuration is not automatically inherited by a separate
terminal. The CLI uses the same credential, refresh, proxy, and rate-limit behavior
as MCP. Help, version, and tool discovery do not require login credentials.
If the checkout already has a .env file, load it explicitly for the command;
neither the CLI nor a plain uv run automatically loads it:
uv run --env-file .env bili-stalker-mcp call get_user_info --args '{"user_id_or_username":"12345"}'
Successful queries write one UTF-8 JSON value to stdout; logs and errors go to
stderr. Redirect stdout to save a result. Exit codes are 0 for success, 1 for
query/configuration failures (including an unhealthy doctor report), 2 for
invalid commands or arguments, and 130 for interruption. Query and argument
failures end with a JSON error object on stderr; risk-control errors
retain code and retry_after. A snapshot can succeed with incomplete
sections: inspect its errors field before interpreting it.
Unknown fields are rejected. Argument errors include valid_fields,
required_fields, and did_you_mean when a correction is available; common names
such as uid are hints, not accepted aliases. Calls default to a 25-second total
budget. CLI timing starts after command parsing and includes dependency loading
and argument reading; native MCP timing starts in the tool body. Exhaustion returns
reason="tool_timeout". If video metadata is already available, it can be returned
with a subtitle error instead; these timeout results are not cached. Adjust
BILI_TOOL_TIMEOUT_SECONDS and leave headroom in the caller's timeout. The budget
uses cooperative async cancellation and cannot interrupt synchronous initialization.
Connections and result caches are process-local; use persistent MCP for repeated queries.
Concurrent callers share fetches but keep independent time budgets. Unfinished
cache work is cancelled when its last waiter leaves.
uv run python -m bili_stalker_mcp ... accepts the same arguments. With an
installed package, use bili-stalker-mcp ... directly. Running without a subcommand
still starts the MCP stdio server; bili-stalker-mcp serve makes that explicit.
Environment Variables
| Key | Req | Description |
|---|---|---|
SESSDATA |
Conditional | Bilibili session token; required unless BILI_COOKIE_FILE provides it. |
BILI_JCT |
No | CSRF protection token. |
BUVID3 |
No | Hardware fingerprint (reduces rate-limiting risk). |
BILI_COOKIE_FILE |
No | Path to a plain Cookie file. |
BILI_REFRESH_TOKEN_FILE |
No | Path to the separate refresh-token file; never set the token through an environment variable. |
BILI_ENABLE_COOKIE_REFRESH |
No | true enables safe automatic refresh; default: false. |
BILI_COOKIE_REFRESH_CHECK_INTERVAL_SECONDS |
No | Refresh-check interval; default: 21600, minimum: 60. |
BILI_PROXY |
No | Route all upstream requests (bilibili_api and the built-in HTTP clients) through this proxy. Recommended when the system proxy is not picked up automatically or DNS resolution for Bilibili hosts is unstable. If the proxy is unreachable on first runtime use, the server falls back to direct connections and logs a warning. The routing decision lasts until the process restarts; tool discovery does not probe the proxy. |
BILI_TOOL_TIMEOUT_SECONDS |
No | Total seconds per tool call, including retries and waits; default: 25. Must be finite and positive. |
BILI_SHORT_LINK_TIMEOUT_SECONDS |
No | Total seconds for short-link resolution; default: 5, also bounded by the remaining tool budget. Must be finite and positive. Successful resolutions are cached for 300 seconds; at most 5 requests are made, stopping as soon as a video destination is known. |
BILI_REQUEST_JITTER_MODE |
No | Upstream jitter behavior: adaptive (default; sleeps only without a configured login or after recent 412/429/403), always, never. |
BILI_REQUEST_JITTER_MIN_MS / BILI_REQUEST_JITTER_MAX_MS |
No | Jitter sleep range; default: 200–1200. |
BILI_REQUEST_JITTER_BUDGET_MS |
No | Total jitter sleep allowed per tool call; default: 500. |
BILI_RISK_PRESSURE_WINDOW_SECONDS |
No | How long a 412/429/403 keeps adaptive jitter engaged; default: 300. |
BILI_LOG_LEVEL |
No | DEBUG, INFO (Default), WARNING. |
BILI_TIMEZONE |
No | Output time zone for formatted timestamps (default: Asia/Shanghai). |
Optional Safe Cookie Refresh
Automatic refresh is disabled by default. Enable it only when the Cookie file and
refresh-token file are existing, readable, writable regular files. The Cookie file
may contain only ordinary Cookie values (SESSDATA, bili_jct, buvid3,
buvid4, and DedeUserID); the refresh token belongs only in its own file.
{
"BILI_COOKIE_FILE": "/secure/bilibili-cookie.txt",
"BILI_REFRESH_TOKEN_FILE": "/secure/bilibili-refresh-token.txt",
"BILI_ENABLE_COOKIE_REFRESH": "true",
"BILI_COOKIE_REFRESH_CHECK_INTERVAL_SECONDS": "21600"
}
When refresh is enabled, do not set SESSDATA, BILI_JCT, or DEDEUSERID in
the environment: those rotating values must come from the Cookie file so a restart
cannot reload stale credentials. BUVID3 and BUVID4 may still be provided through
the environment. Refresh checks are rate-limited, and concurrent MCP calls or server
processes sharing these files use one refresh lock. Pending confirmation is recovered
before another refresh. The .bili-cookie-refresh.lock sidecar may remain on disk
between runs.
For a quicker initial setup, copy the complete Cookie header value from a Bilibili
browser request and ac_time_value from Local Storage, then run:
The path below is under the current user's home directory and works in Bash and PowerShell. You can choose another directory outside the checkout.
uv run bili-stalker-cookie-setup --directory "$HOME/.config/bili-stalker"
For a PyPI-only invocation without cloning this repository:
uvx --from bili-stalker-mcp bili-stalker-cookie-setup --directory "$HOME/.config/bili-stalker"
The script hides both pasted values, refuses directories inside the repository and
existing credential files, and prints only a non-secret MCP env block. Do not
paste an entire cURL command: paste only the value after its cookie: header.
Local Verification
All verification commands use mocks and do not require Bilibili credentials:
uv run pytest -q tests/test_credentials.py tests/test_cookie_refresh.py tests/test_tool_contract.py
uv run pytest -q
uv run black --check bili_stalker_mcp tests scripts
uv run isort --check-only bili_stalker_mcp tests scripts
uv run flake8 bili_stalker_mcp tests scripts
uv run mypy bili_stalker_mcp
Available Tools
| Tool | Capability | Parameters |
|---|---|---|
search_users |
Lightweight user candidates with numeric UIDs | keyword, limit |
get_user_snapshot |
One-call overview: profile + recent videos/dynamics/articles fetched concurrently | user_id_or_username, video_limit, dynamic_limit, article_limit (0 skips a section) |
get_user_info |
Rich profile: level, official title, VIP, live room, ban status, following/follower, total video views/article views/likes (needs bili_jct) |
user_id_or_username |
get_user_videos |
Lightweight video list | user_id_or_username, page, limit |
search_user_videos |
Keyword search in one user's video list | user_id_or_username, keyword, page, limit |
get_video_detail |
Full video detail + optional subtitles | bvid, fetch_subtitles (default: false), subtitle_scope (single/all, default: single), subtitle_page, subtitle_cid, subtitle_mode (smart/full/minimal), subtitle_lang (default: auto), subtitle_max_chars |
get_user_dynamics |
Structured dynamics with image metadata and cursor pagination | user_id_or_username, cursor, limit, dynamic_type |
get_user_articles |
Lightweight article list | user_id_or_username, page, limit |
get_article_content |
Full article markdown content | article_id |
get_user_followings |
Subscription list analysis | user_id_or_username, page, limit |
get_content_comments |
Comments for a video, article, or dynamic (including images and note metadata) | content_type, content_id, cursor, limit, sort |
get_content_comment_replies |
Full sub-replies for a video, article, or dynamic comment | content_type, content_id, root_rpid, page, limit |
When starting from a username, call search_users once and reuse the returned numeric
UID for subsequent tools. Implicit username resolution accepts exact matches only; it
does not silently select the first similar search result.
Comment pictures contain the original image URLs. Regular long comments retain the
full text returned by Bilibili. Note-style comments may contain only a preview; use
the returned note.cvid with get_article_content to retrieve the full note.
For video comments, pass content_type="video" and a BVID, AV number, or video URL
as content_id. Use a top-level comment's rpid as root_rpid when fetching its
complete reply thread.
Dynamic Filtering (dynamic_type)
ALL(default): Text, Draw, Reposts, and Video dynamics.ALL_RAW: Unfiltered (additionally includes Articles and unknown types).VIDEO,ARTICLE,DRAW,TEXT: Specific category filtering.REVIEW: Recognized five-slot rating cards only. Each result exposesreview.rating(filled stars, 0-5),review.title,review.text, cover and jump URLs, plus the source score description when available. This filter does not independently classify whether the rated title is an anime.
Each dynamic item includes an images list. Every image contains url, width,
and height; invalid URLs are omitted, and unavailable dimensions are null.
image_count always equals the number of returned images. Reposts expose the same
fields under origin.images and origin.image_count. Non-image dynamics return
an empty images list.
Pagination: Responses include next_cursor. Pass this to subsequent requests for seamless scrolling.
Subtitle Modes (get_video_detail)
Page scope is independent of language/track mode. The default subtitle_scope="single"
queries only P1 in both smart and full. A full URL with p=2 selects P2;
alternatively pass subtitle_page=2 or a subtitle_cid belonging to this video.
Page/CID must be positive integers, and the two explicit selectors are mutually
exclusive. Conflicting URL/explicit selections, missing pages, and foreign CIDs
return invalid_subtitle_selection without falling back to another page.
For all pages, explicitly set subtitle_scope="all" with a BVID or URL without p.
It cannot be combined with page/CID selectors or URL p. All scope still scans
every page's subtitle metadata; single scope queries only the selected page.
Default behavior change: callers relying on the previous all-page scan must add subtitle_scope="all".
smart(default whenfetch_subtitles=true): download one best-matched track within the selected scope.full: download every language track within the selected scope (higher cost).minimal: skip subtitle metadata and subtitle text fetching.
In smart mode, subtitle_lang can request a language (for example en-US);
auto uses built-in priority fallback.
subtitle_max_chars caps returned subtitle text size to avoid token explosion.
Subtitle text is returned once via full_text; tracks carry metadata only
(text is always empty). In full mode with multiple tracks, each segment in
full_text is prefixed with a [language · part] label.
Video detail includes owner: {mid, name, face} (or null), duration (upstream
total seconds across all parts), pic, tname, videos, and ctime (Unix
seconds). Missing metadata is null; pages[] keeps cid/page/part/duration
with each part's duration in seconds. mid and uid both identify a Bilibili
user. An empty tags array can also mean the detail source omitted tags.
selected_language is set only in smart mode; full mode returns null
and lists languages in tracks[].lan. truncated=true means the character
budget cut or dropped subtitle text. A track can remain in tracks when its
download fails; check errors and full_text. Subtitle text has no timecodes.
subtitles.scope contains mode, target_page, total_pages, returned_pages,
and summary, distinguishing the selected scope from pages actually represented
in the returned text and stating how many pages have no returned text.
returned_pages means at least one text character was returned for that page;
it does not guarantee completeness, so check errors and truncated.
Video pages[] always keeps the complete list. With subtitles disabled, scope is
null and selectors do not apply. minimal validates the selected range but
returns no text pages and makes no subtitle API calls.
Bundled Skill
The repository ships a ready-to-use AI agent skill in skills/bili-content-analysis/:
skills/bili-content-analysis/
├── SKILL.md # Workflow & output contract
└── references/
├── cli.md # CLI discovery, queries, and error handling
└── analysis-style.md # Detailed writing style rules
What It Does
Guides compatible AI agents (Gemini, Claude, etc.) through a structured 6-step workflow for deep Bilibili content analysis using MCP tools or the CLI:
- Clarify target and scope (uid / bvid / keyword).
- Collect evidence — lightweight lists first, heavy detail only for high-value items.
- Reconstruct source structure before interpreting (timeline, chapters, speakers).
- Analyze — facts, logic chain, assumptions, themes, and shifts.
- Retain anchors — uid, bvid, article_id, timestamps, key source snippets.
- Handle failures — state blockers explicitly, stop speculation.
Usage
Copy the bili-content-analysis folder into your project's skill directory:
<project>/.agent/skills/bili-content-analysis/
The agent will automatically activate the skill when user requests involve Bilibili creator tracking, transcript interpretation, timeline reconstruction, or content analysis.
Development
# Setup
git clone https://github.com/222wcnm/BiliStalkerMCP.git
cd BiliStalkerMCP
uv sync --dev
# Test
uv run pytest -q
# Integration & Performance (Requires Auth)
uv run python scripts/integration_suite.py -u <UID>
uv run python scripts/perf_baseline.py -u <UID> --tools dynamics -n 3
Release (Maintainers)
Credentials: The release script uses
UV_PUBLISH_TOKENwhen set; otherwise it reads the matching[pypi]or[testpypi]token from~/.pypirc. Twine is invoked transiently throughuvxonly for package metadata validation and is not a project dependency.
The release script requires PowerShell 7 (pwsh) on Windows or Linux:
# Build + test + package metadata validation (no upload)
pwsh -File ./scripts/pypi_release.ps1
# Upload to TestPyPI
pwsh -File ./scripts/pypi_release.ps1 -TestPyPI -Upload
# Upload to PyPI
pwsh -File ./scripts/pypi_release.ps1 -Upload
Docker
Runs via stdio transport. No ports exposed.
Set SESSDATA in the calling shell first; -e SESSDATA passes it to the
container, and -i keeps stdin open for stdio. Credential paths must refer to
paths inside the container; a loopback proxy there does not address the host.
docker build -t bilistalker-mcp .
docker run --rm -i -e SESSDATA bilistalker-mcp
Troubleshooting
- 412 Precondition Failed: Bilibili anti-crawling system triggered. Refresh
SESSDATAor provideBUVID3. - Cloud IPs: Highly susceptible to blocking; local execution is recommended.
- Long ~20s stalls or DNS timeouts on upstream calls: configure
BILI_PROXY.bilibili_api's curl_cffi client ignores system and environment proxies unless an explicit proxy is set.
Upstream Dependency Note
bilibili-api-python is pinned to ==17.4.2. Its upstream repository has been
permanently shut down following a legal notice from Bilibili, so no further
maintenance or fixes can be expected from that project. Additionally, the
package is licensed GPL-3.0-or-later, which means its source cannot be
vendored or forked into this MIT-licensed repository.
The mitigation path is incremental migration of the remaining SDK-backed
endpoints (user info, video lists, subtitles in video details, dynamics, articles)
onto this project's own raw HTTP stack (SharedRawHttpClient), which already
serves comments, followings, relation stats, and video details without subtitles
independently of the SDK. The pin
should be kept exact so installs never pick up an unknown future version.
License
MIT
Disclaimer: For personal research and learning only. Bulk profiling, harassment, or commercial surveillance is prohibited.
This project is built and maintained with the help of AI.
Установка 222wcnm Bilistalkermcp
У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.
▸ github.com/222wcnm/BiliStalkerMCPFAQ
222wcnm Bilistalkermcp MCP бесплатный?
Да, 222wcnm Bilistalkermcp MCP бесплатный — установка в пару кликов через Unyly без оплаты.
Нужен ли API-ключ для 222wcnm Bilistalkermcp?
Нет, 222wcnm Bilistalkermcp работает без API-ключей и переменных окружения.
222wcnm Bilistalkermcp — hosted или self-hosted?
Доступен hosted-вариант: Unyly запускает сервер в облаке, локальная установка не обязательна.
Как установить 222wcnm Bilistalkermcp в Claude Desktop, Claude Code или Cursor?
Открой 222wcnm Bilistalkermcp на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.
Похожие MCP
GitHub
PRs, issues, code search, CI status
автор: GitHubFilesystem
Secure file operations with configurable access controls.
Memory
Knowledge graph-based persistent memory system.
Template MCP Server
A CLI tool to create a new Model Context Protocol server project with TypeScript support, dual transport options, and an extensible structure
автор: mcpdotdirectServer Sequential Thinking
MCP server for sequential thinking and problem solving
автор: GitHub ActionsUnyly Deploy
Deploy sites and MCP servers to Unyly straight from your AI agent
автор: UnylyAmap Maps Mcp Server
MCP server for using the AMap Maps API
автор: duxiaohuiPayMCP
Lightweight payments layer for MCP servers: turn tools into paid endpoints with a two-line decorator. [PyPI](https://pypi.org/project/paymcp/) · [npm](https://w
автор: blustAIServer For Power BI
Enables exploring Microsoft Fabric / Power BI workspaces and semantic models, and executing ad-hoc DAX queries.
автор: Mitsubishi-FusoGpt Image 2 Mcp
RunAPI GPT Image 2 MCP server for image generation: create tasks, poll results, and check pricing across 1 model from Claude Code, Codex, Cursor, and VS Code.
автор: runapi-aiCompare 222wcnm Bilistalkermcp with
Не уверен что выбрать?
Найди свой стек за 60 секунд
Автор?
Embed-бейдж для README
Похожее
Все в категории development
