Skip to main content
Glama
README.md
# cnki-mcp

[![CI](https://github.com/yhong91/cnki-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/yhong91/cnki-mcp/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/)

**English** | [简体中文](README.zh-CN.md)

A Model Context Protocol (MCP) server for **CNKI (China National Knowledge Infrastructure)** built on Playwright browser automation and native CNKI endpoints.

Beyond full literature search, professional search expressions, article details, citation networks, batch `GB/T 7714` / EndNote citation export, and full-text PDF downloads, `cnki-mcp` provides **exact journal navigation (`navi.cnki.net`), non-expiring permanent journal URLs (`permanent_url`), login-free official RSS 2.0 feeds (`rss_url`), batch OPML 2.0 export, indexing/impact-factor inspection, and single/multi-issue/full-year TOC traversal**. This eliminates the fuzzy-matching cross-journal pollution common in CNKI's `LY` source filter (e.g., distinguishing *教育研究* from *高等教育研究* or *比较教育研究*).

It also features an **adaptive three-stage authentication workflow** (silent campus IP auto-reauthentication -> on-demand off-campus CARSI institutional SSO popup with optional institution auto-selection -> dismissal cooldown), **automatic CAPTCHA popup recovery**, **`0600` `storage_state` persistence**, **dynamic real Chrome User-Agent alignment**, and a **`cnki_status` network/auth diagnostic tool**.

## Features (13 MCP Tools)

### Journal Navigation, Issue TOC & RSS / OPML Feeds

| Tool | Description |
| --- | --- |
| `cnki_journal_search` | Search journals on `navi.cnki.net` by title, ISSN, CN number, or sponsor; prioritizes exact matches and supports `exact=True` to prevent cross-journal pollution (returns `permanent_url` and `rss_url` when `baseid` is available). |
| `cnki_journal_detail` | Fetch journal metadata, non-expiring `permanent_url`, login-free official RSS 2.0 feed (`rss_url`), indexing badges (PKU Core / CSSCI / CSCD / AMI / WJCI / SCI / EI, etc.), composite/comprehensive impact factors, and all available years/issues. |
| `cnki_journal_toc` | Extract table of contents (TOC) by journal detail URL or exact title (latest/online-first, single issue, multi-issue batch, or full-year traversal) with optional original cover/TOC PDF download. |
| `cnki_journal_opml` | Resolve permanent homepages and official RSS 2.0 feeds for a list of journals and export a standard OPML 2.0 file ready for Folo, NetNewsWire, Reeder, or Inoreader. |

### Literature Search, Citations & Full-Text Retrieval

| Tool | Description |
| --- | --- |
| `cnki_search` | Search academic papers with natural-language modifiers (`作者:`, `关键词:`, `单位:`, `基金:`, `来源:`, `篇名:`, `摘要:`, year ranges) or structured filters, including `source` + `exact_source=True` exact journal filtering and `export_id` extraction. |
| `cnki_professional_search` | Run raw CNKI expert/professional query expressions (using unquoted integer years, e.g., `SU %= '人工智能' AND LY = '教育研究' AND YE BETWEEN (2020, 2025)`). |
| `cnki_syntax_guide` | Return the complete CNKI professional search syntax guide (field codes, operators, proximity operators, and examples) with zero browser overhead. |
| `cnki_get_article` | Fetch detailed paper metadata (non-expiring KCMS `permanent_url`, volume/issue/pages, `GB/T 7714` citation, plus Master/PhD thesis `advisor`, `degree`, `university`, and `major`); optionally includes citation networks. |
| `cnki_search_with_abstracts` | Batch-search and enrich papers: `mode="basic"` (default) uses CNKI's `GetExport` API for fast full abstracts, keywords, and `GB/T 7714` citations; `mode="full"` also extracts reference/citation networks. |
| `cnki_export_citations` | Batch-export `GB/T 7714` citations, EndNote records, and structured metadata from `export_ids` (fast, no detail-page visits) or article `urls`. |
| `cnki_get_citations` | Extract reference, citation, co-reference, and secondary reference/citation networks plus counts. |
| `cnki_download` | Download full-text PDFs (silent headless download on campus/campus-VPN; automatic CARSI SSO popup and resume off-campus). |

### Network & Authentication Diagnostics

| Tool | Description |
| --- | --- |
| `cnki_status` | Inspect CNKI's view of the current egress IP (`cnki_client_ip`), institutional authorization, and login state (avoids false off-campus checks caused by split-tunnel proxies). `probe=False` (default) reads local/in-memory state with zero network requests; `probe=True` safely tests campus IP authorization in an isolated incognito context without disturbing existing off-campus CARSI sessions. |

## Permanent Journal URLs, Official RSS 2.0 & OPML 2.0

- **Non-expiring `permanent_url`**: Constructed from CNKI's canonical journal identifier (`baseid`, e.g. `JYYJ`, `YWZG`) as `https://navi.cnki.net/knavi/journals/<BASEID>/detail?uniplatform=NZKPT`, avoiding expiring `?p=...` search links.
- **Login-free official RSS 2.0 (`rss_url`)**: `https://rss.cnki.net/knavi/rss/<BASEID>?pcode=CJFD,CCJD` returns standard RSS 2.0 XML directly without cookies or campus IP access.
- **One-shot OPML 2.0 export (`cnki_journal_opml`)**: Pass a list of journal titles or URLs to verify metadata and generate an OPML 2.0 bundle for **Folo**, **NetNewsWire**, **Reeder**, **Inoreader**, and any standard RSS reader.

## Installation

Requirements: Python `>= 3.11` and local Google Chrome (or Playwright's bundled Chromium).

```bash
# Clone and install development/runtime dependencies
git clone https://github.com/yhong91/cnki-mcp.git
cd cnki-mcp
uv sync

# If Google Chrome is not installed locally, install Playwright Chromium
uv run playwright install chromium
```

Install the global `cnki-mcp` CLI tool via `uv`:

```bash
# Install directly from GitHub
uv tool install git+https://github.com/yhong91/cnki-mcp

# Or install in editable mode from a local clone
uv tool install --editable .
```

## Adaptive Authentication & CLI Usage

### 1. Three-Stage Adaptive Auth (Campus Silent vs. Off-Campus CARSI)

1. **Cached / Campus Direct Pass-Through**: With a valid session or fresh campus IP authorization, searches, TOC downloads, and full-text PDF downloads run silently in headless mode with zero popups.
2. **Silent Headless IP Re-Authentication**: If a download hits a login gate (for example, when persisted `~/.cnki_state.json` still contains an expired `LID` or `Ecp_notFirstLogin` cookie), `cnki-mcp` first clears stale login cookies and silently triggers CNKI IP login in the background. On campus networks or split-tunneled campus VPNs, fresh institutional cookies are acquired within ~2 seconds with **zero popups**.
3. **Off-Campus CARSI Popup with Optional Institution Auto-Select**: Only when silent IP login confirms no campus IP authorization (and a desktop GUI is available with `CNKI_AUTO_AUTH=1`), a visible browser window opens `https://fsso.cnki.net/`. If `CNKI_CARSI_ORG` is configured (e.g. `北京大学`), it automatically jumps straight to your university's identity provider login page. After login, cookies and `localStorage` are hot-reloaded into the headless browser and the download resumes automatically. Closing the window activates a cooldown (`CNKI_AUTH_COOLDOWN`, default `120`s) so batch downloads do not spam repeated popups.

- **Automatic CAPTCHA Recovery**: Slider/puzzle/click-word CAPTCHAs or HTTP `403` risk-control redirects automatically open a visible browser window on desktops so you can complete verification once and resume seamlessly.
- **Session Persistence (`0600`)**: Full Playwright `storage_state` (cookies + `localStorage`) is saved with `0600` permissions to `~/.cnki_state.json` (with legacy sync to `~/.cnki_cookies.json`).
- **Headless Remote Servers**: On Linux servers without `DISPLAY` / `WAYLAND_DISPLAY` (or with `CNKI_AUTO_AUTH=0`), no GUI window is attempted; structured `login_required` / `captcha_required` responses are returned instead.

### 2. CLI Commands

```bash
# Print version
cnki-mcp --version

# Manually open CNKI CARSI institutional external login (https://fsso.cnki.net/)
cnki-mcp --auth --carsi

# Open default CNKI navigation page to complete CAPTCHA or manual login
cnki-mcp --auth

# Open a custom CNKI URL for verification/login
cnki-mcp --auth --url "https://kns.cnki.net/kns8s/search"

# Start MCP stdio server
cnki-mcp
```

## Environment Variables

| Variable | Default | Description |
| --- | --- | --- |
| `CNKI_HEADED` | `0` | Set to `1` / `true` to run Playwright in visible (headed) mode permanently |
| `CNKI_BROWSER_CHANNEL` | `chrome` | Preferred browser channel; falls back to Playwright Chromium if unavailable |
| `CNKI_STATE_FILE` | `~/.cnki_state.json` | Full `storage_state` (cookies + `localStorage`) file path (`0600` permissions; never commit) |
| `CNKI_COOKIE_FILE` | `~/.cnki_cookies.json` | Legacy cookie list file path (`0600` permissions; never commit) |
| `CNKI_AUTO_AUTH` | `1` | Enable automatic desktop popup on off-campus login or CAPTCHA (`0` / `false` disables) |
| `CNKI_AUTH_TIMEOUT` | `110000` | Single popup wait timeout in milliseconds |
| `CNKI_AUTH_COOLDOWN` | `120` | Cooldown in seconds after closing/cancelling a login popup (`0` disables) |
| `CNKI_CARSI_ORG` | *(empty)* | Optional university name on `fsso.cnki.net` to auto-select (e.g., `北京大学`) |
| `CNKI_DOWNLOAD_DIR` | `./downloads` | Directory for downloaded PDFs and TOC files (recommended to set an explicit path such as `~/Downloads/cnki`) |

## MCP Client Configuration

Compatible with Claude Desktop, Cursor, Claude Code, Windsurf, and any stdio MCP client.

### Option 1: Globally Installed via `uv tool install` (Recommended)

```json
{
  "mcpServers": {
    "cnki-mcp": {
      "command": "cnki-mcp",
      "env": {
        "CNKI_BROWSER_CHANNEL": "chrome",
        "CNKI_HEADED": "false",
        "CNKI_CARSI_ORG": "Your University Name",
        "CNKI_DOWNLOAD_DIR": "~/Downloads/cnki"
      }
    }
  }
}
```

### Option 2: Run Directly from a Local Source Clone

```json
{
  "mcpServers": {
    "cnki-mcp": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/cnki-mcp",
        "run",
        "cnki-mcp"
      ],
      "env": {
        "CNKI_DOWNLOAD_DIR": "~/Downloads/cnki"
      }
    }
  }
}
```

> **Tip**: If your MCP client or gateway supports a per-server tool call timeout, setting it to **`180` seconds** ensures off-campus CARSI QR sign-in and large thesis PDF downloads complete without premature timeouts.

## Project Architecture

```text
src/cnki_mcp/
├── __init__.py          # Package version
├── _utils.py            # Shared whitespace & Playwright page safety helpers
├── config.py            # BrowserConfig dataclass & environment variable parsing
├── session.py           # Storage state, 0600 cookie persistence, UA alignment & status parsing
├── browser.py           # CNKIBrowser lifecycle, stealth, CAPTCHA & adaptive IP/CARSI auth
├── query_builder.py     # Natural query parser & CNKI professional search expression builder
├── journal_parser.py    # Pure offline navi.cnki.net HTML, RSS/permanent URL & OPML parsers
├── journal.py           # Playwright journal search, detail, TOC traversal & OPML export
├── papers_parser.py     # Pure offline kns.cnki.net HTML, citation API & GetExport parsers
├── papers.py            # Playwright paper search, details, citations, export & PDF download
└── server.py            # MCP Server tool schemas, dispatcher & CLI entrypoint
```

## Development & Testing

```bash
uv sync --frozen --dev
uv run ruff check src/ tests/
uv run ruff format --check src/ tests/
uv run pytest -v -W error
```

## Acknowledgements

This project draws inspiration and CNKI endpoint/DOM parsing experience from the following open-source repositories:

- [weileyao2005/cnki-deepsearch](https://github.com/weileyao2005/cnki-deepsearch) — Inspiration for CNKI academic search, professional search expression building, and MCP tool architecture.
- [cookjohn/cnki-skills](https://github.com/cookjohn/cnki-skills) — Reference for `navi.cnki.net` journal navigation, indexing/TOC extraction, original TOC reader handling, and CNKI's `GetExport` citation export endpoint.
- [l0o0/jasminum](https://github.com/l0o0/jasminum) — Community insights on CNKI thesis metadata extraction, permanent KCMS links, and CNKI page structure quirks.

Also built with thanks to [Model Context Protocol Python SDK](https://github.com/modelcontextprotocol/python-sdk), [Playwright](https://playwright.dev/python/), and [BeautifulSoup4](https://www.crummy.com/software/BeautifulSoup/).

## Compliance & Disclaimer

- This project is intended strictly as a personal academic search, journal TOC tracking, and bibliography management helper relying on your own legitimate campus network, CARSI, or personal CNKI subscription.
- It **does not** contain any paywall bypass, access-control circumvention, or automated CAPTCHA-solving mechanism; whenever authentication or security verification is required, it is handed to the user in a visible browser window.
- Please comply with CNKI's Terms of Service and applicable laws, maintain reasonable request rates, and do not use this tool for large-scale commercial scraping or unauthorized redistribution.

## License

Released under the [MIT License](LICENSE).

TDQS

A3.6/5.0

Scored across 13 tools

Disambiguation3/5

Three overlapping search entry points exist (cnki_search, cnki_professional_search, cnki_search_with_abstracts), and the latter explicitly mirrors cnki_search's parameters, so an agent must reason carefully about which to call. Citation retrieval is also split between cnki_get_citations and cnki_get_article(include_citations=True), and cnki_journal_detail vs cnki_journal_opml both return permanent_url/rss_url. Descriptions do disambiguate each case, but the boundaries are not self-evident from names alone.

Naming Consistency4/5

All names are snake_case with a consistent cnki_ namespace prefix, and most follow a verb_noun pattern (get_article, download, export_citations, journal_search). A few deviate into noun_phrase style (syntax_guide, journal_toc, journal_opml, status) and the prefix ordering shifts between cnki_<verb>_<noun> and cnki_journal_<noun>. Minor deviations only; overall predictable.

Tool Count5/5

13 tools is well within the sweet spot and each maps to a concrete capability: search, article detail, citations, download, journal navigation/TOC/RSS, export, and auth status. No obviously redundant or filler tool given the breadth of the CNKI domain (articles, journals, subscription feeds, campus auth).

Completeness4/5

The surface covers the full research workflow: discovery (plain + professional search), enrichment (abstracts/citations), full-text download, journal-level TOC and RSS/OPML subscription, citation export, and auth diagnostics. Minor gaps remain around author/institution-centric lookup, saved-library operations, and batch full-text download, but these are workaroundable via the syntax search and export tools.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues