# 插件机制

> 后端插件沿用上游 FBA 的设计：一个目录、一份 plugin.toml，声明路由、配置、依赖和支持的数据库；内置 10 个插件各是什么，fba add 怎么装，插件管理页上启停的效果，以及插件能挂进哪些扩展点（通知类型、数据变更、导入导出、Webhook 事件、短信模板、AI 工具）。

Source: https://yile2020.github.io/fastapi-react-admin/features/plugins/

后端的插件机制来自上游 [fastapi-best-architecture](https://github.com/fastapi-practices/fastapi_best_architecture)（FBA）：每个插件是 `apps/api/backend/plugin/` 下的一个目录，里面一份 `plugin.toml` 声明它是什么、挂在哪、要什么配置、依赖哪些插件、支持哪几种数据库；后端启动时扫描这些目录，把路由、配置、钩子接进来。审批流、AI 助手、能力开放、短信、通知这些功能都是插件。**1.0 起插件接口在兼容承诺里**：`plugin.toml` 的字段、`fba add` 的安装流程、下面列的扩展点不做破坏性改动，第三方插件照旧能装能跑（见[版本升级](https://yile2020.github.io/fastapi-react-admin/reference/upgrade/)）。

## 在界面上哪里找？

| 入口 | 路径 | 谁能用 | 做什么 |
|---|---|---|---|
| **系统管理 → 插件管理** | `/system/plugin` | 超级管理员 | 每个插件一张卡片：说明、版本、标签、类型、支持的数据库、实际的接口前缀、配置项；启用 / 停用、下载 zip、卸载、从 zip 或 git 地址安装 |
| 命令行 | `fba add` / `fba remove` | 有服务器权限的人 | 安装 / 卸载插件，含建表和初始化数据 |

插件管理的所有接口按**超级管理员**判，不用权限码。

## 内置了哪些插件？

| 插件 | 是什么 | 类型 | 依赖 |
|---|---|---|---|
| `ai` | [AI 助手](https://yile2020.github.io/fastapi-react-admin/features/ai-assistant/) | 独立路由 | |
| `config` | [参数配置](https://yile2020.github.io/fastapi-react-admin/features/config-dict/) | 扩展 admin | |
| `dict` | [数据字典](https://yile2020.github.io/fastapi-react-admin/features/config-dict/) | 扩展 admin | **必装**，不能卸载 |
| `email` | 邮件发送 | 独立路由 | `plugin.toml` 只声明了 PostgreSQL 和 MySQL；它没有数据表 |
| `notice` | [通知公告](https://yile2020.github.io/fastapi-react-admin/features/notifications/) | 扩展 admin | `notification` |
| `notification` | [站内消息与通知渠道路由](https://yile2020.github.io/fastapi-react-admin/features/notifications/) | 扩展 admin | |
| `oauth2` | GitHub / Google [第三方登录](https://yile2020.github.io/fastapi-react-admin/features/login-security/) | 独立路由 | |
| `open` | [能力开放](https://yile2020.github.io/fastapi-react-admin/features/open-api/)（AK/SK 接口、Webhook） | 独立路由 | |
| `sms` | 短信（阿里云 / 腾讯云） | 独立路由 | |
| `workflow` | [审批流](https://yile2020.github.io/fastapi-react-admin/features/approval-workflow/) | 扩展 admin | `notification` |

**扩展型**插件把路由并进已有的应用（比如 `config` 的接口落在 `/api/v1/sys/configs`），**独立路由型**插件自带一组路由。插件管理页上会把声明的前缀和实际挂载的地址都列出来。

## `plugin.toml` 里写什么？

```toml
[plugin]
summary = "审批流"                 # 1–100 字
version = "0.0.1"                 # x.y.z
description = "…"                 # 1–500 字
author = "yile"
tags = ["other"]                  # ai / mcp / agent / auth / storage / notification / task / payment / other
database = ["mysql", "postgresql", "sqlserver"]
depends_on = ["notification"]     # 依赖的插件；不能依赖自己，成环或缺失都会报错

[app]
extend = "admin"                  # 扩展型：并进 backend.app.admin.api 的同名路径
# router = ["v1"]                 # 独立路由型：从插件的 api/router.py 里取这些路由

[api.workflow]                    # 键名必须和 api/ 下的文件名一致
prefix = "/workflow"
tags = "审批流"

[settings]                        # 键名全大写；值是字符串、数字、布尔或字符串列表
WORKFLOW_AI_APPROVE_ENABLED = true
```

- **依赖顺序**决定路由注入和 `fba init` 执行 SQL 的先后。
- **有 `model/` 的插件必须声明 `database`**，并且为声明的每种库带上完整的初始化 / 销毁 SQL（SQL Server 只需要雪花主键那一套）。
- **`[settings]` 怎么进到 `settings`**：优先级是进程环境变量 > `.env` > `plugin.toml`。但只写在 `plugin.toml` 里、没在 `core/conf.py` 声明的键是「额外字段」，**容器的环境变量覆盖不了它** —— 所以内置插件的每个配置项都在 `conf.py` 里另外声明了一遍（只声明类型、不给默认值）。反过来，`conf.py` 里**带了默认值**的键，`plugin.toml` 里写的值会被忽略。
- 插件目录里的 `requirements.txt` 会用 `uv pip` 装上，每次后端启动也会检查一遍；`.env.example` 在安装时追加进 `.env`。

## 怎么安装、卸载、停用？

**命令行安装**（只能在开发环境）：

```bash
fba add --path ./my_plugin.zip          # 或 --repo-url <git 地址>
fba add --path ./my_plugin.zip --no-sql # 不建表、不跑初始化 SQL
```

它会解压或克隆、追加 `.env.example`、装依赖、为插件的模型建表并执行当前数据库对应的初始化 SQL。**不走 Alembic 迁移**。zip 的要求：根目录下是插件目录，里面至少有 `plugin.toml` 和 `README.md`；插件名取自 **zip 的文件名**。`fba remove <插件>` 执行销毁 SQL、卸载依赖、把目录打包成 `.backup.zip` 后删除；必装插件拒绝卸载。两者完成后都要**重启后端**。

**插件管理页上安装 / 卸载**同样只在开发环境可用，但**不建表、不跑 SQL**（卸载也不跑销毁 SQL），成功后提示按插件的 README 配置并重启。要建表用命令行。

**启用 / 停用**：插件管理页上的开关，状态存在 Redis。

- 停用**立即生效**：所有插件的路由在启动时都挂上了，每个请求先检查插件状态，停用的插件接口直接返回错误「插件 X 未启用，请联系系统管理员」（HTTP 500）。
- 停用的插件提供的 AI 工具会从工具清单里消失；停用 `ai` 时 MCP 网关也拒绝访问。
- 插件的启动钩子（`setup` / `lifespan`）只在启动时对已启用的插件执行，这部分要重启才生效；新安装的插件的路由也要重启后才有。
- 停用**不会隐藏菜单**：侧边栏里那几项还在，点进去接口报错。

## 插件能挂进哪些扩展点？

启动时扫描所有插件目录下的这些文件名，有就加载：

| 文件 | 注册什么 | 内置的用例 |
|---|---|---|
| `hooks.py` | `setup(app)`、`lifespan`、`otel(app)` 三个钩子 | `ai` |
| `notification_kinds.py` | 通知类型（能走哪些渠道、默认策略），见[消息与通知](https://yile2020.github.io/fastapi-react-admin/features/notifications/) | `notice`、`open`、`workflow` |
| `data_change.py` | 数据变更记录的登记，见[日志与审计](https://yile2020.github.io/fastapi-react-admin/features/audit-logs/#给自己的表接入数据变更记录) | `config`、`oauth2` |
| `dataio.py` | 导入导出资源，见[导入导出](https://yile2020.github.io/fastapi-react-admin/features/import-export/#给自己的列表页加导入导出) | `dict`、`notice` |
| `webhook_events.py` | 能力开放的 Webhook 事件 | `workflow` |
| `sms_templates.py` · `sms_providers.py` | 短信业务模板 · 短信厂商 | `workflow`（模板） |
| `ai_tools.py` | AI 助手能调用的工具，见 [AI 助手](https://yile2020.github.io/fastapi-react-admin/features/ai-assistant/#内置了哪些工具怎么加一个) | `workflow` |

这些扫描**不看插件是否启用**：停用的插件声明的通知类型、导入导出资源照样登记着，只是接口调不通。

## 插件的前端页面

前端**不会**自动出现插件的页面。一个插件要在后台有页面，需要：

1. 在 `packages/platform/src/pages/<名字>/` 写页面组件
2. 在 `apps/web/src/routes/_auth/` 下加路由文件
3. 在 `apps/web/src/lib/page-registry.tsx` 里登记「路由 → 组件」（多页签靠它挂载页面）
4. 插件的初始化 SQL 里写好菜单行

菜单的路径在前端找不到对应路由时，侧边栏会跳过它、开发时在控制台警告。完整的「加一个页面」流程见[从零加一个业务模块](https://yile2020.github.io/fastapi-react-admin/guides/first-module/)。

## 它不做什么

- 插件管理页上的安装 / 卸载不建表、不跑 SQL；生产环境不能在页面上装插件。
- 停用插件不会隐藏它的菜单，停用后调用它的接口返回 500 而不是更合适的状态码。
- 启停开关不检查必装插件，`dict` 也能在页面上被停用。
- 插件管理页判断「支持的数据库」时，当前库写死成了 SQL Server，不读实际的 `DATABASE_TYPE`。
- `ai`、`sms`、`workflow` 三个内置插件没有 `README.md`，从页面上下载它们的 zip 再拿去安装，会过不了「必须有 README」的检查。
- 插件只有后端的约定；前端页面要按上面四步手工接。

## 代码在哪

- 插件加载：[`plugin/core.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/core.py)（依赖与必装检查）· [`router.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/router.py)（路由注入）· [`validator.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/validator.py)（`plugin.toml` 校验）· [`settings_source.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/settings_source.py) · [`status.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/status.py)（启停检查）· [`hooks.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/hooks.py)
- 安装：[`plugin/installer.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/installer.py) · 命令行 [`cli.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/cli.py) · 插件管理接口 [`api/v1/sys/plugin.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/api/v1/sys/plugin.py)
- 前端：[`pages/plugin/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/plugin) · [`apps/web/src/lib/page-registry.tsx`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/web/src/lib/page-registry.tsx)
- 上游的插件文档：[FBA 文档](https://fastapi-practices.github.io/fastapi_best_architecture_docs/)

## 怎么测的

- [`tests/test_plugin_order_is_deterministic.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/tests/test_plugin_order_is_deterministic.py)：插件按依赖排出的顺序每次都一样。[`tests/test_sql_scripts.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/tests/test_sql_scripts.py)：各插件的 SQL 脚本齐全。
- 停用插件的效果：`ai` 插件停用后 MCP 网关关闭（`test_ai_mcp.py`）、`workflow` 插件停用后它的 AI 工具一起消失（`test_ai_workflow_tools.py`）。
- **没有测试的**：`plugin.toml` 校验、安装器、插件管理接口，插件管理页也没有 E2E。

## 在演示站里试试

[在线演示](https://fra.wubunan.com/sign-in)（`admin` / `123456`）：打开「系统管理 → 插件管理」，看每个插件声明的接口前缀和实际挂载的地址、它带的配置项。演示站不是开发环境，安装和卸载会被拒绝；**别去停用插件**，所有人共用这个实例。
