Metadata-Version: 2.4
Name: zotero-mcp-local
Version: 0.1.4
Summary: MCP Server for accessing and analyzing your local Zotero library with AI agents
License: MIT
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: mcp>=1.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pypdf>=4.0.0
Description-Content-Type: text/markdown

# Zotero MCP

<!-- mcp-name: io.github.piiinpiiins/zotero-mcp-local -->

## English

A [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that connects AI agents (Claude, etc.) to your local **Zotero** library. Search papers, read PDFs, find related work — all through natural language.

### Features

#### Zotero Local Tools
- **`search_items(query)`** — Search by title or author
- **`get_item_details(item_key)`** — Get full metadata (abstract, authors, DOI, etc.)
- **`find_related_papers(item_key, limit)`** — Find related papers using 5-dimensional composite similarity (shared collections 30%, tags 25%, fulltext word overlap 25%, authors 10%, venue 10%)
- **`list_collections(parent_collection_key)`** — Browse collection (folder) hierarchy — call with no arguments for top-level, or with a key for sub-collections
- **`get_collection_items(collection_key)`** — List all items in a specific collection
- **`get_pdf_text(item_key, max_pages)`** — Extract text from PDF attachments

#### Research Analysis Tools (Connected Papers + Gap Finder)
- **`search_connected_papers(query, doi, item_key, limit)`** — Find related papers using bibliographic coupling (the same algorithm as connectedpapers.com). Provide a free-text query, a DOI, or a Zotero item key. Uses Semantic Scholar by default; set `CONNECTED_PAPERS_API_KEY` to use the official Connected Papers API.
- **`find_research_gaps(item_keys, topic)`** — Analyze a set of papers' PDFs to extract stated limitations, suggested future work, and methodological gaps. Synthesizes recurring themes across all papers. `item_keys` is comma-separated.
- **`find_key_passages(item_keys, query, top_n)`** — Search across multiple papers' PDFs for the paragraphs most relevant to your query (TF-IDF ranked). Returns passage text, paper title, Zotero key, and page number. Useful for finding evidence to support an argument.

#### Resources
- `zotero://library/info` — Library statistics
- `zotero://library/items` — Recent 50 items
- `zotero://items/{key}` — Item details by key

### Installation

#### Prerequisites

- **Zotero 7** (installed, default database path `~/Zotero/zotero.sqlite`) — officially supported; compatibility with Zotero 5 and 6 is untested
- **uv** — Python package manager:

  **Mac/Linux:**
  ```bash
  curl -LsSf https://astral.sh/uv/install.sh | sh
  ```
  **Windows (PowerShell):**
  ```powershell
  powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
  ```

  > After installing, **restart your terminal** and verify with `uv --version`.
  >
  > If the installation was successful, it will display the version number, e.g.:
  > ```
  > uv 0.6.6 (Homebrew 2025-03-04)
  > ```
  > If you see `command not found`, it means `uv` was not added to your PATH correctly. Check your shell config file (`~/.zshrc` or `~/.bashrc`) to ensure the uv path is included.

#### Configure Claude Desktop

Open Claude Desktop, go to **Settings → Developer → Edit Config**, and paste the following into `claude_desktop_config.json`:

```json
{
  "preferences": {
    "coworkScheduledTasksEnabled": true,
    "ccdScheduledTasksEnabled": true,
    "sidebarMode": "chat",
    "coworkWebSearchEnabled": true
  },
  "mcpServers": {
    "zotero": {
      "command": "uvx",
      "args": ["zotero-mcp-local"]
    }
  }
}
```

Save the file and **restart Claude Desktop**. Go to **Settings → Developer**, you should see the Zotero MCP server with a **"running"** status:

![Zotero MCP running](docs/claude_desktop_running.png)

### Usage

Once configured, just ask Claude naturally:

- "Search my Zotero library for papers about reminiscence therapy"
- "Show me the details of paper ABCD1234"
- "Find papers related to ABCD1234 in my library"
- "Extract the text from the PDF of paper XYZ789"
- "Show me all my Zotero collections"
- "What papers are in the 'Background / trend' folder?"

**Research analysis workflow:**

```
1. search_items("your topic")                         → find paper keys in Zotero
2. search_connected_papers(item_key="ABCD1234")       → expand with related papers from Semantic Scholar
3. find_research_gaps(item_keys="K1,K2,K3")          → surface limitations & future work
4. find_key_passages(item_keys="K1,K2,K3", query="your argument") → find supporting paragraphs
```

- "Find papers related to 'participatory design elderly' using Connected Papers"
- "Analyze the research gaps in papers KEY1, KEY2, KEY3, focusing on older adults"
- "Find paragraphs about 'social isolation intervention design' across these papers: KEY1, KEY2"

### How It Works

- **Database Access:** Reads your local Zotero SQLite database via a temporary copy (read-only, never modifies your data).
- **Related Papers Algorithm:** Computes similarity using 5 weighted dimensions — shared collections, tags, fulltext word overlap (IDF-filtered), shared authors, and publication venue.
### Using on Another Mac

If you want to use zotero-mcp-local on another Mac (without Claude Desktop or Claude Code), you need to copy your Zotero data:

#### Files to Copy

| File | Est. Size | Required | Purpose |
|------|-----------|----------|---------|
| `zotero.sqlite` | Tens of MB | **Yes** | All metadata queries |
| `storage/` folder | Possibly several GB | For PDF features | PDF text extraction |
| MCP server | Just install | **Yes** | Provides MCP tool interface |

- **`~/Zotero/zotero.sqlite`** — The core database. All metadata (titles, authors, abstracts, tags, collections, dates) is stored here.
- **`~/Zotero/storage/`** — PDF files live here. Without it, search and metadata queries still work, but `get_pdf_text` will fail.

#### Setup Steps

```bash
# 1. Copy Zotero data (assuming default path ~/Zotero/)
scp ~/Zotero/zotero.sqlite user@other-mac:~/Zotero/
scp -r ~/Zotero/storage/ user@other-mac:~/Zotero/storage/

# 2. Install MCP server on the other Mac
pip install zotero-mcp-local

# 3. Set env var if database is not at default path
export ZOTERO_DB_PATH="/path/to/zotero.sqlite"

# 4. Start MCP server
uvx zotero-mcp-local
```

The system is fully local — no internet or Zotero account sync required. As long as you have the `zotero.sqlite` file, you can query your entire library.

### Installing with Claude Code (VS Code Extension)

If you are using Claude Code inside VS Code (rather than Claude Desktop), follow these steps to install from source.

#### Compatible Environments

| OS | Status |
|----|--------|
| macOS 13+ (Sonoma / Sequoia) | Fully tested |
| Linux (Ubuntu 22.04+) | Should work; `launchctl` step not needed (use `~/.bashrc` or `~/.zshenv` instead) |
| Windows 11 | Should work with uv; set env vars via System Properties → Environment Variables |

#### Prerequisites

| Tool | Purpose | Install |
|------|---------|---------|
| [Zotero](https://www.zotero.org/) | Source of your library database | Download from zotero.org |
| [uv](https://docs.astral.sh/uv/) | Python package manager | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
| [VS Code](https://code.visualstudio.com/) + Claude Code extension | AI agent host | Install from VS Code marketplace |
| [Git](https://git-scm.com/) | Clone the repo | Usually pre-installed on Mac/Linux |

#### Installation Steps

**Step 1 — Clone the repository**

```bash
git clone https://github.com/piiinpiiins/Zotero-MCP.git
cd Zotero-MCP
```

**Step 2 — Create the MCP config file**

Create `.mcp.json` in the project root (this file is in `.gitignore` and will not be committed):

```json
{
  "mcpServers": {
    "zotero": {
      "command": "uv",
      "args": [
        "--directory", "/absolute/path/to/Zotero-MCP",
        "run", "python", "-m", "src.zotero_mcp.server"
      ],
      "env": {
        "SEMANTIC_SCHOLAR_API_KEY": "YOUR_KEY_HERE"
      }
    }
  }
}
```

Replace `/absolute/path/to/Zotero-MCP` with the actual path where you cloned the repo.

**Step 3 — Get a Semantic Scholar API key (free, optional but recommended)**

`search_connected_papers` and `visualize_connected_papers` are powered by the **Semantic Scholar Academic Graph API (v1)**. They work **without an API key** — but the free shared pool is rate-limited (the client paces requests ~4s apart), so building a Connected Papers graph can take **20–60 seconds**. Adding a free key gives you a dedicated pool (~1 req/sec) for faster, more reliable results.

1. Go to [https://www.semanticscholar.org/product/api](https://www.semanticscholar.org/product/api)
2. Click **"Get API Key"** and fill in the form (free, instant)
3. Paste the key into the `SEMANTIC_SCHOLAR_API_KEY` field in `.mcp.json`

Rate limit with a key: **1 request/second (dedicated pool)**. Without a key: shared pool, slower and more likely to get throttled.

> **Note:** `SEMANTIC_SCHOLAR_API_KEY` is **separate** from `CONNECTED_PAPERS_API_KEY`. The Connected Papers key only affects the optional official Connected Papers API path — it does **not** raise your Semantic Scholar rate limit.

**Step 4 — Set the API key as a system environment variable (macOS)**

Due to a macOS behavior where GUI apps don't always inherit `env` fields from `.mcp.json`, run the following command so the key is available to all processes:

```bash
launchctl setenv SEMANTIC_SCHOLAR_API_KEY "YOUR_KEY_HERE"
```

> **Note:** This setting is lost on reboot. To make it permanent, add the following line to `~/.zshenv`:
> ```bash
> export SEMANTIC_SCHOLAR_API_KEY="YOUR_KEY_HERE"
> ```
> Then re-run `launchctl setenv` or reboot once.

**Step 5 — Enable the MCP server in Claude Code**

In VS Code, open Claude Code settings (`.claude/settings.local.json`) and ensure:

```json
{
  "enableAllProjectMcpServers": true,
  "enabledMcpjsonServers": ["zotero"]
}
```

**Step 6 — Reload VS Code**

Press `Cmd+Shift+P` → **Developer: Reload Window**. Claude Code will start the MCP server process and connect to it.

**Step 7 — Verify**

In a Claude Code conversation, try:

```
search_connected_papers(query="mycelium composite")
```

If it returns a list of papers without a rate-limit error, the setup is complete.

---

### Troubleshooting: Semantic Scholar API Key Not Working

This documents a known issue encountered on macOS with Claude Code (VS Code extension).

#### Symptom

`search_connected_papers` fails with:

```
Error: Rate limited by Semantic Scholar. Please set SEMANTIC_SCHOLAR_API_KEY environment variable...
Progress: [1/1] Fetching seed paper
```

Even after placing the key in `.mcp.json`'s `env` field and reloading VS Code.

#### Root Cause

On macOS, GUI applications (including the VS Code extension) do not always propagate `env` fields from `.mcp.json` into the MCP server subprocess environment. As a result, the server starts without the key, falls back to Semantic Scholar's shared rate-limit pool, and gets throttled — especially after a few rapid requests.

This was confirmed by:
1. Verifying the key was valid (`curl` with the key returned HTTP 200)
2. Checking the server process with `ps eww -p <PID> | grep SEMANTIC` — the key was absent from the process environment
3. After `launchctl setenv`, the key appeared in new processes

#### Fix 1 — `launchctl setenv` (immediate, session-scoped)

```bash
launchctl setenv SEMANTIC_SCHOLAR_API_KEY "YOUR_KEY_HERE"
```

Restart Claude Code after running this.

#### Fix 2 — `~/.zshenv` (permanent across reboots)

Add this line to `~/.zshenv`:

```bash
export SEMANTIC_SCHOLAR_API_KEY="YOUR_KEY_HERE"
```

#### Fix 3 — Self-bootstrapping in `server.py` (built-in fallback)

`server.py` now contains a `_load_keys_from_mcp_json()` function that reads the `env` block from `.mcp.json` at startup and sets any missing environment variables directly via `os.environ`. This means the server can find its own key even if the OS-level injection fails.

#### Fix 4 — Retry logic in the API client

`semantic_scholar.py` now retries automatically on HTTP 429 (up to 3 times, with 5s / 10s / 15s back-off). This prevents transient throttling from crashing the entire tool call.

---

### Tested Environment

| Software | Version |
|----------|---------|
| macOS | 14.6 (Sonoma) |
| Zotero | 7.0.32 |
| Claude Desktop | 1.1.6452 |
| Claude Code (VS Code extension) | tested April 2026 |

### Troubleshooting

| Problem | Solution |
|---------|----------|
| Server not showing "running" | Restart Claude Desktop after saving config |
| "Zotero database not found" | Check `ZOTERO_DB_PATH` or ensure Zotero is installed |
| First command fails | Try again — the server may need a moment to initialize |
| `search_connected_papers` rate-limited despite having a key | See **Troubleshooting: Semantic Scholar API Key Not Working** above |

### Note: What is `zotero.sqlite`?

`zotero.sqlite` is a [SQLite](https://www.sqlite.org/) database file where Zotero stores all your library data — titles, authors, tags, collections, DOIs, notes, and more. Unlike server-based databases (MySQL, PostgreSQL), SQLite keeps everything in a single file, and no separate server process is needed.

Zotero MCP reads this file (via a temporary read-only copy) to provide your library data to Claude. It **never modifies** your original database.

Default location: `~/Zotero/zotero.sqlite`

### Note: Where should Zotero MCP be installed?

Zotero MCP does not need to be placed in any specific folder. The installation method uses `uvx zotero-mcp-local`, which automatically downloads and runs the package from PyPI — no manual cloning or file placement required.

You only need to:
1. Install `uv`
2. Add `"command": "uvx", "args": ["zotero-mcp-local"]` in your Claude Desktop config

`uvx` automatically manages the package download and storage (typically under `~/.cache/uv/`).

The only path you need to verify is your **Zotero database** itself, which defaults to `~/Zotero/zotero.sqlite`. If it's not at the default location, specify it via the `ZOTERO_DB_PATH` environment variable.

### Roadmap (planned, not yet available)

The following features are planned for a future release and are **not** part of the current version:

- **Research World (gamified progress)** — turn your writing and reading into a visible research map: bricks, structures, topic trails, streaks, researcher stats, and Minecraft / Minetest export.
- **APA → ACM LaTeX conversion** — convert a Markdown draft with APA 7th in-text citations into ACM numbered LaTeX (`\cite{}`), including Figure/Table cross-references, ready for Overleaf.

---

## 中文說明

### 功能

一個 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 伺服器，讓 AI Agent（Claude 等）能直接存取你本地的 **Zotero** 資料庫。用自然語言搜尋文獻、閱讀 PDF、尋找相關論文。


#### Zotero 本地工具
- **`search_items(query)`** — 依標題或作者搜尋文獻
- **`get_item_details(item_key)`** — 取得完整詮釋資料（摘要、作者、DOI 等）
- **`find_related_papers(item_key, limit)`** — 使用五維複合相似度找出相關論文（共同集合 30%、標籤 25%、全文詞彙重疊 25%、作者 10%、出版場所 10%）
- **`list_collections(parent_collection_key)`** — 瀏覽集合（資料夾）層級結構 — 不帶參數顯示頂層集合，帶 key 顯示子集合
- **`get_collection_items(collection_key)`** — 列出特定集合中的所有文獻
- **`get_pdf_text(item_key, max_pages)`** — 提取 PDF 附件全文

#### 研究分析工具（Connected Papers + 研究缺口分析）
- **`search_connected_papers(query, doi, item_key, limit)`** — 使用 bibliographic coupling（與 connectedpapers.com 相同演算法）找出相關論文。可傳入關鍵字、DOI 或 Zotero item key。預設使用 Semantic Scholar；設定 `CONNECTED_PAPERS_API_KEY` 可改用官方 Connected Papers API。
- **`find_research_gaps(item_keys, topic)`** — 分析多篇論文的 PDF，提取明確說明的研究限制、建議的未來研究方向、以及方法論缺口，並跨論文整合共同主題。`item_keys` 以逗號分隔。
- **`find_key_passages(item_keys, query, top_n)`** — 在多篇論文的 PDF 中以 TF-IDF 搜尋與你的查詢最相關的段落，回傳段落原文、論文標題、Zotero key 及頁碼，可直接用於引用或佐證論點。

#### 資源
- `zotero://library/info` — 資料庫統計資訊
- `zotero://library/items` — 最近 50 筆文獻
- `zotero://items/{key}` — 依 Key 取得文獻詳情

### 安裝

#### 前置需求

- **Zotero 7**（已安裝，預設資料庫路徑 `~/Zotero/zotero.sqlite`）— 正式支援；Zotero 5 與 6 相容性未實測
- **uv** — Python 套件管理工具：

  **Mac/Linux：**
  ```bash
  curl -LsSf https://astral.sh/uv/install.sh | sh
  ```
  **Windows（PowerShell）：**
  ```powershell
  powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
  ```

  > 安裝完成後請**重新開啟終端機**，輸入 `uv --version` 確認安裝成功。
  >
  > 如果安裝成功，會顯示版本號，例如：
  > ```
  > uv 0.6.6 (Homebrew 2025-03-04)
  > ```
  > 如果出現 `command not found`，表示 `uv` 未正確加入 PATH，需要檢查 shell 設定檔（`~/.zshrc` 或 `~/.bashrc`）是否有加入 uv 的路徑。

#### 設定 Claude Desktop

開啟 Claude Desktop，前往 **Settings → Developer → Edit Config**，將以下內容貼入 `claude_desktop_config.json`：

```json
{
  "preferences": {
    "coworkScheduledTasksEnabled": true,
    "ccdScheduledTasksEnabled": true,
    "sidebarMode": "chat",
    "coworkWebSearchEnabled": true
  },
  "mcpServers": {
    "zotero": {
      "command": "uvx",
      "args": ["zotero-mcp-local"]
    }
  }
}
```

儲存後**重新啟動 Claude Desktop**，前往 **Settings → Developer**，應可看到 Zotero MCP 伺服器顯示 **「running」** 狀態：

![Zotero MCP running](docs/claude_desktop_running.png)

### 使用範例

設定完成後，直接用自然語言與 Claude 對話：

- 「搜尋我 Zotero 裡關於懷舊治療的文獻」
- 「顯示文獻 ABCD1234 的詳細資訊」
- 「找出我資料庫中與 ABCD1234 相關的論文」
- 「提取 XYZ789 的 PDF 全文」
- 「顯示我所有的 Zotero 集合」
- 「Background / trend 資料夾裡有哪些論文？」

**研究分析典型工作流程：**

```
1. search_items("你的主題")                              → 找到 Zotero 裡的論文 key
2. search_connected_papers(item_key="ABCD1234")         → 擴展文獻，找出 Semantic Scholar 上的相關論文
3. find_research_gaps(item_keys="K1,K2,K3")            → 找出研究缺口與未來研究方向
4. find_key_passages(item_keys="K1,K2,K3", query="你的論點") → 找出支持論點的段落
```

- 「用 Connected Papers 找跟『參與式設計 高齡者』相關的論文」
- 「分析 KEY1、KEY2、KEY3 這幾篇論文的研究缺口，聚焦在高齡使用者面向」
- 「在這些論文 KEY1、KEY2 裡找跟『社會孤立介入設計』相關的段落」

### 運作原理

- **資料庫存取：** 透過臨時副本讀取 Zotero SQLite 資料庫（唯讀，不會修改你的資料）。
- **關聯論文演算法：** 使用五維加權相似度 — 共同集合、標籤、全文詞彙重疊（IDF 過濾）、共同作者、出版場所。
### 在另一台 Mac 使用

如果想在另一台 Mac 使用 zotero-mcp-local（不透過 Claude Desktop 或 Claude Code），需要拷貝 Zotero 資料：

#### 需要拷貝的檔案

| 檔案 | 大小估計 | 必要性 | 用途 |
|------|---------|--------|------|
| `zotero.sqlite` | 數十 MB | **必須** | 所有 metadata 查詢 |
| `storage/` 資料夾 | 可能數 GB | PDF 功能需要 | PDF 文字提取 |
| MCP server 程式 | 安裝即可 | **必須** | 提供 MCP 工具介面 |

- **`~/Zotero/zotero.sqlite`** — 核心資料庫，所有文獻的 metadata（標題、作者、摘要、標籤、collections、日期等）都存在這裡。
- **`~/Zotero/storage/`** — PDF 檔案存放處。不拷貝的話搜尋和查詢 metadata 仍可用，但 `get_pdf_text` 會失敗。

#### 設定步驟

```bash
# 1. 把 Zotero 資料拷過去（假設放在預設路徑 ~/Zotero/）
scp ~/Zotero/zotero.sqlite user@other-mac:~/Zotero/
scp -r ~/Zotero/storage/ user@other-mac:~/Zotero/storage/

# 2. 在另一台 Mac 安裝 MCP server
pip install zotero-mcp-local

# 3. 如果資料庫不在預設路徑，設定環境變數
export ZOTERO_DB_PATH="/path/to/zotero.sqlite"

# 4. 啟動 MCP server
uvx zotero-mcp-local
```

這個系統完全是本地運作，不需要網路、不需要 Zotero 帳號同步。只要有 `zotero.sqlite` 檔案，就能查詢整個文獻庫。

### 使用 Claude Code（VS Code 擴充套件）安裝

如果你使用的是 VS Code 裡的 Claude Code（而非 Claude Desktop），請依以下步驟從原始碼安裝。

#### 適用系統環境

| 作業系統 | 狀態 |
|---------|------|
| macOS 13+（Sonoma / Sequoia） | 完整測試 |
| Linux（Ubuntu 22.04+） | 應可正常運作；不需要 `launchctl`，改用 `~/.bashrc` 或 `~/.zshenv` 設定環境變數 |
| Windows 11 | 應可搭配 uv 運作；環境變數透過「系統內容 → 環境變數」設定 |

#### 前置需求

| 工具 | 用途 | 安裝方式 |
|------|------|---------|
| [Zotero](https://www.zotero.org/) | 文獻資料庫來源 | 從 zotero.org 下載 |
| [uv](https://docs.astral.sh/uv/) | Python 套件管理工具 | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
| [VS Code](https://code.visualstudio.com/) + Claude Code 擴充套件 | AI Agent 宿主 | 從 VS Code Marketplace 安裝 |
| [Git](https://git-scm.com/) | 拉取程式碼 | Mac/Linux 通常已預裝 |

#### 安裝步驟

**步驟 1 — Clone 專案**

```bash
git clone https://github.com/piiinpiiins/Zotero-MCP.git
cd Zotero-MCP
```

**步驟 2 — 建立 MCP 設定檔**

在專案根目錄建立 `.mcp.json`（此檔案已加入 `.gitignore`，不會被 commit）：

```json
{
  "mcpServers": {
    "zotero": {
      "command": "uv",
      "args": [
        "--directory", "/你的專案絕對路徑/Zotero-MCP",
        "run", "python", "-m", "src.zotero_mcp.server"
      ],
      "env": {
        "SEMANTIC_SCHOLAR_API_KEY": "你的金鑰"
      }
    }
  }
}
```

將 `/你的專案絕對路徑/Zotero-MCP` 替換為實際路徑。

**步驟 3 — 取得 Semantic Scholar API Key（免費，選用但建議）**

`search_connected_papers` 與 `visualize_connected_papers` 由 **Semantic Scholar 學術圖譜 API（v1）** 提供。**沒有 API key 也能使用**，但免費共用配額有速率限制（用戶端會把請求間隔約 4 秒），因此建一張 Connected Papers 關聯圖可能需要 **20–60 秒**。申請免費金鑰可取得獨立配額（約 1 次/秒），更快也更穩定。

1. 前往 [https://www.semanticscholar.org/product/api](https://www.semanticscholar.org/product/api)
2. 點擊 **「Get API Key」** 填寫申請表（免費，立即取得）
3. 將金鑰填入 `.mcp.json` 的 `SEMANTIC_SCHOLAR_API_KEY` 欄位

有金鑰時：**1 次請求/秒（獨立配額）**。無金鑰時：使用共用配額，速度較慢且容易被節流。

> **注意：** `SEMANTIC_SCHOLAR_API_KEY` 與 `CONNECTED_PAPERS_API_KEY` 是**兩把不同的金鑰**。Connected Papers 金鑰只影響選用的官方 Connected Papers API 路徑，**不會**提高 Semantic Scholar 的速率上限。

**步驟 4 — 在系統層設定環境變數（macOS）**

由於 macOS 的 GUI app 行為，`.mcp.json` 的 `env` 欄位不一定能正確傳遞給 MCP server process，需額外執行：

```bash
launchctl setenv SEMANTIC_SCHOLAR_API_KEY "你的金鑰"
```

> **注意：** `launchctl setenv` 的設定在重開機後會消失。若要永久生效，在 `~/.zshenv` 加入：
> ```bash
> export SEMANTIC_SCHOLAR_API_KEY="你的金鑰"
> ```
> 然後重新執行 `launchctl setenv` 一次，或重開機。

**步驟 5 — 在 Claude Code 啟用 MCP server**

確認 `.claude/settings.local.json` 包含：

```json
{
  "enableAllProjectMcpServers": true,
  "enabledMcpjsonServers": ["zotero"]
}
```

**步驟 6 — 重新載入 VS Code**

按 `Cmd+Shift+P` → **Developer: Reload Window**，Claude Code 會啟動 MCP server 並與之連線。

**步驟 7 — 驗證**

在 Claude Code 對話中輸入：

```
search_connected_papers(query="mycelium composite")
```

若回傳論文列表而非 rate limit 錯誤，代表設定成功。

---

### 問題排除：Semantic Scholar API Key 無效

以下記錄在 macOS 搭配 Claude Code（VS Code 擴充套件）時遇到的已知問題。

#### 症狀

`search_connected_papers` 回傳以下錯誤，即使已在 `.mcp.json` 填入正確 key：

```
Error: Rate limited by Semantic Scholar. Please set SEMANTIC_SCHOLAR_API_KEY environment variable...
Progress: [1/1] Fetching seed paper
```

#### 根本原因

在 macOS 上，GUI 應用程式（包含 VS Code 擴充套件）不一定會將 `.mcp.json` 的 `env` 欄位傳遞給 MCP server 的子程序環境變數，導致 server 以無金鑰模式啟動，使用 Semantic Scholar 的共用配額，連續幾次請求後即被節流。

**診斷過程：**
1. 用 `curl` 帶金鑰呼叫 S2 API → 回傳 HTTP 200（金鑰本身有效）
2. 用 `ps eww -p <PID> | grep SEMANTIC` 確認 server process 的環境變數 → 確認金鑰不存在
3. 執行 `launchctl setenv` 後，新啟動的 process 才有金鑰

#### 修復方式

**修復 1 — `launchctl setenv`（立即生效，重開機後失效）**

```bash
launchctl setenv SEMANTIC_SCHOLAR_API_KEY "你的金鑰"
```

執行後重新啟動 Claude Code。

**修復 2 — `~/.zshenv`（永久生效）**

在 `~/.zshenv` 加入：

```bash
export SEMANTIC_SCHOLAR_API_KEY="你的金鑰"
```

**修復 3 — `server.py` 自舉（已內建為 fallback）**

`server.py` 在啟動時會執行 `_load_keys_from_mcp_json()`，自行讀取 `.mcp.json` 的 `env` 區塊，並透過 `os.environ` 補齊缺少的環境變數。即使 OS 層的注入失敗，server 仍能找到金鑰。

**修復 4 — API client 自動重試（已內建）**

`semantic_scholar.py` 在收到 HTTP 429 時會自動重試最多 3 次（等待 5s / 10s / 15s），避免偶發的節流造成整個工具呼叫失敗。

---

### 測試環境

| 軟體 | 版本 |
|------|------|
| macOS | 14.6 (Sonoma) |
| Zotero | 7.0.32 |
| Claude Desktop | 1.1.6452 |
| Claude Code（VS Code 擴充套件） | 2026 年 4 月測試 |

### 常見問題排除

| 問題 | 解決方法 |
|------|----------|
| 伺服器未顯示 "running" | 儲存設定後重新啟動 Claude Desktop |
| "Zotero database not found" | 確認 `ZOTERO_DB_PATH` 或確保 Zotero 已安裝 |
| 第一個指令失敗 | 再試一次，伺服器可能需要片刻初始化 |
| `search_connected_papers` 有金鑰仍被 rate limit | 參閱上方「問題排除：Semantic Scholar API Key 無效」 |

### 備註：
#### `zotero.sqlite` 是什麼？

`zotero.sqlite` 是一個 [SQLite](https://www.sqlite.org/) 資料庫檔案，Zotero 將你所有的文獻資料都儲存在這個檔案中 — 包括標題、作者、標籤、集合、DOI、筆記等。與需要啟動伺服器的資料庫（MySQL、PostgreSQL）不同，SQLite 將所有資料存在單一檔案中，不需要額外的伺服器程序。

Zotero MCP 透過臨時的唯讀副本讀取此檔案，將你的文獻資料提供給 Claude 使用。它**絕不會修改**你的原始資料庫。

預設路徑：`~/Zotero/zotero.sqlite`

#### Zotero MCP 應該放在哪裡？

Zotero MCP 不需要放在特定資料夾。安裝方式是用 `uvx zotero-mcp-local`，`uvx` 會自動從 PyPI 下載並執行，不需要手動 clone 或放置任何檔案。

使用者只需要：
1. 安裝 `uv`
2. 在 Claude Desktop 設定中加入 `"command": "uvx", "args": ["zotero-mcp-local"]`

`uvx` 會自動管理套件的下載和存放位置（通常在 `~/.cache/uv/` 下）。

唯一需要確認位置的是 **Zotero 資料庫本身**，預設在 `~/Zotero/zotero.sqlite`。如果不在預設位置，才需要透過 `ZOTERO_DB_PATH` 環境變數指定。

### 未來功能（規劃中，尚未提供）

以下功能為未來版本規劃，**目前版本尚未包含**：

- **研究世界（遊戲化進度）** — 把寫作與閱讀變成一張可見的研究地圖：磚塊、建築、主題路徑、連續天數、研究者統計，並可匯出成 Minecraft／Minetest。
- **APA → ACM LaTeX 轉換** — 把含 APA 第 7 版內文引用的 Markdown 草稿，轉成 ACM 編號式 LaTeX（`\cite{}`），連 Figure／Table 交叉引用一併處理，可直接貼進 Overleaf。

---

## License

MIT

---

[![Buy Me A Coffee](https://img.shields.io/badge/Buy%20Me%20A%20Coffee-support-yellow?style=flat&logo=buy-me-a-coffee)](https://buymeacoffee.com/apinrece)


---

## Disclaimer / 免責聲明

This is an unofficial tool and is not affiliated with or endorsed by Zotero (Corporation for Digital Scholarship). "Zotero" is a trademark of its respective owner.

本產品為非官方工具，與 Zotero（Corporation for Digital Scholarship）並無隸屬關係；Zotero 為其商標。
