mcp-luopan
mcp-luopan
Превращает «Лопань» — расчет карты судьбы на основе метода «Чжэнь Цюань» (Ziping Zhenquan) — в набор инструментов MCP (Model Context Protocol), чтобы любой MCP-клиент (Claude Code / Claude Desktop / OpenClaw / Cursor / собственный LLM-агент) мог составлять карты, читать их и отвечать на вопросы пользователей в ходе диалога.
Облачный вход уже запущен: https://luopan.caihangao.com. MCP по умолчанию указывает на него, работает «из коробки», не нужно запускать сервер локально.
Какие проблемы это решает
LLM сами по себе не умеют рассчитывать Бацзы. Позволять модели «анализировать карту» на основе тренировочных данных — ошибка: небесные стволы, земные ветви, месячные указатели, десять божеств и определение структуры — это правила, которые должны выполняться специализированным движком.
mcp-luopan упаковывает весь движок (расчет → десять божеств → структура → удача → отчет → уточняющие вопросы) в 3 инструмента MCP. LLM больше не выдумывает, а:
Получает точные данные карты (четыре столпа / структура / удача / пять элементов / десять божеств).
Формулирует ответ на основе реальных данных (способность рассказывать истории остается за LLM, факты — за движком).
Поддерживает контекстные уточняющие вопросы (5 уточняющих вопросов / TTL 2 часа, управляется сессией на бэкенде).
Related MCP server: Chinese Fortune Analysis System (BaZi)
Типичные сценарии использования
Сценарий А: Анализ для друга в Claude Code / Claude Desktop
Вы (пользователь):
Помоги мне проанализировать мужчину, родившегося 15 марта 1991 года в 5 утра, посмотри структуру и карьеру в этом году.
Claude автоматически:
Вызывает
luopan_analyze(year=1991, month=3, day=15, hour=5, gender=1)→ получаетsession_idи полную карту.Переводит на естественный язык «структуру правильного чиновника / врожденные данные / тренд удачи / портрет партнера».
Вы уточняете «карьера в этом году» → Claude вызывает
luopan_chat(session_id, "карьера в этом году")→ получает ответ, специфичный для этой конкретной карты.
Весь процесс не требует от вас знания терминов или чтения JSON.
Сценарий Б: Пакетный анализ
Вы хотите запустить «распределение структур 100 знаменитостей»:
# 伪代码:让一个 Agent 循环调用
for person in people:
chart = call_tool("luopan_analyze", **person.birth_info)
record(person.name, chart["pattern"]["final_pattern"])Движок находится в облаке и не нагружает ваш локальный процессор; скрипт занимается только IO-оркестрацией.
Сценарий В: Встраивание в OpenClaw / Feishu Agent
Зарегистрируйте luopan в mcp.json для OpenClaw, предоставьте агенту (например, боту Feishu) доступ к этим 3 инструментам, и агент сможет рассчитывать карты и отвечать на вопросы в диалоге Feishu. Текущий локальный OpenClaw уже работает по этой модели; развертывание облачного OpenClaw — в планах (TODO).
Сценарий Г: LLM Eval / Эксперименты с промпт-инжинирингом
Хотите протестировать языковой стиль разных моделей при интерпретации карт или настроить «личность Лопаня» для агента — бэкенд всегда возвращает одни и те же фактические данные, различия моделей полностью проявляются на уровне естественного языка.
Быстрый старт: 60 секунд
1. Установка
git clone <this-repo> /Users/Neil/Projects/mcp-servers/mcp-luopan
cd /Users/Neil/Projects/mcp-servers/mcp-luopan
uv venv && uv pip install -e .Или используйте обычный venv:
python3 -m venv .venv && source .venv/bin/activate
pip install -e .После установки появится исполняемый файл mcp-luopan (в .venv/bin/).
2. Дымовой тест (проверка без MCP-хоста)
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | .venv/bin/mcp-luopanОжидается увидеть 3 инструмента: luopan_analyze / luopan_chat / luopan_session_info.
3. Регистрация в MCP-хосте
Claude Code (самый распространенный сейчас)
Отредактируйте ~/.claude.json или проектный .mcp.json:
{
"mcpServers": {
"luopan": {
"command": "/Users/Neil/Projects/mcp-servers/mcp-luopan/.venv/bin/mcp-luopan",
"env": {
"LUOPAN_API_BASE": "https://luopan.caihangao.com",
"LUOPAN_TIMEOUT_SECONDS": "60"
}
}
}
}Перезапустите Claude Code, затем откройте новый сеанс и просто скажите «посмотри мою карту с помощью Лопаня», и он вызовет инструменты.
OpenClaw (локально или в облаке)
Добавьте в ~/.openclaw/mcp.json:
"luopan": {
"command": "/Users/Neil/Projects/mcp-servers/mcp-luopan/.venv/bin/mcp-luopan",
"env": {
"LUOPAN_API_BASE": "https://luopan.caihangao.com",
"LUOPAN_TIMEOUT_SECONDS": "60"
}
}Чтобы агент мог использовать его, в tools.allow агента не нужно явно перечислять luopan_* — OpenClaw по умолчанию позволяет всем агентам видеть все серверы из mcp.json.
Claude Desktop
Отредактируйте ~/Library/Application Support/Claude/claude_desktop_config.json, структура такая же.
Семантика трех инструментов
Все инструменты возвращают JSON-строку. При ошибке возвращается
{"error": "...", "hint": "..."}, исключения LLM не выбрасываются.
luopan_analyze(year, month, day, hour, gender)
Полный анализ карты — один вызов выдает всю информацию. Перед вызовом обязательно: подтвердите с пользователем дату по солнечному календарю, час рождения (0-23) и пол (1=мужчина / 0=женщина).
Поля ответа (выборочно):
Поле | Содержание |
| 12-значный короткий ID для последующего |
| Четыре столпа (небесные стволы и земные ветви года/месяца/дня/часа) |
| Определение структуры (например, «структура правильного чиновника / врожденные данные / followup_remaining=5») |
| Трехуровневая интерпретация (карточка tier1 / подробный разбор tier2 / технический tier3) |
| Временная шкала удачи + 5 уровней благоприятности |
| Основные моменты карты (13 правил, редкость 1-3) |
| Портрет совместимого партнера (38 подструктур × 3 состояния) |
| Только для женщин (звезда мужа/детей/дворец супруга, только если gender=0) |
| Статистика пяти элементов / отношения десяти божеств |
| Сколько еще уточняющих вопросов осталось (по умолчанию 5) |
luopan_chat(session_id, question)
Уточняющий вопрос по уже существующей карте. Должен быть выполнен в течение 2 часов и не более 5 раз.
Возврат (нормализован):
{
"answer": "AI 的回答文本",
"followup_remaining": 4,
"followup_count": 1,
"max_followups": 5,
"session_id": "..."
}Когда followup_remaining == 0 или возвращается session_expired, необходимо заново вызвать luopan_analyze для создания новой карты.
luopan_session_info(session_id)
Оптимистичная проверка состояния сессии — не обращается к бэкенду. У бэкенда нет отдельного интерфейса состояния сессии, авторитетное решение принимается на основе ошибки luopan_chat. Этот инструмент предназначен для помощи агенту в локальном отслеживании того, «истекла ли сессия».
Параметры конфигурации
Переменная окружения | Значение по умолчанию | Описание |
|
| Адрес бэкенда. Для облака рекомендуется |
|
| Тайм-аут HTTP. Анализ ИИ иногда занимает 30с+, оставьте запас |
|
| Количество повторных попыток при кратковременных сетевых сбоях |
Пример полного диалога с LLM
Ниже приведена последовательность вызовов инструментов, которую LLM должна генерировать автоматически (вам нужно просто вести обычный диалог):
[user] 我哥 1985 年 8 月 12 日中午 12 点出生,男的,最近老换工作,帮我看看是不是格局问题?
[assistant] (调用 luopan_analyze year=1985 month=8 day=12 hour=12 gender=1)
[tool result]
session_id=a1b2c3d4e5f6
pattern=偏财格 / 败格有救(柳暗花明)
...
[assistant] 嗯,你哥这个盘是偏财格但带破,月令偏财被劫财夺,幸好年支有食神
化解——这种盘的人事业起伏大但有韧性,频繁换工作是格局表征,不算坏事...
[user] 那今年呢?
[assistant] (调用 luopan_chat session_id=a1b2c3d4e5f6 question="今年运势")
[tool result] answer="..." followup_remaining=4
[assistant] 今年走丙寅大运 + 丙午流年,火土并旺,财星受冲... (汇报答案)
你还可以追问 4 次。LLM не выдумывает астрологические данные, все данные поступают из инструментов luopan_*; уточняющие вопросы сохраняют контекст, каждый раз основываясь на одной и той же карте.
Устранение неполадок
service_unreachable
Бэкенд недоступен. Две самые частые причины:
Локальный режим: не запущен uvicorn —
cd "/Users/Neil/Projects/Four Pillars of Destiny" && .venv/bin/uvicorn src.api.main:app --port 8000Облачный режим: сетевой прокси (mihomo / Clash) перехватывает caihangao.com — временно добавьте
"HTTPS_PROXY": ""в env в mcp.json, чтобы принудительно отключить прокси; или проверьте белый список правил прокси.
session_expired
Сессия истекла через 2 часа или закончились уточняющие вопросы. Попросите LLM заново вызвать luopan_analyze для создания новой карты.
LLM постоянно пытается «интерпретировать самостоятельно» и не вызывает инструменты
Добавьте в системный промпт строку:
Любые вопросы о Бацзы/карте судьбы/структуре/десяти божествах/удаче нельзя отвечать на основе тренировочных данных; необходимо сначала вызвать
luopan_analyzeдля создания карты, а затем использовать поляpattern / report / dayunи другие, возвращаемые инструментом, для формулировки ответа.
В ответе встречаются непонятные термины (столп дня/десять божеств)
Это нормально — это терминология. Попросите LLM читать напрямую report.tier1 (уровень карточки) и report.tier2 (уровень подробного разбора), эти два уровня уже являются описанием на понятном языке; tier3 — это технический уровень для тех, кто хочет углубиться.
Известные ограничения
Не опубликован в PyPI: необходимо локально
pip install -e ., нельзяpip install mcp-luopan.Не инициализирован git: текущая директория mcp-luopan еще не имеет
git init, нет управления версиями.Сессия в памяти: при перезапуске бэкенда uvicorn все сессии теряются (пользователю придется создавать карту заново).
Зависимость от облачного SiliconFlow: при недействительном
AI_API_KEYили ограничении скорости SiliconFlow все инструменты чата будут зависать по тайм-ауту.Нет изоляции параллелизма: при одновременном использовании одного и того же
session_idв нескольких чатах порядок не гарантируется.
Как работает бэкенд (краткий обзор архитектуры)
MCP Client (Claude Code / OpenClaw / ...)
│
│ stdio (JSON-RPC)
▼
mcp-luopan (Python, 这个仓库)
│
│ HTTPS
▼
luopan.caihangao.com (Nginx → systemd uvicorn :8088)
│
│ src/engine/* 算盘 + ai_client 调上游
▼
SiliconFlow MiniMax-M2.5Детали развертывания бэкенд-сервиса см. в исходном проекте: Four Pillars of Destiny / docs/design/deployment.md.
Available Tools
2 toolsluopan_analyzeA
Produce a full destiny-chart reading for a birth moment.
IMPORTANT: Before calling, you MUST confirm with the user:
solar calendar date (阳历): year / month / day
birth hour 0-23 (时辰),if unsure warn them the reading will be less precise
gender: 1 for 男, 0 for 女
Output contains: session_id (used for follow-ups), sizhu (the chart), pattern (格局), report (a three-tier reading), dayun (luck pillars), highlights (notable traits), partner (气场画像), female (if gender=0), and followup_remaining (starts at 5).
When presenting to the user, translate technical terms (e.g. 十神, 格局名称) into plain language like "气场 / 画像 / 此局". The public persona is 罗盘 (fengshui compass), never expose the words 八字 / 子平.
Sessions expire in 2 hours and allow up to 5 follow-up questions via luopan_chat.
Args: year: Birth year, e.g. 1991 month: Birth month 1-12 day: Birth day 1-31 hour: Birth hour 0-23 gender: 1 = 男, 0 = 女
| Name | Required | Description | Default |
|---|---|---|---|
| year | Yes | ||
| month | Yes | ||
| day | Yes | ||
| hour | Yes | ||
| gender | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Despite no annotations, the description fully discloses behavioral traits: outputs, session expiration (2 hours), follow-up limit (5), and presentation instructions (translate terms, use persona).
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Well-structured with clear sections (title, note, output, presentation, session info). Slightly lengthy but every sentence adds value; no wasted words.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the output schema exists, the description still adds valuable context about follow-ups, session expiration, and output fields. No notable gaps.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, but the description explains all 5 parameters with examples and ranges (e.g., year e.g. 1991, month 1-12, day 1-31, hour 0-23, gender 1=男, 0=女). This adds complete meaning beyond the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states it produces a full destiny-chart reading for a birth moment. It distinguishes from the sibling tool luopan_chat by mentioning follow-up capability.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly lists pre-call confirmations required from the user, warns about less precise hour, and explains session expiration and follow-up limit. Provides clear guidance on when to use this tool vs luopan_chat.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
luopan_chatA
Ask a follow-up question against an existing chart-reading session.
Session_id comes from a prior luopan_analyze call. The backend enforces a 2-hour TTL and a 5-question cap; when either is hit, call luopan_analyze again to open a new session.
Returns (normalized): answer: the AI reply text followup_remaining: questions you still have left after this one followup_count: questions used so far (incl. this one) max_followups: hard cap (5) session_id: echoed back
When followup_remaining == 0 or this call returns session_expired,
the next turn must call luopan_analyze to open a fresh session.
When followup_remaining == 1, warn the user before they spend it.
Args: session_id: The session_id returned by luopan_analyze question: The user's follow-up question (specific events / years / topics yield better answers than vague "is my fate good")
| Name | Required | Description | Default |
|---|---|---|---|
| session_id | Yes | ||
| question | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description fully discloses behavior: backend-enforced limits, return fields with meanings, and lifecycle management. It clearly states what happens when limits are hit, meeting the full burden for behavioral transparency.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-structured: purpose statement, runtime constraints, structured return fields, and actionable usage notes. Each sentence earns its place; no redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the output schema not provided as structured input, the description enumerates return fields and their meanings. It fully explains the session lifecycle, restrictions, and expected behavior, providing complete context for an AI to use the tool correctly within the sibling ecosystem.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 0%, so description must add meaning. It explains session_id comes from prior luopan_analyze, and question provides usage tips ('specific events/years/topics yield better answers'). This adds significant value beyond the bare schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: 'Ask a follow-up question against an existing chart-reading session.' It specifies the resource (session) and verb (ask), and distinguishes from sibling tool luopan_analyze, which starts new sessions.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly guides when to use (follow-up questions) and when not to (session expired or followup_remaining==0, then call luopan_analyze). It also details constraints (2-hour TTL, 5-question cap) and gives actionable advice (warn user when remaining==1).
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
2 tool updates
v0.1.0- First observed
luopan_analyze - First observed
luopan_chat
TDQS
Scored across 2 tools
The two tools have clearly distinct purposes: one creates a new chart-reading session, the other handles follow-up questions within an existing session. There is no overlap or ambiguity.
Both tools follow a consistent verb_noun pattern with the prefix 'luopan_' (luopan_analyze, luopan_chat) in snake_case, making them predictable and easy to understand.
With only 2 tools, the server is tightly scoped to its purpose: initial analysis and follow-up chat. No unnecessary tools exist, and the count is perfect for the functionality provided.
The tool set covers the complete lifecycle: creating a session with a full chart reading and asking up to 5 follow-up questions. No obvious gaps exist for the intended domain.
Maintenance
Related MCP Connectors
Generate BaZi charts from birth details. Explore Four Pillars, solar terms, and Luck Pillars for d…
BaZi four pillars, Chinese zodiac, lunisolar calendar and almanac days for AI agents.
BaZi (Chinese Four Pillars) chart calculator. Structured chart data only, no predictions.
Free BaZi, I Ching, tarot, Zi Wei and bilingual learning tools with transparent methods. No API key.
61
Related MCP Servers
- AlicenseAqualityBmaintenanceEnables AI tools to perform Chinese fortune-telling analysis including Ziwei Doushu (Purple Star Astrology) and Bazi (Four Pillars) chart generation, fortune reading, and element analysis. Supports multiple calendar systems and output formats for comprehensive divination services.78 npm6MIT
- AlicenseNot gradedqualityDmaintenanceEnables traditional Chinese fortune-telling through BaZi (Four Pillars) analysis, including solar/lunar date conversion, Five Element balance calculations, Ten Gods deduction, and destiny interpretation for metaphysics applications.23 npmMIT
- AlicenseNot gradedqualityDmaintenanceProvides accurate Chinese Bazi (八字) fortune-telling calculations including birth chart analysis, destiny forecasting, and Chinese calendar information. Addresses inaccuracies in existing AI fortune-telling tools by delivering precise Bazi data for personality analysis and metaphysical insights.343 npmISC
- AlicenseAqualityCmaintenanceEnables AI agents to perform Chinese metaphysics calculations including BaZi charts, Tong Shu indicators, solar terms, and more, using a verified engine with 740+ tests.88MIT