Skip to main content
Glama

huiwen-mcp

Model Context Protocol (MCP) Server for the Huiwen Library Management System (Libsys / OPAC) — An AI-oriented read-only data gateway for libraries: Enables AI clients like Claude / Cherry Studio / DeepSeek to securely and audibly retrieve catalog records, item availability, circulation statistics, and union catalogs.

An official adaptation layer developed by a university library, adhering to the security baseline of read-only by default, least privilege, and full-chain auditing.

  • Protocol: Model Context Protocol (Anthropic open standard, same technical approach as Yale Library's catalog integration)

  • Runtime: Python ≥ 3.10 · FastMCP 3.x

  • Data Sources: demo (zero-dependency demonstration) / opac (Huiwen OPAC public web protocol) / oracle (Huiwen Libsys database read-only direct connection)

  • License: Apache-2.0 (recommended, see License & Compliance)


Table of Contents

  1. Features

  2. System Design Philosophy

  3. Implementation Technical Approach

  4. Quick Start

  5. Configuration (Environment Variables / .env)

  6. Tool List

  7. Client Integration Examples

  8. Use Cases

  9. Security & Compliance

  10. Testing

  11. Project Structure

  12. Roadmap

  13. License & Compliance

  14. Troubleshooting


Features

Capability

Description

🔍 Catalog Search

Multi-field / CLC / Location / In-library filter / Sort / Pagination

📚 Bibliographic Details

Full bibliographic record for a single item, all holding item status & circulation statistics

✅ Item Availability

Quick check of borrowable status by ISBN / Barcode / Title

🔥 Hot & New Books

Popular borrowing rankings, new book alerts for the last N days

🧭 Classification Browsing

Real-time hit counts for CLC classifications/prefixes

📊 Statistics

Total holdings / By location / By classification

🤝 Union Catalog

PROCAT cross-library union search (optional, disabled by default, JWT authentication)

👤 Patron Data (admin)

Current borrowing / Borrowing history / Fines (PII masked by default)

🛡️ Security

Authentication → Rate Limiting → PII/Patron Gating → JSONL Auditing; read-only by default

🔌 Transport

stdio (in-process) / Streamable HTTP (service-oriented)

🐳 Deployment

Docker image (non-root, reproducible build); production/gateway-level authentication scheme in docs/deployment-guide.md

🧩 Pluggable Data Sources

demo / opac / oracle switchable with one click, same tool signatures

Design Trade-off: Write operations (renewal, reservation, interlibrary loan ordering) are intentionally not implemented — this project only provides "secure and auditable reading"; all write paths are delegated to the original business systems and manual processes.


System Design Philosophy

Positioning: Data Gateway / Skill Layer, Not a Database Proxy

AI clients (large language models) never directly connect to the Huiwen database. All queries are encapsulated through a controlled tool layer:

┌─────────────── AI 客户端(Claude / Cherry Studio / 自研 Agent / 本地 LLM) ───────────────┐
│                                      │                                                    │
│             stdio(子进程协议)        │        Streamable HTTP(服务化 / 网关 / SSO)        │
└──────────────────────────────────────┼────────────────────────────────────────────────────┘
                                       ▼
┌───────────────────────────────────────────────────────────────────────────────────────┐
│   huiwen-mcp(FastMCP 3.x)                                                            │
│   ┌─────────────── 安全链 _guard ───────────────┐                                        │
│   │ 认证(Auth) → 限流(TokenBucket) → 门控(PII/读者) │   ← 每个工具必经                     │
│   └──────────────────────────────────────────────┘                                        │
│   │ 工具层:search_books / get_book_detail / union_search / get_reader_* / … (12 个)     │
│   └──────────────────────────────────┬───────────────────────────────────────────────────┘
                                       ▼
┌───────────────────────────────────────────────────────────────────────────────────────┐
│   适配器(可插拔数据源,统一 CatalogBackend 接口)                                       │
│   ├─ OracleBackend:白名单参数化 SQL(db/queries.py 封闭集)   → 汇文 Libsys 只读账号    │
│   ├─ OpacBackend:白名单参数调汇文 OPAC 公开网页协议           → opac 站点                │
│   └─ DemoBackend:内置样例数据                                 → 离线演示/测试            │
└───────────────────────────────────────────────────────────────────────────────────────┘
  • Single Responsibility per Layer: The adapter is only responsible for data retrieval; _guard is only responsible for security; auditing independently writes JSONL logs; the upper-layer AI only interacts with tool signatures, unaware of backend differences (three backends, same signatures).

  • Secure by Default: data_source=demo runs with zero dependencies; opac/oracle require explicit configuration; patron-sensitive tools require an admin token; write operations are disabled by default; external union services are disabled by default.

Why MCP

  • MCP is an open standard for connecting AI to "databases/business systems" (Anthropic released Nov 2024, ecosystem includes GitHub/cloud vendors/database vendors). Choosing an open standard over a private API ensures: client replaceability (Claude/Cherry Studio/DeepSeek/custom Agent), service reusability across multiple systems, and long-term freedom from vendor lock-in — this is the same path Yale Library took with MCP for catalog integration.

  • FastMCP provides stdio / HTTP dual transport for server implementation, supporting both in-process and service-oriented deployment with a single codebase.

Transport Mode Selection: stdio vs HTTP

  • stdio: Launched in-process with the client, zero operations overhead, lowest latency, suitable for personal/single-machine integration with AI desktop clients.

  • HTTP (Streamable HTTP): Independent service, suitable for multi-user/centralized deployment; can be fronted by an OAuth2/JWT reverse proxy and campus unified identity for centralized auditing.


Implementation Technical Approach

Concern

Approach

MCP Server

fastmcp>=2,<4; add_tool registration; stdio/http dual run()

Strict Tool Signature Constraints

FastMCP 3.x rejects tool functions with *args/**kwargs → All tools use explicitly typed parameters; _guard wraps with functools.wraps and passes kwargs transparently (explicit token model, avoids **kwargs triggering framework rejection)

Authentication Chain

AuthConfig (Bearer) + RateLimit (Token Bucket) + Patron/PII Gating (admin token) + AuditLogger (JSONL)

Oracle Backend

python-oracledb; 11g → thick mode (Instant Client), 12c+ → thin; all SQL confined to db/queries.py (parameterized, whitelist, read-only account)

OPAC Backend

Whitelist parameters construct Huiwen public web protocol (openlink.php search / item.php details / top_lend.php hot items), parse public HTML templates (selectors verified against vendor templates item by item)

Union Catalog

POST {base}/api/search/listByQuery + {current,pageSize,items:[{field,value,logic,type}]} + ?tenantCode&tk=<JWT> (contract verified against live system); disabled by default

Configuration

HUIWEN_ environment variables (.env auto-loaded) + config.local.json (sensitive values, git-ignored, auto-merged)

Models

pydantic explicit result models, type-safe, stable serialization

Key Contracts (All Verified Against Live Systems)

  • OPAC: Search results <ol id="search_book_list"><li class="book_list_info">, title/call number/holding copies/available copies/hit count; detail page item table; hot list.

  • Union PROCAT: POST (GET→405); authentication via query parameter tk= (JWT issued by OPAC patron session getReaderJwt); items[].logic="1"(AND)/"2"(OR); field mapping any/title/author/subject/isbn/clcNumber/publisher/series. See docs/union-catalog-search.md for details.

⚠️ OPAC / Union are vendor-closed or third-party systems; contracts may change with deployment versions. All integration documentation is based on "live system verification" and validated using tests/test_*_live.py.


Quick Start

1) Installation

git clone <your-repo-url> && cd huiwen-mcp
# 方式 A:uv(推荐)
uv sync
# 方式 B:pip
python -m venv .venv
. .venv/bin/activate
pip install -e .

2) Run with Zero Configuration (demo data source, offline)

HUIWEN_DATA_SOURCE=demo uv run huiwen-mcp        # stdio 模式
HUIWEN_DATA_SOURCE=demo HUIWEN_TRANSPORT=http uv run huiwen-mcp   # HTTP 模式

demo includes sample bibliographic/patron data, suitable for smoke testing, development testing, and integration teaching.

2b) One-Click Docker Deployment

docker build -t huiwen-mcp:latest .
docker run --rm -it -e HUIWEN_DATA_SOURCE=demo huiwen-mcp:latest   # stdio,离线可跑

# 服务化(HTTP + 认证 + 审计)
docker run -d --name huiwen -p 8765:8765 \
  -e HUIWEN_TRANSPORT=http -e HUIWEN_DATA_SOURCE=opac \
  -e HUIWEN_OPAC_BASE_URL=https://opac.example.edu.cn \
  -e HUIWEN_AUTH_ENABLED=true -e HUIWEN_AUTH_BEARER_TOKEN=<强随机> \
  -v huiwen-audit:/var/log/huiwen huiwen-mcp:latest

More (Oracle 11g thick / compose / reverse proxy-level authentication with campus CAS) in docs/deployment-guide.md.

3) Connect to Real Data Sources (opac / oracle)

Copy .env.example to .env and fill in the values (.env is git-ignored):

cp .env.example .env
# 编辑 .env:设置 HUIWEN_DATA_SOURCE 与对应凭据
HUIWEN_DATA_SOURCE=opac
HUIWEN_OPAC_BASE_URL=https://opac.example.edu.cn      # 你们学校 OPAC 地址

Or use config.local.json (sensitive configuration auto-loaded, not committed to repository).


Configuration (Environment Variables / .env)

All configurations can be injected via environment variables (prefix HUIWEN_), and also support .env files (auto-loaded). Priority: Environment Variables > Explicit config.json / CONFIG_PATH > config.local.json Auto-Merge > Built-in Defaults.

General

Variable

Description

Default

HUIWEN_DATA_SOURCE

demo / opac / oracle

demo

HUIWEN_TRANSPORT

stdio / http

stdio

HUIWEN_HOST / HUIWEN_PORT

HTTP listening

127.0.0.1 / 8765

HUIWEN_INCLUDE_PII

Whether to output patron sensitive fields (requires admin)

false

HUIWEN_AUDIT_LOG

JSONL audit log path (leave empty to disable)

Empty

HUIWEN_CONFIG_LOCAL_PATH

Local sensitive configuration file name

config.local.json

OPAC

Variable

Description

Default

HUIWEN_OPAC_BASE_URL

Huiwen OPAC root URL

HUIWEN_OPAC_TIMEOUT

Search timeout (recycle bin is slow 15-40s, allow enough time)

25s

HUIWEN_OPAC_ALLOW_READER_SESSION

Whether to allow personal data after patron login (disabled by default)

HUIWEN_OPAC_UNION_ENABLED

Union catalog switch (disabled by default)

HUIWEN_OPAC_UNION_BASE_URL

Union service URL

HUIWEN_OPAC_UNION_TENANT

Tenant code

HUIWEN_OPAC_UNION_TOKEN

Patron session JWT (entire getReaderJwt string)

Oracle

Variable

Description

HUIWEN_ORACLE_DSN

host:port/service or Easy Connect

HUIWEN_ORACLE_USER / _PASSWORD

Read-only account (strongly recommended)

HUIWEN_ORACLE_MODE

thin (12c+) / thick (11g/10g requires Instant Client)

HUIWEN_ORACLE_CLIENT_LIB_DIR

Instant Client directory for thick mode

HUIWEN_ORACLE_READ_ONLY

Semantic constraint for read-only (default true)

HUIWEN_ORACLE_POOL_MIN/MAX

Connection pool size

Security

Variable

Description

HUIWEN_AUTH_ENABLED

Whether to enable Bearer authentication (must enable in production)

HUIWEN_AUTH_BEARER_TOKEN

Static Bearer Token

HUIWEN_AUTH_ADMIN_TOKENS

Comma-separated admin tokens (for patron/write-related export tools)

HUIWEN_RATE_LIMIT_ENABLED / _RPS / _BURST

Token bucket rate limiting


Tool List

Tool

Description

Token Required

search_books

Catalog search (field/CLC/location/in-library filter/sort/pagination)

get_book_detail

Full bibliographic information for a single item (including all holding items and circulation statistics)

get_availability

Check item availability by ISBN/Barcode/Title

get_hot_books

Popular borrowing rankings (can be filtered by CLC category)

get_new_arrivals

New book alerts for the last N days

browse_classification

CLC classification browsing/real-time prefix hit counts

union_search

Cross-library union catalog read-only search (disabled by default)

Configuration

get_statistics

Holdings statistics (total/by location/by classification)

get_reader_borrowing

Patron's current borrowing

admin

get_reader_history

Patron's borrowing history

admin

get_reader_fines

Patron's fines

admin

get_system_status

Data source and service status

For functional descriptions and integration assessment of Huiwen ACS/SIP2 interface services, see docs/huiwen-acs-sip2-interface-description-and-integration-assessment.md (authoritative field mapping, read-only subset candidates, explicitly prohibited items).

Patron tools are masked by default (include_pii=false does not return ID numbers/contact information; true requires admin).


Client Integration Examples

Claude Desktop / MCP-Supported Desktop Clients

{
  "mcpServers": {
    "huiwen": {
      "command": "/path/to/uv",
      "args": ["--directory", "/path/to/huiwen-mcp", "run", "huiwen-mcp"],
      "env": { "HUIWEN_DATA_SOURCE": "demo" }
    }
  }
}

Remote HTTP (Requires Authentication Gateway Setup)

HUIWEN_TRANSPORT=http HUIWEN_HOST=0.0.0.0 HUIWEN_PORT=8765 uv run huiwen-mcp

Clients use ${MCP_SERVER_URL} to connect to http://<host>:8765/mcp/ (Streamable HTTP). When HUIWEN_AUTH_ENABLED=true is enabled, the token is passed as a tool parameter token with each call; the HTTP Authorization header is not consumed by the server (see deployment guide §3.2).


Use Cases

User

Scenario

Patron

"Is 'The Three-Body Problem' available, which floor, how many copies can be borrowed, what's popular nearby" — one-stop for finding books/studying/research

Reference Librarian

Auto-check catalog/holdings → generate draft response → manual review (Copilot mode)

Subject Librarian

Subject bibliographies, literature support statistics, departmental purchase recommendation reports

Acquisitions/Cataloging

ISBN deduplication, gap analysis, new book alerts, metadata validation

Library Leadership

Holdings/circulation statistics charts, data weekly reports

AI Librarian Portal

As the core data layer for intelligent Q&A/intelligent book recommendations

Consortium Building

Cross-library union search (gap found → search union → formal interlibrary loan)

For complete suggestions (including locally deployed LLM + RAG layered approach and domestic/international benchmarking), see docs/service-and-application-suggestions.md.


Security & Compliance

  1. Read-Only by Default: All tools are read-only; write operations (renewal/reservation/interlibrary loan ordering) are intentionally not implemented.

  2. Whitelist SQL: The Oracle backend only executes the parameterized SQL closed set within db/queries.py, no free SQL.

  3. Full-Chain Gating: Authentication → Rate Limiting → Patron/PII Gating → Auditing (JSONL). Patron personal data requires an admin token and is masked by default.

  4. Authentication Contract (Verified Against Live System): The token is passed via the tool parameter token (an optional parameter for each tool; _guard extracts it from the parameters and compares it with HUIWEN_AUTH_BEARER_TOKEN). The HTTP Authorization header passthrough is not implemented — transport layer TLS/unified identity is handled by the reverse proxy gateway; huiwen-mcp's own authentication is the second line of defense behind the gateway. Tokens are not written to audit logs (_guard pops them before recording).

  5. Secrets Not Committed to Repository: DSN/password/JWT/site URLs are only passed via environment variables or config.local.json (git-ignored). The repository contains no real deployment data (see NOTICE).

  6. External Services Handled with Caution: The Union PROCAT is a third-party multi-tenant system, disabled by default; confirm authorization with the union/service provider before enabling. OPAC is closed-source, has had public vulnerabilities historically; the adapter only uses whitelist parameters.

  7. Vulnerability reporting and handling are in SECURITY.md.


Testing

File

Content

Run Command

tests/smoke_demo.py

Demo backend smoke test (offline)

uv run python tests/smoke_demo.py

tests/test_stdio.py

stdio integration/authentication regression (demo)

uv run python tests/test_stdio.py

tests/test_oracle_live.py

Live database integration (disabled by default)

HUIWEN_LIVE_ORACLE=1 ...

tests/test_union_live.py

Union PROCAT live system (disabled by default)

HUIWEN_LIVE_UNION=1 ...

Live database/live system tests are disabled by default (require local explicit setting of HUIWEN_LIVE_* to execute) to avoid touching any real systems. Docker images are not built/published by default (the release strategy is "publish only source code and documentation"): if an image is needed, please docker build locally (add --build-arg WITH_INSTANT_CLIENT=true for Oracle thick mode).


Project Structure

huiwen-mcp/
├── src/huiwen_mcp/
│   ├── server.py            # FastMCP 装配、stdio/http 启动、main()
│   ├── config.py            # 配置:env/.env/config.local.json 分层合并
│   ├── audit.py             # JSONL 审计
│   ├── adapters/
│   │   ├── base.py          # CatalogBackend 抽象
│   │   ├── demo.py          # 内置演示数据
│   │   ├── opac.py          # 汇文 OPAC 网页协议(含 union_search)
│   │   └── oracle.py        # Libsys 数据库只读(thin/thick)
│   ├── db/queries.py        # 白名单参数化 SQL(Oracle 后端唯一 SQL 来源)
│   ├── models/schemas.py    # pydantic 结果模型
│   └── tools/catalog.py     # 12 个 MCP 工具 + _guard 安全链
├── docs/                    # 表结构 / 联盟契约 / 服务与应用建议 / 部署指南 / SIP2 评估
├── tests/                   # demo/stdio/oracle-live/union-live
├── Dockerfile / compose.yaml / .dockerignore
├── .env.example / config.example.json / config.local.json(忽略)
├── LICENSE / NOTICE / SECURITY.md / CONTRIBUTING.md / CODE_OF_CONDUCT.md
└── pyproject.toml

Roadmap

  • Phase 1: Read-only search MCP (demo + opac + oracle three backends)

  • Phase 2: OPAC / Oracle live database integration testing, Union catalog integration testing (contract verified + token scheme)

  • Phase 2 Remaining: Docker image (non-root, reproducible build) + deployment guide (including reverse proxy-level authentication template)

  • Released: v1.0.0 tag + GitHub Release (source code and documentation; no CI/workflows, Docker images not automatically built)

  • OAuth2/JWT gateway implementation for campus CAS / unified service portal (template ready, requires on-site configuration)

  • Phase 2.5/3 Candidate: Huiwen ACS/SIP2 read-only subset (assessment in docs/huiwen-acs-sip2-interface-description-and-integration-assessment.md)

  • Phase 3: RAG vector database + local LLM for intelligent book recommendations / reference consultation (see docs/service-and-application-suggestions.md)

  • Phase 4: Huiwen new-generation platform OpenAPI integration


License & Compliance

Open Source License Version Suggestion

This project recommends using the Apache License 2.0 (the repository includes the complete LICENSE):

  1. Permissive: Allows universities, vendors, and cloud platforms to freely use/modify/redistribute (including commercial use) as long as the copyright and license notice are retained—facilitating adoption by AI toolchains and third-party systems.

  2. Patent grant: Apache-2.0 explicitly grants a patent license from contributors (Section 3), making it clearer and more "anti-litigation" when multiple institutions/parties (multiple universities, technology vendors) contribute jointly.

  3. Contributor terms standardization: Implicitly grants a project license (Section 5, Contribution Grant), eliminating the need for each contributor to sign a separate CLA, consistent with common GitHub open-source project practices.

  4. Differentiation: Compared to MIT, Apache-2.0 is more suitable for infrastructure-type projects formally released by institutions and potentially maintained by multiple parties over the long term.

If your library prefers a "minimalist style," you can revert to MIT at any time: simply replace the full LICENSE file, change license in pyproject.toml back to { text = "MIT" }, and update this section in the README.

Compliance Statement (Important)

  • Contains no vendor/third-party source code: This project is an independent interoperability layer for the closed-source Huiwen/Libsys. It does not contain any proprietary code from Huiwen or the consortium. The OPAC/consortium contract is based solely on public web protocols and real-site response records. See NOTICE.

  • No deployment-sensitive data is published with the repository: Actual DSNs, account passwords, OPAC login instances, consortium JWTs, reader PII, or vendor SECRET_KEY are not in the repository (SECURITY.md/CONTRIBUTING.md has set red lines strictly prohibiting any suspected sensitive data from being committed).

  • Trademarks: Huiwen, Libsys, and OPAC are trademarks/product names of their respective owners (e.g., Jiangsu Huiwen Software). This repository uses them only for interoperability reference, not implying endorsement or affiliation.

  • Before using this software, please confirm the authorization and usage boundaries with Huiwen Software, the consortium service provider, and your library's IT center.


Troubleshooting

Phenomenon

Handling

"Backend not supported"

Verify HUIWEN_DATA_SOURCE; union_search is only for the opac backend and requires consortium configuration to be enabled.

Oracle DPY-3010 / connection failure

For 11g use HUIWEN_ORACLE_MODE=thick + HUIWEN_ORACLE_CLIENT_LIB_DIR (Instant Client).

OPAC search timeout

The site side is slow (15–40s common); increase HUIWEN_OPAC_TIMEOUT or retry later.

union_search returns enabled:false

Consortium not enabled or token missing → enable configuration and fill in JWT.

Consortium returns storage token not found

JWT expired → re-login to OPAC, get getReaderJwt to update the token.

Framework rejects tool registration (*args/**kwargs)

Tool functions must have explicit parameters; do not use *args/**kwargs signatures.

Reader tool returns "requires admin token"

Use a token from HUIWEN_AUTH_ADMIN_TOKENS.

-
license - not tested
-
quality - not tested
B
maintenance

Maintenance

Maintainers
Response time
Release cycle
1Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

  • Read-only MCP server for ClassQuill, a tutoring-business-management platform.

  • Hosted MCP server exposing US hospital procedure cost data to AI assistants

  • Read-only MCP connector serving the Run It on AI book; index and Implementation Blocks are free.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/isaacwang2023-droid/huiwen-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server