Skip to main content
Glama
ZoezoeCookie

mcp-luopan

by ZoezoeCookie

mcp-luopan

Convierte "Luopan" —el cálculo de cartas astrales basado en el método de格局 (geju) de Ziping Zhenquan— en un conjunto de herramientas MCP (Model Context Protocol), permitiendo que cualquier cliente MCP (Claude Code / Claude Desktop / OpenClaw / Cursor / Agente LLM propio) pueda calcular cartas, leerlas y responder preguntas de seguimiento en la conversación.

La entrada en la nube ya está disponible: https://luopan.caihangao.com. MCP apunta a ella por defecto, lista para usar, sin necesidad de iniciar servicios localmente.


¿Qué problema resuelve?

Los LLM por sí mismos no saben calcular Bazi. Hacer que el modelo "analice una carta" basándose directamente en su conocimiento de entrenamiento es incorrecto: los tallos y ramas, los meses, los diez dioses y la determinación de patrones son cálculos basados en reglas que deben ser realizados por un motor especializado.

mcp-luopan encapsula todo el motor (cálculo de carta → diez dioses → patrones → grandes ciclos → informe → preguntas de seguimiento) en 3 herramientas MCP, para que el LLM no invente, sino que:

  1. Obtenga datos precisos de la carta (cuatro pilares / patrones / grandes ciclos / cinco elementos / diez dioses)

  2. Organice el lenguaje basándose en datos reales (la capacidad de contar historias se deja al LLM, los hechos al motor)

  3. Admita preguntas de seguimiento con contexto (5 preguntas / TTL de 2 horas, gestionado por la sesión del backend)


Related MCP server: Chinese Fortune Analysis System (BaZi)

Escenarios de uso típicos

Escenario A: Analizar una carta para un amigo en Claude Code / Claude Desktop

Tú (usuario):

Ayúdame a analizar a un chico nacido el 15 de marzo de 1991 a las 5 de la mañana, mira su patrón y su carrera este año.

Claude automáticamente:

  1. Llama a luopan_analyze(year=1991, month=3, day=15, hour=5, gender=1) → obtiene el session_id y la carta completa

  2. Traduce para ti en lenguaje natural el "Patrón de Oficial Directo / Destino Celestial / Tendencia de los Grandes Ciclos / Perfil de pareja"

  3. Tú preguntas "¿carrera este año?" → Claude llama a luopan_chat(session_id, "carrera este año") → obtiene la respuesta específica para esta carta

En todo el proceso no necesitas entender terminología ni ver JSON.

Escenario B: Análisis por lotes

Quieres ejecutar una "distribución de patrones de 100 celebridades":

# 伪代码:让一个 Agent 循环调用
for person in people:
    chart = call_tool("luopan_analyze", **person.birth_info)
    record(person.name, chart["pattern"]["final_pattern"])

El motor está en la nube, no ocupa CPU de tu máquina; el script solo se encarga de la orquestación de E/S.

Escenario C: Integración en OpenClaw / Agente de Feishu

Registra luopan en el mcp.json de OpenClaw, autoriza estas 3 herramientas a un agente (por ejemplo, un bot de Feishu), y el agente podrá calcular cartas y responder preguntas en la conversación de Feishu. Actualmente, OpenClaw local ya ha funcionado bajo este modelo; el despliegue de OpenClaw en la nube está en TODO.

Escenario D: Evaluación de LLM / Experimentos de ingeniería de prompts

Quieres probar el estilo de lenguaje de diferentes modelos al interpretar cartas, o ajustar la "personalidad de Luopan" para un agente: el backend siempre devuelve los mismos datos factuales, y las diferencias del modelo quedan totalmente expuestas en el nivel del lenguaje natural.


Inicio rápido: 60 segundos para empezar

1. Instalar

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 .

O usa un venv normal:

python3 -m venv .venv && source .venv/bin/activate
pip install -e .

