> ## Documentation Index
> Fetch the complete documentation index at: https://ahvn.top/llms.txt
> Use this file to discover all available pages before exploring further.

# 30 分钟企业工作坊：数据分析

> 注册只读 SQL snippet，通过 database MCP profile 执行，并模拟 Agent 分析。

<Note>
  本工作坊是 `demos/enterprise/02_snippets_and_predicates.py` 与 `03_agent_analysis_session.py` 的文档转录。实时 LLM 分析为可选项（`HVNB_RUN_LLM_DEMO=1`）。
</Note>

你将注册只读 SQL snippet 与 predicate，通过 `database` MCP profile 执行它们，并模拟 Agent 分析会话。MCP 工具调用日志已在文档中说明，但当前发布基线上尚未交付。

<br />

## 1. 前置条件

完成 [数据连接](/quickstart/data-connection)，或确保 `demos/data/warehouse.db` 已存在：

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
rtk bash scripts/sync-env.bash -- --extra sql
rtk uv run python demos/enterprise/01_connect_and_ingest.py
```

<br />

## 2. 注册 Snippet 与 Predicate

**脚本：** `demos/enterprise/02_snippets_and_predicates.py`

将只读 SQL 存储为 `db-snippet` 行，将可复用过滤器存储为 `db-predicate` 行：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heavenbase as hb
import heavenbase.ext as hb_ext

ws = hb.HeavenBase("ent-02-snippets", backends={"main": {"type": "inmem"}})
ws.enable_extension("database")
database_id = hb_ext.ingest_database(ws, "demos/data/warehouse.db", name="warehouse")["database"][0]

ws.upsert(
    "db-snippet",
    {
        "object_id": "snippet-customer-count",
        "database_id": database_id,
        "title": "Count customers",
        "sql": "SELECT COUNT(*) AS n FROM customers",
        "readonly": True,
        "card_text": "count all customers in warehouse",
    },
)

ws.upsert(
    "db-predicate",
    {
        "object_id": "pred-high-spend",
        "column_id": amount_col_id,
        "expression": "amount > :threshold",
        "desc": "Orders above a spend threshold",
        "card_text": "high spend orders filter",
    },
)
```

<br />

## 3. 通过 Database Profile 运行 Snippet

`database` profile 扩展 read/query 工具组，并新增 `run_snippet` 与 `suggest_sql`。首次使用时会自动启用扩展：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
toolkit = ws.to_mcp(profile="database")

result = toolkit.run("run_snippet", snippet_id="snippet-customer-count")
print(result["rows"])  # [{"n": ...}]

suggestions = toolkit.run("suggest_sql", question="count customers")
print([row["object_id"] for row in suggestions["snippets"]])
```

除非在 `CM_HVNB` 中设置 `heavenbase.database.allow_write=true`（默认 `false`），否则写 snippet 会被拒绝。

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
rtk uv run python demos/enterprise/02_snippets_and_predicates.py
```

<br />

## 4. Agent 分析会话

**脚本：** `demos/enterprise/03_agent_analysis_session.py`

暴露 database profile，并在进程内模拟 Agent 调用：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
ws.enable_extension("agent")
toolkit = ws.to_mcp(name="ent-03-database", profile="database")

suggested = toolkit.run("suggest_sql", question="count customers")
counted = toolkit.run("run_snippet", snippet_id="snippet-customer-count")
tables = toolkit.run("query", entity="db-table", spec={"select": ["table_name"], "limit": 5})
```

供外部 Agent 连接：

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
hb mcp serve --workspace ent-03-analysis --profile database
```

可选的实时 LLM 分析（需要 provider 凭证）：

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
HVNB_RUN_LLM_DEMO=1 rtk uv run python demos/enterprise/03_agent_analysis_session.py
```

该脚本使用 `deepseek-v4-flash`，并将 database MCP 工具集 (Toolkit) 挂载到 `LLMSession`。

<br />

## 5. 会话日志（规划中）

通过 `heavenbase.mcp.log_sessions` 记录 MCP 工具调用已在原型计划中定义，但**当前发布基线上尚未实现**。CLI 通过 `hb llm chat` 与 `hb llm session` 记录日志的功能现已交付。

MCP 日志落地后，enterprise 演示 `03` 将记录三条针对 `agent-message` 行的元分析查询：

* 工具调用频率 — 按 `tool_name` 分组
* 错误率 — 筛选 `error_flag` 为 true 的行
* 慢调用 — 按 `duration_ms` 降序排序

<br />

## Summary

* 只读 `db-snippet` 行可通过 `database` profile 安全执行；写访问默认关闭。
* `suggest_sql` 按卡片文本搜索 snippet 与 predicate，无需在引擎内调用 LLM。
* Agent 通过 MCP 连接，获得面向 `db-*` 实体的小型、schema 感知工具面。

<br />

## 进一步探索

<Tip>
  **相关资源：**

  * [数据连接](/quickstart/data-connection) — 摄取并浏览 schema 实体
  * [MCP 工具集参考](/reference/mcp-toolkit/overview) — Profile 与工具表
  * [Agent 扩展](/features/agent-extension) — 会话、Skill 与 CLI 日志
  * [Enterprise 演示轨道](https://github.com/Magolor/HeavenBase/tree/master/demos/enterprise) — 完整可运行脚本
</Tip>

<br />
