# TuViMCP

> Tử Vi Horoscope MCP Server - a Python MCP server for generating, analyzing, and managing Vietnamese Tử Vi astrology charts with clean JSON output for LLM agents.

- **Type:** MCP server
- **Install:** `agentstack add mcp-nmhaaa3218-tuvimcp`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [nmhaaa3218](https://agentstack.voostack.com/s/nmhaaa3218)
- **Installs:** 0
- **Category:** [Developer Tools](https://agentstack.voostack.com/c/developer-tools)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [nmhaaa3218](https://github.com/nmhaaa3218)
- **Source:** https://github.com/nmhaaa3218/TuViMCP
- **Website:** https://pypi.org/project/tuvi-mcp-server/

## Install

```sh
agentstack add mcp-nmhaaa3218-tuvimcp
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Tu Vi Horoscope MCP Server

[](https://github.com/nmhaaa3218/TuViMCP/actions/workflows/ci.yml)
[](https://opensource.org/licenses/MIT)

[](https://glama.ai/mcp/servers/nmhaaa3218/TuViMCP)

This is a Model Context Protocol (MCP) server developed in Python that calculates and manages Vietnamese "Tử Vi" horoscope charts. It is optimized to output clean, structured JSON data that LLM agents can easily read, interpret, and explain to users.

---

## English Documentation

### Quick Links
- [Contributing Guidelines](CONTRIBUTING.md)
- [Changelog / Release History](CHANGELOG.md)
- [Example JSON Outputs & Scripts](examples/)

### Features
- **Horoscope Generation:** Converts Solar or Lunar birth dates and times into a full Tử Vi chart (Thiên Bàn and Địa Bàn with 12 houses and over 100 stars).
- **High-Quality Image Rendering:** Generates beautiful, print-ready chart images with element-based colored text (Green for Wood, Red for Fire, Yellow for Earth, Gray for Metal, Blue for Water), custom badge boxes for Tuần & Triệt, and geometric connecting lines highlighting the Mệnh and Thân relationship.
- **Vận Hạn (Transit Analysis):** Computes transit stars (Lưu tinh) and maps the active 10-year period (Đại Hạn), yearly period (Tiểu Hạn), and monthly period (Nguyệt Hạn) for any target year and month (e.g., 2026).
- **Local Persistence:** Save, retrieve, list, and delete horoscope charts from a local SQLite database (`tuvi_horoscopes.db`).
- **Flexible Hour Mapping:** Automatically maps calendar hours (e.g., "14:30") or string names (e.g., "Ngọ", "Tý") to the correct Earthly Branch hour index.
- **Local Inlining (Independent):** Includes the core `ansaotuvi` calculation logic internally with custom Tuần/Triệt double-cung fixes.

### Known Limitations & Assumptions
- **Timezone Assumption:** Calculations default to the Vietnamese local timezone (GMT+7). Birth details outside this timezone must be converted beforehand.
- **Calendar Boundaries:** The core calculations are stable for modern birth years, but traditional leap months (tháng nhuận) follow standard Vietnamese lunar calendar mappings (Hoang Nam Dia methodology) which might vary in historical or remote future years.
- **Calculations School (Phái):** Star distributions follow standard consensus calculations. Customizable star weight/distributions (different schools like Nam Phái vs. Bắc Phái vs. custom configurations) are not supported.

### Accuracy, Methodology & Tradition Disclaimer
> [!NOTE]
> **Traditional Calculations Disclaimer:** Vietnamese "Tử Vi" is a highly rich astrological methodology with various traditional schools (e.g., Nam Phái vs. Bắc Phái). Calculation parameters, star rankings, element determinations, and interpretations may differ depending on the specific lineage or school. The output generated by this tool is calculated strictly according to standard consensus computational logic and should be treated as a computational reference rather than a definitive astrological interpretation.

### Installation

You can install `tuvi-mcp-server` directly from PyPI:
```bash
pip install tuvi-mcp-server
```

### Development & Contribution Setup

If you want to contribute to the package or run unit tests, set up a local development environment:

1. **Create Virtual Environment:**
   ```bash
   python3 -m venv .venv
   ```

2. **Install Package in Editable Mode:**
   ```bash
   .venv/bin/pip install --upgrade pip
   .venv/bin/pip install -e ".[test]"
   ```

3. **Running Tests:**
   Verify your local setup by running the test suite:
   ```bash
   .venv/bin/pytest
   ```

### How to Run

#### 1. Stdio Mode (Default for Claude Desktop & Cursor)
```bash
.venv/bin/tuvi-mcp
```

#### 2. Streamable HTTP Mode (For Remote & Cloud Deployments)
To run the server over HTTP (runs on port `1850` by default):
```bash
.venv/bin/tuvi-mcp --http
```
Override host and port:
```bash
.venv/bin/tuvi-mcp --http --host 127.0.0.1 --port 1850
```

### Tool API Reference

All tools run locally inside the MCP environment. They require no external authentication or network rate limiting.

#### 1. `generate_horoscope`
Generates a full Tử Vi chart from raw birth details, with optional high-quality chart image rendering.
* **Purpose & Comparison:** Use this for on-the-fly, unsaved calculations. Use `get_saved_horoscope` to load previously saved profiles.
* **Side Effects:** If `generate_image` is `True`, renders a PNG file to a temporary location on the local filesystem and returns its path.
* **Arguments:**
  - `name` (string): Person's name (default: "Khách").
  - `day` (integer): Day of birth (1-31).
  - `month` (integer): Month of birth (1-12).
  - `year` (integer): Year of birth.
  - `hour_val` (string): Hour of birth (e.g., "14:30", "Ngọ", "Tý", or branch index `1-12`).
  - `gender_val` (string): Gender ("Nam" or "Nữ", case-insensitive).
  - `is_solar` (boolean): True for Solar, False for Lunar (default: True).
  - `current_year` (integer, optional): Year to inspect transit stars/Vận Hạn for (defaults to current year).
  - `generate_image` (boolean, optional): Whether to generate and return the high-quality chart image along with the chart data (default: True).
* **Return Value:** 
  - If `generate_image` is `True`, returns a list containing `[Image, chart_data]` (where `Image` is a FastMCP Image content block pointing to the generated PNG).
  - If `generate_image` is `False`, returns the raw JSON dictionary `chart_data` directly. Contains keys: `thien_ban` (demographics, pillars, element, destiny) and `dia_ban` (12 houses with stars).
  - Returns `{"error": "error_message"}` if calculations fail.

#### 2. `get_van_han`
Calculates yearly transit stars and active houses (major, yearly, and monthly periods) for a target period.
* **Purpose & Comparison:** Use this tool to perform predictive transit analysis for a specific target timeframe.
* **Side Effects:** None (read-only calculation).
* **Calendar Prerequisites:** **CRITICAL:** `current_year` and `current_month` represent the **Lunar** year and month. If inspecting a Solar timeframe (e.g. 'October 2026'), you **MUST** convert it using `convert_calendar` first.
* **Arguments:**
  - `name`, `day`, `month`, `year`, `hour_val`, `gender_val`, `is_solar` (same as birth parameters above).
  - `current_year` (integer): Target Lunar year to inspect (default: current year).
  - `current_month` (integer): Target Lunar month to inspect (1-12, default: 1).
* **Return Value:** A dictionary with keys `person_details` (Can-Chi), `target_period` (resolved age and target), `transit_stars`, `dai_han`, and `tieu_han`. Returns `{"error": "error_message"}` if input details are invalid.

#### 3. `save_horoscope`
Saves birth details to the SQLite database.
* **Purpose & Comparison:** Saves birth details so they can be loaded later without manually entering birth details again.
* **Side Effects:** Write operation. Inserts a new record into the SQLite database (`~/.tuvi_mcp/tuvi_horoscopes.db`).
* **Arguments:**
  - `name`, `day`, `month`, `year`, `hour_val`, `gender_val`, `is_solar`, `notes` (string, optional).
* **Return Value:** A dictionary `{"message": "Successfully saved...", "id": }`. Returns `{"error": "error_message"}` on validation/database failure.

#### 4. `list_saved_horoscopes`
Lists all saved records from the database.
* **Purpose & Comparison:** Discover saved horoscope profiles before loading/deleting them.
* **Side Effects:** Read-only database query.
* **Return Value:** A list of profile dictionaries containing `id`, `name`, birth details, `notes`, and `created_at`. Returns a list with an error dictionary `[{"error": "error_message"}]` on query failures.

#### 5. `get_saved_horoscope`
Retrieves a saved record and generates its chart.
* **Purpose & Comparison:** Loads a saved profile. Useful to avoid re-entering raw parameters.
* **Side Effects:** Read-only database query and base chart calculation.
* **Arguments:**
  - `horoscope_id` (integer, optional): The database ID of the record.
  - `name` (string, optional): The name of the record.
  - *Interaction:* At least one must be provided. If both are supplied, `horoscope_id` takes precedence. If only `name` is provided, retrieves the *latest* matching record.
* **Return Value:** The full horoscope chart dictionary structure (`chart_data`) with database metadata added under a `"metadata"` key (`{"id": , "notes": , "created_at": }`). Returns `{"error": "Horoscope record not found"}` if not found.

#### 6. `delete_saved_horoscope`
Deletes a record from the database.
* **Purpose & Comparison:** Permanently removes a profile from the database.
* **Side Effects:** Destructive write operation. Cannot be automatically undone.
* **Arguments:**
  - `horoscope_id` (integer): The database ID of the record to delete.
* **Return Value:** A success message dictionary `{"message": "Successfully deleted..."}`. Returns `{"error": "No horoscope record found with ID..."}` if missing.

#### 7. `convert_calendar`
Converts a date between the Solar (Dương lịch) and Lunar (Âm lịch) calendars.
* **Purpose & Comparison:** Translate dates back and forth. Crucial for converting Solar target timeframes to Lunar periods before calling `get_van_han`.
* **Side Effects:** None (mathematical calculation).
* **Arguments:**
  - `day` (integer): Day of the date to convert.
  - `month` (integer): Month of the date to convert.
  - `year` (integer): Year of the date to convert.
  - `from_solar` (boolean): `True` to convert Solar -> Lunar (default), `False` to convert Lunar -> Solar.
  - `lunar_leap` (boolean): Only used if `from_solar` is `False`. `True` if the input lunar month is a leap month (tháng nhuận).
  - `timezone` (integer): Timezone offset (default: 7 for Vietnam/ICT).
* **Return Value:**
  - Converted date parameters: `day`, `month`, `year` of target calendar, plus a `leap` boolean (specifically indicating if the Lunar month is a leap month).
  - Returns `{"error": "error_message"}` if date arguments fail validation.

### Example Tool Call & JSON Outputs

To illustrate the structured responses, here is an example of what the server outputs when calling the core tools.

#### 1. Horoscope Generation Output Summary (`generate_horoscope`)

When calling `generate_horoscope(name="Nguyễn Văn A", day=10, month=6, year=1995, hour_val="14:30", gender_val="Nam", is_solar=true)`, the server outputs a structured JSON response containing `thien_ban` (person information) and `dia_ban` (the list of 12 houses and their stars).

**Response Snippet:**
```json
{
  "thien_ban": {
    "ten": "Nguyễn Văn A",
    "gioi_tinh": "Nam",
    "ngay_duong": "10/6/1995",
    "ngay_am": "13/5/1995",
    "gio_sinh": "Đinh Mùi",
    "chi_gio_sinh": "Mùi",
    "am_duong_menh": "Âm dương thuận lý",
    "hanh_cuc": 5,
    "ten_cuc": "Thổ ngũ Cục",
    "menh_chu": "Cự môn",
    "than_chu": "Thiên tướng",
    "ban_menh": "SƠN ÐẦU HỎA"
  },
  "dia_ban": [
    {
      "cung_so": 1,
      "cung_ten": "Mậu Tý",
      "hanh_cung": "Thủy",
      "cung_chu": "Phụ mẫu",
      "dai_han": 115,
      "tieu_han": "Tuất",
      "sao": [
        {
          "id": 9,
          "name": "Tham lang",
          "element": "T",
          "type": 1,
          "attribute": "Hãm địa"
        }
      ]
    }
    // ... 11 other cungs (houses)
  ]
}
```

*For the complete output, see [examples/sample_horoscope_output.json](examples/sample_horoscope_output.json).*

#### 2. Vận Hạn Analysis Output Summary (`get_van_han`)

When calling `get_van_han(...)` for a target year/month, it tracks yearly transit stars (sao lưu) and flags the active houses:

**Response Snippet:**
```json
{
  "person_details": {
    "name": "Nguyễn Văn A",
    "element": "H",
    "destiny_cuc": "Thổ ngũ Cục"
  },
  "target_period": {
    "current_year": 2026,
    "current_year_can_chi": "Bính Ngọ",
    "current_month_lunar": 5,
    "current_age": 32
  },
  "transit_stars": [
    {"name": "Lưu Thái Tuế", "cung_so": 7, "chi": "Ngọ"},
    {"name": "Lưu Lộc Tồn", "cung_so": 9, "chi": "Thân"}
    // ... other transit stars
  ],
  "dai_han": {
    "cung_so": 10,
    "cung_chu": "Tử tức",
    "dai_han": 35,
    "transit_stars": []
  },
  "tieu_han": {
    "cung_so": 7,
    "cung_chu": "Tật ách",
    "tieu_han": "Ngọ",
    "transit_stars": ["Lưu Thái Tuế"]
  }
}
```

*For the complete output, see [examples/sample_van_han_output.json](examples/sample_van_han_output.json).*

### Client Integration Examples

#### Claude Desktop Configuration
Add the following to your `claude_desktop_config.json` file:

```json
{
  "mcpServers": {
    "tuvi-horoscope": {
      "command": "/path/to/TuViMCP/.venv/bin/tuvi-mcp",
      "args": []
    }
  }
}
```

#### Cursor Integration
Go to Settings -> Features -> MCP, click "+ Add New MCP Server":
- **Name:** TuViMCP
- **Type:** command
- **Command:** `/path/to/TuViMCP/.venv/bin/tuvi-mcp`

---
---

# Máy chủ MCP Luận giải Lá số Tử Vi

Đây là máy chủ Model Context Protocol (MCP) được phát triển bằng Python, dùng để lập và quản lý lá số Tử Vi theo hệ Việt Nam. Kết quả được chuẩn hóa dưới dạng JSON sạch, có cấu trúc rõ ràng, giúp các LLM agent dễ dàng đọc, phân tích và diễn giải lại cho người dùng.

---

## Tài liệu Tiếng Việt

### Đường Dẫn Nhanh
- [Hướng dẫn Đóng góp](CONTRIBUTING.md)
- [Lịch sử Thay đổi](CHANGELOG.md)
- [Thư mục Output JSON mẫu & Mã nguồn ví dụ](examples/)

### Tính năng chính

* **Lập lá số Tử Vi:** Hỗ trợ chuyển đổi ngày giờ sinh Dương lịch hoặc Âm lịch thành lá số Tử Vi đầy đủ, bao gồm Thiên Bàn, Địa Bàn, 12 cung và hơn 100 sao.

* **Vẽ lá số chất lượng cao:** Xuất ảnh lá số sắc nét tỷ lệ chuẩn phù hợp in ấn, tự động tô màu chữ theo ngũ hành của sao (Mộc: Xanh lá, Hỏa: Đỏ, Thổ: Vàng cam, Kim: Xám, Thủy: Xanh dương), vẽ nhãn bao nổi bật cho cung bị Tuần/Triệt, vẽ các đường nối hình học làm nổi bật tam hợp chiếu mệnh thân.

* **Xem Vận Hạn:** Tính toán các sao lưu động như Lưu Thái Tuế, Lưu Lộc Tồn, v.v., đồng thời xác định các cung hạn đang kích hoạt gồm Đại Hạn 10 năm, Tiểu Hạn theo năm và Nguyệt Hạn theo tháng cho bất kỳ năm/tháng cần xem nào, ví dụ năm 2026.

* **Lưu trữ cục bộ:** Hỗ trợ lưu, truy xuất, liệt kê và xóa thông tin lá số thông qua cơ sở dữ liệu SQLite cục bộ (`tuvi_horoscopes.db`).

* **Tự động quy đổi giờ sinh:** Có thể tự động chuyển đổi giờ theo đồng hồ, ví dụ `"14:30"`, hoặc tên giờ truyền thống, ví dụ `"Ngọ"`, `"Tý"`, sang đúng chỉ số Địa Chi tương ứng.

* **Tích hợp logic tính toán nội bộ:** Bao gồm sẵn phần lõi tính toán từ `ansaotuvi`, đồng thời bổ sung các chỉnh sửa riêng cho trường hợp Tuần/Triệt bao phủ hai cung.

### Hạn chế hiện tại & Giả định
- **Giả định múi giờ:** Mặc định tính toán theo múi giờ Việt Nam (GMT+7). Mọi thông tin giờ sinh ở múi giờ khác cần được quy đổi về GMT+7 trước khi truyền vào.
- **Giới hạn lịch pháp:** Các phép tính toán âm dương lịch ổn định và chính xác cao với các năm sinh thời hiện đại. Thuật toán chuyển đổi lịch âm dựa trên phương pháp của Hoàng Nam Địa (HND), có thể có sai lệch nhỏ ở một số năm nhuận quá khứ xa hoặc tương lai xa.
- **Hệ phái an sao:** Thuật toán an sao theo quy chuẩn chung phổ biến tại Việt Nam. Dự án hiện chưa hỗ trợ cấu hình tùy biến trọng số sao hoặc các cách an sao khác nhau của các hệ phái khác (như Nam phái vs Bắc phái vs tự chọn).

### Tuyên bố miễn trừ trách nhiệm về Lịch pháp & Học phái
> [!NOTE]
> **Tuyên bố về các trường phái tính toán:** Tử Vi Việt Nam là một bộ môn học thuật vô cùng phong phú với nhiều trường phái truyền thống khác nhau (như Nam Phái, Bắc Phái). Các phương pháp an sao, phân định thứ hạng sao, ngũ hành bản mệnh hay luận giải có thể có sự khác biệt nhất định tùy thuộc vào từng truyền thừa hay học phái. Kết quả thu được từ công cụ này được tính toán hoàn toàn dựa trên logic đồng thuận phổ biến và chỉ nên được sử dụng như một tài liệu tham khảo tính toán khách quan, không phải là lời luận giải Tử Vi mang tính chất duy nhất hay định mệnh.

---

### Cài đặt

Bạn có thể cài đặt trực tiếp `tuvi-mcp-server` từ PyPI bằng pip:
```bash
pip install tuvi-mcp-server

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [nmhaaa3218](https://github.com/nmhaaa3218)
- **Source:** [nmhaaa3218/TuViMCP](https://github.com/nmhaaa3218/TuViMCP)
- **License:** MIT
- **Homepage:** https://pypi.org/project/tuvi-mcp-server/

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-nmhaaa3218-tuvimcp
- Seller: https://agentstack.voostack.com/s/nmhaaa3218
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