Una vez instalado, tendrás el ejecutable mcp-luopan (en .venv/bin/).

2. Prueba de humo (verificación sin entrar al host MCP)

echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | .venv/bin/mcp-luopan

Se espera ver 3 herramientas: luopan_analyze / luopan_chat / luopan_session_info.

3. Registrar en un host MCP

Claude Code (el más común actualmente)

Edita ~/.claude.json o el .mcp.json a nivel de proyecto:

{
  "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"
      }
    }
  }
}

Reinicia Claude Code, luego abre una nueva sesión y di directamente "usa Luopan para mirarme una carta", y llamará a la herramienta.

OpenClaw (local o en la nube)

Añádelo a ~/.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"
  }
}

Para que un agente lo use, tools.allow del agente no necesita listar explícitamente luopan_*: OpenClaw permite por defecto que todos los agentes vean todos los servidores en mcp.json.

Claude Desktop

Edita ~/Library/Application Support/Claude/claude_desktop_config.json, la estructura es la misma.


Semántica de las tres herramientas

Todas las herramientas devuelven cadenas JSON. En caso de error, devuelven {"error": "...", "hint": "..."}, sin lanzar excepciones al LLM.

luopan_analyze(year, month, day, hour, gender)

Análisis completo de la carta: una llamada produce toda la información. Antes de llamar, debes: confirmar con el usuario la fecha solar, la hora de nacimiento (0-23) y el género (1=hombre / 0=mujer).

Campos de retorno (extracto):

Campo

Contenido

session_id

ID corto de 12 dígitos, usado para luopan_chat posterior

sizhu

Cuatro pilares (tallos y ramas de los pilares de año/mes/día/hora)

pattern

Determinación del patrón (ej. "Patrón de Oficial Directo / Destino Celestial / followup_remaining=5")

report

Interpretación en tres niveles (tarjeta tier1 / lectura detallada tier2 / técnica tier3)

dayun

Línea de tiempo de los grandes ciclos + 5 niveles de fortuna

highlights

Puntos destacados de la carta (13 reglas, rareza 1-3)

partner

Perfil de pareja complementaria (38 sub-patrones × 3 mapeos de estado)

female

Exclusivo para mujeres (estrella del esposo/hijos/palacio conyugal, solo si gender=0)

wuxing / shishen

Estadísticas de los cinco elementos / relaciones de los diez dioses

followup_remaining

Cuántas preguntas de seguimiento quedan (por defecto 5)

luopan_chat(session_id, question)

Pregunta de seguimiento sobre una carta existente. Debe realizarse dentro de las 2 horas y con un máximo de 5 preguntas.

Retorno (normalizado):

{
  "answer": "AI 的回答文本",
  "followup_remaining": 4,
  "followup_count": 1,
  "max_followups": 5,
  "session_id": "..."
}

Cuando followup_remaining == 0 o devuelve session_expired, se debe llamar de nuevo a luopan_analyze para iniciar una nueva carta.

luopan_session_info(session_id)

Consulta optimista del estado de la sesión: no contacta al backend. El backend no tiene una interfaz de estado de sesión independiente, la determinación autorizada depende del error de luopan_chat. Esta herramienta es una ayuda para que el agente mantenga localmente "si la sesión ha expirado".


Parámetros de configuración

Variable de entorno

Valor por defecto

Descripción

LUOPAN_API_BASE

http://127.0.0.1:8000

Dirección del backend. Para la nube se recomienda https://luopan.caihangao.com; para depuración local usa http://127.0.0.1:8000 iniciando uvicorn

LUOPAN_TIMEOUT_SECONDS

60

Tiempo de espera HTTP. El análisis de IA a veces tarda más de 30s, deja suficiente margen

LUOPAN_HTTP_RETRIES

1

Número de reintentos por fluctuaciones breves de red


Ejemplo de una conversación completa con LLM

La siguiente es la secuencia de llamadas a herramientas que el LLM debería generar automáticamente (tú solo necesitas conversar normalmente):

[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 次。

El LLM no inventa la numerología, todos los datos provienen de la herramienta luopan_*; las preguntas de seguimiento mantienen el contexto, cada vez se basan en esta misma carta.


Solución de problemas

service_unreachable

Backend inalcanzable. Los dos casos más comunes:

  • Modo local sin uvicorn iniciado: cd "/Users/Neil/Projects/Four Pillars of Destiny" && .venv/bin/uvicorn src.api.main:app --port 8000

  • Modo nube con proxy de red (mihomo / Clash) interceptando caihangao.com: añade temporalmente "HTTPS_PROXY": "" en el env de mcp.json para forzar el cierre del proxy; o revisa la lista blanca de reglas del proxy.

session_expired

La sesión superó las 2h o se agotaron las preguntas. Haz que el LLM llame de nuevo a luopan_analyze para iniciar una nueva carta.

El LLM siempre quiere "interpretar por sí mismo" y no llama a la herramienta

Añade una línea al System prompt:

Cualquier pregunta sobre Bazi/cartas/patrones/diez dioses/grandes ciclos, no puedes responderla basándote en datos de entrenamiento; debes llamar primero a luopan_analyze para iniciar la carta, y luego usar los campos pattern / report / dayun devueltos por la herramienta para organizar el lenguaje.

Aparecen términos como pilar del día/diez dioses que no se entienden

Es normal: son términos técnicos. Haz que el LLM lea directamente report.tier1 (nivel tarjeta) y report.tier2 (nivel lectura detallada), esas dos capas ya son narrativas en chino para personas; tier3 es la capa técnica para quienes deseen profundizar.


Limitaciones conocidas

  • No publicado en PyPI: se debe hacer pip install -e . localmente, no se puede hacer pip install mcp-luopan

  • Sin git: el directorio actual de mcp-luopan aún no tiene git init, no hay gestión de versiones

  • Sesión en memoria: si el backend uvicorn se reinicia, se pierden todas las sesiones (el usuario debe reiniciar la carta)

  • Dependencia de SiliconFlow en la nube: cuando AI_API_KEY caduca o SiliconFlow limita la tasa, todas las herramientas de chat se bloquearán por timeout

  • Sin aislamiento de concurrencia: no se garantiza el orden cuando el mismo session_id es consultado varias veces simultáneamente


Cómo funciona el backend (vistazo a la arquitectura)

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

Para detalles sobre el despliegue del servicio backend, consulta el proyecto original: Four Pillars of Destiny / docs/design/deployment.md.

Available Tools

2 tools
luopan_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 = 女

ParametersJSON Schema
NameRequiredDescriptionDefault
yearYes
monthYes
dayYes
hourYes
genderYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.9/5.0
Behavior5/5

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.

Conciseness4/5

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.

Completeness5/5

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.

Parameters5/5

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.

Purpose5/5

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.

Usage Guidelines5/5

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")

ParametersJSON Schema
NameRequiredDescriptionDefault
session_idYes
questionYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A5/5.0
Behavior5/5

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.

Conciseness5/5

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.

Completeness5/5

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.

Parameters5/5

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.

Purpose5/5

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.

Usage Guidelines5/5

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.

  1. 2 tool updatesv0.1.0
    • First observedluopan_analyze
    • First observedluopan_chat

TDQS

A5/5.0

Scored across 2 tools

Disambiguation5/5

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.

Naming Consistency5/5

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.

Tool Count5/5

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.

Completeness5/5

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

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    B
    maintenance
    Enables 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.
    7
    8 npm
    6
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables 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 npm
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides 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 npm
    ISC
  • A
    license
    A
    quality
    C
    maintenance
    Enables AI agents to perform Chinese metaphysics calculations including BaZi charts, Tong Shu indicators, solar terms, and more, using a verified engine with 740+ tests.
    8
    8
    MIT