feat(mcp): 业务工具扩到 12 个 + --mcp --with-http 双形态
- 新增 8 个只读工具:permission(user/role/authorize) · dict(type/data) · data(query/count) · schema(index) - data.query/count 走严格白名单:表名 valid_table、列名查 information_schema、值全参数化 (参数化只防值注入,结构注入必须靠列白名单) - `--mcp --with-http`:MCP 与 HTTP 同一进程、同一 AppState、同一个库,人机协作不用切进程 - mcp-smoke 13 → 20 条(新增四域可用性 / 列裁剪 / 结构注入防护) - 影响:测试 280;踩坑两处 —— COALESCE 默认值类型必须与列一致;入参 f_ 列名 / 出参 camelCase 两套命名
This commit is contained in:
1 parent
217dadf008
commit
16266c93c3
8 files changed
+1167
-31
No files matched your search
@@ -411,3 +411,45 @@ module 114 / boundary 11 / contract 10 / citations 4 / **arch 7/7** / naming 3-0
|
||||
3. `--mcp --with-http` 双形态(当前 MCP 与 HTTP 各占一个数据目录,联调不便)
|
||||
4. `BaselineHttpAdapter`(P4 对账前必须有)
|
||||
|
||||
## 11:00 P1 第二批:业务工具 12 个 + 双形态
|
||||
|
||||
### 交付
|
||||
|
||||
- **12 个业务工具**(原 4 + 新 8),全部**只读**:
|
||||
`permission.user.list` / `permission.role.list` / `permission.authorize.list`
|
||||
|`dict.type.list` / `dict.data.list`|`data.query` / `data.count`|`schema.index.list`
|
||||
- **`--mcp --with-http` 双形态**:同一进程、同一 `AppState`、同一个库。
|
||||
AI 通过 MCP 写、浏览器刷新就能看 —— 人机协作的手感落地了。
|
||||
- `mcp-smoke.sh` 从 13 条扩到 **20 条**(新增:四域工具可用 / 列裁剪 / 结构注入防护)
|
||||
- 全部只读的理由:写工具依赖平台约束(enCode 唯一、菜单三处一致、授权四源合并),
|
||||
P2 元数据引擎才成体系。现在硬写会造出「能跑但埋雷」的工具。
|
||||
|
||||
### 🔴 两个新坑
|
||||
|
||||
**① 列类型不能猜**:`base_dictionary_type.f_type` 是 **INTEGER**,
|
||||
写 `COALESCE(f_type, '')` 直接 `invalid input syntax for type integer: ""`。
|
||||
→ 凡是 `COALESCE(某列, 默认值)`,默认值类型必须与列一致;整数列用 `0` 不是 `''`。
|
||||
|
||||
**② 入参出参两套命名**(最有价值的自提示):
|
||||
- 入参(columns / where / orderBy)用**物理列名** `f_account`
|
||||
- 出参 JSON 键是**去 f_ 前缀的 camelCase** `account`
|
||||
`row_to_json` 会转换。按 `f_` 去读响应拿到 undefined,**且不报错**。
|
||||
→ 已写进 `data.query` 的 pitfalls(P0 级)。这条是我自己写测试时踩的,
|
||||
AI 更会踩,所以必须进自提示而不是文档。
|
||||
|
||||
### 安全设计(data.query / data.count)
|
||||
|
||||
```
|
||||
表名 → valid_table() 白名单(仅 [a-z0-9_])
|
||||
列名 → information_schema 查出来的列集合
|
||||
排序列 → 同上
|
||||
where → 结构化数组 [{column, op, value}],op 白名单,值全部参数化
|
||||
limit → 默认 20 / 上限 200(内存预算)
|
||||
```
|
||||
🔴 **参数化只能防「值注入」,防不了「结构注入」** —— 列名必须走白名单。
|
||||
尺子 M19 专门钉这条:列名传 `f_account; DROP TABLE x` ⇒ `UNKNOWN_COLUMN`。
|
||||
|
||||
### 数字
|
||||
|
||||
`cargo test` **280** |十道闸门全绿 | `mcp-smoke` **20/20**
|
||||
|
||||
@@ -213,7 +213,7 @@ ssw-platform/
|
||||
| **静态·命名** | **`scripts/check-naming.sh`** | **内部标识剥离 NM1–NM3 阻断 + NM4 注释量化(`--strict` 可升级)** | **3/0 已绿(69 处注释技术债)** |
|
||||
| 契约尺子·面 A | `scripts/perm-smoke.sh` | 43 条(面 A 契约闭环 32 + 真实业务模块 asset 9 + 多应用 `App-Code` 路由 2) | 已绿 |
|
||||
| 契约尺子·面 B | `scripts/perm-smoke-jnpf.sh` | 23 条(官方形状 18 + 多应用 `App-Code` 路由 1 + 用户 CRUD 4,诚实记 SKIP) | **23/23 已绿** |
|
||||
| **契约尺子·MCP** | **`scripts/mcp-smoke.sh`** | **13 条:4 元工具上限 / 分层加载 / 自提示 / 业务失败不误报协议错 / stdout 纯 NDJSON** | **13/13 已绿** |
|
||||
| **契约尺子·MCP** | **`scripts/mcp-smoke.sh`** | **20 条:4 元工具上限 / 分层加载 / 自提示 / 业务失败不误报协议错 / 结构注入防护 / stdout 纯 NDJSON** | **20/20 已绿** |
|
||||
| **运行时·内存** | **`scripts/mem-budget.sh`** | **空载物理内存(vmmap `Physical footprint`)是否 ≤ 预算** | **7 MB / 40 MB 预算 已绿** |
|
||||
|
||||
🔴 期望值只有一处:`docs/contract.md` 附录 A(机器可读 `[ENDPOINT]` / `[OFFICIAL]` 等),由 `scripts/contract_expect.py` 解析。
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
//! business —— 业务工具(P1 第二批:permission / dict / data / schema 四域)。
|
||||
//!
|
||||
//! ## 这批工具的共同原则
|
||||
//!
|
||||
//! | 原则 | 原因 |
|
||||
//! |---|---|
|
||||
//! | **表名与列名只来自白名单** | 参数化只能防「值注入」,防不了「结构注入」 |
|
||||
//! | **默认只读** | 写工具(create/update/delete)等 P2 元数据引擎就绪后再放,避免 AI 早期误改 |
|
||||
//! | **列表必须有 limit 上限** | 终端产品内存预算 ≤120MB,一次全表读进 Vec 直接爆 |
|
||||
//! | **敏感列不返** | `base_user` 的 `f_password` / `f_secretkey` 永不出现在结果里 |
|
||||
//!
|
||||
//! ## 为什么先做「读」不做「写」
|
||||
//!
|
||||
//! 写工具的正确性依赖平台约束(enCode 唯一、菜单三处一致、授权四源合并),
|
||||
//! 这些在 P2 元数据引擎里才成体系。现在硬写「建菜单」会造出一堆
|
||||
//! 「能跑但会埋雷」的工具 —— 不如先把「看清现状」做扎实,AI 排查问题已经能省一半时间。
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::adapter::{BoxFut, PlatformAdapter, ToolError};
|
||||
use crate::registry::{Annotations, Category, Example, Hints, Pitfall, Severity, ToolDef};
|
||||
|
||||
macro_rules! passthrough {
|
||||
($name:ident, $op:literal) => {
|
||||
fn $name<'a>(
|
||||
adapter: &'a dyn PlatformAdapter,
|
||||
args: Value,
|
||||
) -> BoxFut<'a, Result<Value, ToolError>> {
|
||||
Box::pin(async move { adapter.invoke($op, args).await })
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ================================================================ permission.role.list
|
||||
|
||||
passthrough!(role_list_handler, "permission.role.list");
|
||||
|
||||
pub const ROLE_LIST: ToolDef = ToolDef {
|
||||
id: "permission.role.list",
|
||||
category: Category::Permission,
|
||||
title: "角色列表",
|
||||
one_liner: "列出角色(含启用状态),授权前先确认 roleId",
|
||||
input_schema: r#"{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"keyword": { "type": "string", "description": "按名称/编码模糊匹配" },
|
||||
"enabledOnly": { "type": "boolean", "default": true, "description": "只看启用的" },
|
||||
"limit": { "type": "integer", "default": 50, "minimum": 1, "maximum": 200 }
|
||||
},
|
||||
"additionalProperties": false
|
||||
}"#,
|
||||
annotations: Annotations::READ,
|
||||
hints: Hints {
|
||||
when_to_use: &["给角色授权前拿 roleId", "排查「为什么这个人看不到菜单」"],
|
||||
when_not_to_use: &["要改角色(P2 才有写工具)"],
|
||||
preconditions: &[],
|
||||
pitfalls: &[Pitfall {
|
||||
severity: Severity::P1,
|
||||
wrong: "用 f_en_code 当唯一标识去关联",
|
||||
right: "关联一律用 f_id(36 位 UUID)",
|
||||
rationale: "enCode 在官方 DDL 里没有 UNIQUE 约束,改名后历史授权会指向不存在的编码。",
|
||||
}],
|
||||
examples: &[Example {
|
||||
args: r#"{"keyword":"管理员"}"#,
|
||||
note: "按名称找",
|
||||
}],
|
||||
},
|
||||
handler: role_list_handler,
|
||||
};
|
||||
|
||||
// ================================================================ permission.user.list
|
||||
|
||||
passthrough!(user_list_handler, "permission.user.list");
|
||||
|
||||
pub const USER_LIST: ToolDef = ToolDef {
|
||||
id: "permission.user.list",
|
||||
category: Category::Permission,
|
||||
title: "用户列表",
|
||||
one_liner: "列出用户(不含口令),排查账号/角色/机构归属",
|
||||
input_schema: r#"{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"keyword": { "type": "string", "description": "按账号/姓名/手机号模糊匹配" },
|
||||
"organizeId": { "type": "string", "description": "只看某个机构下的" },
|
||||
"limit": { "type": "integer", "default": 50, "minimum": 1, "maximum": 200 }
|
||||
},
|
||||
"additionalProperties": false
|
||||
}"#,
|
||||
annotations: Annotations::READ,
|
||||
hints: Hints {
|
||||
when_to_use: &["确认某账号是否存在", "排查登录问题(锁定 / 停用 / 归属机构)"],
|
||||
when_not_to_use: &["要改密码或角色(P2)"],
|
||||
preconditions: &[],
|
||||
pitfalls: &[
|
||||
Pitfall {
|
||||
severity: Severity::P0,
|
||||
wrong: "把 f_password 当可读字段去比对",
|
||||
right: "只比 md5(明文) 的派生值,或直接走登录接口验证",
|
||||
rationale: "库里存的是 md5(明文)(基线平台是再叠加 secretkey 的二次哈希);\
|
||||
任何「读出密码看看」的思路都是错的,且响应里根本不含该列。",
|
||||
},
|
||||
Pitfall {
|
||||
severity: Severity::P1,
|
||||
wrong: "认为 f_account 唯一",
|
||||
right: "唯一性由应用层保证(只比 delete_mark=0 的行)",
|
||||
rationale: "官方 DDL 里 f_account 没有 UNIQUE,软删后重建同账号会出现两行。",
|
||||
},
|
||||
],
|
||||
examples: &[Example {
|
||||
args: r#"{"keyword":"admin"}"#,
|
||||
note: "查管理员账号",
|
||||
}],
|
||||
},
|
||||
handler: user_list_handler,
|
||||
};
|
||||
|
||||
// ================================================================ permission.authorize.list
|
||||
|
||||
passthrough!(authorize_list_handler, "permission.authorize.list");
|
||||
|
||||
pub const AUTHORIZE_LIST: ToolDef = ToolDef {
|
||||
id: "permission.authorize.list",
|
||||
category: Category::Permission,
|
||||
title: "查授权",
|
||||
one_liner: "查某个角色/用户被授了哪些菜单(面 A 判据)",
|
||||
input_schema: r#"{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"objectType": { "type": "string", "enum": ["role", "user", "position", "org"], "description": "授权对象类型" },
|
||||
"objectId": { "type": "string", "description": "对象 id" }
|
||||
},
|
||||
"required": ["objectType", "objectId"],
|
||||
"additionalProperties": false
|
||||
}"#,
|
||||
annotations: Annotations::READ,
|
||||
hints: Hints {
|
||||
when_to_use: &["确认某角色到底能看到哪些菜单", "排查 403"],
|
||||
when_not_to_use: &["要写授权(P2)"],
|
||||
preconditions: &["先 permission.role.list 或 permission.user.list 拿 objectId"],
|
||||
pitfalls: &[
|
||||
Pitfall {
|
||||
severity: Severity::P0,
|
||||
wrong: "用大写 objectType(Role / User)",
|
||||
right: "一律小写 role / user / position / org",
|
||||
rationale: "`base_authorize.f_object_type` 存的是小写;大写查不到任何行,\
|
||||
表现成「没授权」而不是报错。",
|
||||
},
|
||||
Pitfall {
|
||||
severity: Severity::P1,
|
||||
wrong: "只看本表就断定「有/无权限」",
|
||||
right: "记住权限是**四源合并**:直授 + 角色 + 组织 + 岗位,且管理员短路",
|
||||
rationale: "只查 base_authorize 的直授会漏掉角色/组织/岗位三条来源。",
|
||||
},
|
||||
],
|
||||
examples: &[Example {
|
||||
args: r#"{"objectType":"role","objectId":"填一个真实 roleId"}"#,
|
||||
note: "查角色授权",
|
||||
}],
|
||||
},
|
||||
handler: authorize_list_handler,
|
||||
};
|
||||
|
||||
// ================================================================ dict.type.list
|
||||
|
||||
passthrough!(dict_type_list_handler, "dict.type.list");
|
||||
|
||||
pub const DICT_TYPE_LIST: ToolDef = ToolDef {
|
||||
id: "dict.type.list",
|
||||
category: Category::Dict,
|
||||
title: "字典分类",
|
||||
one_liner: "列出字典分类(下拉框的数据源)",
|
||||
input_schema: r#"{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"keyword": { "type": "string", "description": "按名称/编码模糊匹配" },
|
||||
"limit": { "type": "integer", "default": 50, "minimum": 1, "maximum": 200 }
|
||||
},
|
||||
"additionalProperties": false
|
||||
}"#,
|
||||
annotations: Annotations::READ,
|
||||
hints: Hints {
|
||||
when_to_use: &["建表单要给字段配下拉时", "确认某字典编码存不存在"],
|
||||
when_not_to_use: &["要看字典项(用 dict.data.list)"],
|
||||
preconditions: &[],
|
||||
pitfalls: &[Pitfall {
|
||||
severity: Severity::P1,
|
||||
wrong: "拿 f_full_name(中文名)去配字典",
|
||||
right: "配 f_en_code(英文编码)",
|
||||
rationale: "表单 JSON 里存的是 enCode;用中文名匹配不上,会静默变成空下拉。",
|
||||
}],
|
||||
examples: &[Example {
|
||||
args: r#"{"keyword":"状态"}"#,
|
||||
note: "找状态类字典",
|
||||
}],
|
||||
},
|
||||
handler: dict_type_list_handler,
|
||||
};
|
||||
|
||||
// ================================================================ dict.data.list
|
||||
|
||||
passthrough!(dict_data_list_handler, "dict.data.list");
|
||||
|
||||
pub const DICT_DATA_LIST: ToolDef = ToolDef {
|
||||
id: "dict.data.list",
|
||||
category: Category::Dict,
|
||||
title: "字典项",
|
||||
one_liner: "列出某个字典分类下的选项(含默认值)",
|
||||
input_schema: r#"{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"dictionaryTypeId": { "type": "string", "description": "字典分类 id(来自 dict.type.list)" },
|
||||
"limit": { "type": "integer", "default": 100, "minimum": 1, "maximum": 500 }
|
||||
},
|
||||
"required": ["dictionaryTypeId"],
|
||||
"additionalProperties": false
|
||||
}"#,
|
||||
annotations: Annotations::READ,
|
||||
hints: Hints {
|
||||
when_to_use: &["确认某字典有哪些选项、默认选哪个"],
|
||||
when_not_to_use: &["还没拿到 dictionaryTypeId(先 dict.type.list)"],
|
||||
preconditions: &["dictionaryTypeId 必须来自 dict.type.list 的 id"],
|
||||
pitfalls: &[Pitfall {
|
||||
severity: Severity::P2,
|
||||
wrong: "假设返回项按 enCode 排序",
|
||||
right: "按 f_sort_code 排;同 sortCode 时顺序不稳定",
|
||||
rationale: "下拉框的展示顺序由 sortCode 决定,靠 enCode 猜顺序会与前端不一致。",
|
||||
}],
|
||||
examples: &[Example {
|
||||
args: r#"{"dictionaryTypeId":"填一个真实字典 id"}"#,
|
||||
note: "查字典项",
|
||||
}],
|
||||
},
|
||||
handler: dict_data_list_handler,
|
||||
};
|
||||
|
||||
// ================================================================ data.query
|
||||
|
||||
passthrough!(data_query_handler, "data.query");
|
||||
|
||||
pub const DATA_QUERY: ToolDef = ToolDef {
|
||||
id: "data.query",
|
||||
category: Category::Data,
|
||||
title: "查数据",
|
||||
one_liner: "按表名查数据(结构化条件 + 列白名单,不拼字符串)",
|
||||
input_schema: r#"{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"table": { "type": "string", "description": "物理表名,如 asset_data_resource" },
|
||||
"columns": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "要返回的列(缺省=全部列);列名会按 information_schema 校验"
|
||||
},
|
||||
"where": {
|
||||
"type": "array",
|
||||
"description": "结构化条件(AND 连接),值为参数化绑定",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"column": { "type": "string" },
|
||||
"op": { "type": "string", "enum": ["eq","ne","like","gt","ge","lt","le","isnull","notnull"] },
|
||||
"value": { "type": "string" }
|
||||
},
|
||||
"required": ["column", "op"]
|
||||
}
|
||||
},
|
||||
"orderBy": { "type": "string", "description": "排序列(白名单校验)" },
|
||||
"desc": { "type": "boolean", "default": true },
|
||||
"limit": { "type": "integer", "default": 20, "minimum": 1, "maximum": 200 }
|
||||
},
|
||||
"required": ["table"],
|
||||
"additionalProperties": false
|
||||
}"#,
|
||||
annotations: Annotations::READ,
|
||||
hints: Hints {
|
||||
when_to_use: &["核对某张表里到底有什么数据", "排查「列表页为什么是空的」"],
|
||||
when_not_to_use: &["要聚合统计(用 data.count)", "表名不确定(先 schema.table.list)"],
|
||||
preconditions: &["表名必须是物理表名(`f_` 前缀的列名不在这里查)", "列名不确定先 schema.table.describe"],
|
||||
pitfalls: &[
|
||||
Pitfall {
|
||||
severity: Severity::P0,
|
||||
wrong: "以为 where 是 SQL 片段,传 `status = 1 or 1=1`",
|
||||
right: "where 是结构化数组:`[{\"column\":\"f_status\",\"op\":\"eq\",\"value\":\"1\"}]`",
|
||||
rationale: "本工具**不接受任何 SQL 字符串**:表名、列名、排序字段全部走白名单,\
|
||||
值全部参数化绑定。传 SQL 片段会被当成普通字符串值,查不到数据(不报错)。",
|
||||
},
|
||||
Pitfall {
|
||||
severity: Severity::P0,
|
||||
wrong: "入参用 `f_account`,出参也按 `f_account` 取值",
|
||||
right: "入参(columns/where/orderBy)用物理列名 `f_account`;出参键是 `account`",
|
||||
rationale: "同一行数据两套命名:**进 SQL 用 `f_` 前缀,出 JSON 去前缀转 camelCase**。\
|
||||
按 `f_` 去读响应会拿到 undefined,而且不报错。",
|
||||
},
|
||||
Pitfall {
|
||||
severity: Severity::P1,
|
||||
wrong: "不传 limit 就想看全部",
|
||||
right: "默认 20、上限 200;要全量导出走 ops 域的备份工具",
|
||||
rationale: "终端产品内存预算 ≤120MB,一次把大表读进 Vec 会直接把进程打爆。",
|
||||
},
|
||||
],
|
||||
examples: &[
|
||||
Example {
|
||||
args: r#"{"table":"asset_data_resource","limit":5}"#,
|
||||
note: "看前 5 条",
|
||||
},
|
||||
Example {
|
||||
args: r#"{"table":"base_user","columns":["f_id","f_account"],"where":[{"column":"f_account","op":"like","value":"admin"}],"limit":10}"#,
|
||||
note: "带结构化条件",
|
||||
},
|
||||
],
|
||||
},
|
||||
handler: data_query_handler,
|
||||
};
|
||||
|
||||
// ================================================================ data.count
|
||||
|
||||
passthrough!(data_count_handler, "data.count");
|
||||
|
||||
pub const DATA_COUNT: ToolDef = ToolDef {
|
||||
id: "data.count",
|
||||
category: Category::Data,
|
||||
title: "数数据",
|
||||
one_liner: "按表名 + 结构化条件计数(不取数据,内存友好)",
|
||||
input_schema: r#"{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"table": { "type": "string", "description": "物理表名" },
|
||||
"where": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"column": { "type": "string" },
|
||||
"op": { "type": "string", "enum": ["eq","ne","like","gt","ge","lt","le","isnull","notnull"] },
|
||||
"value": { "type": "string" }
|
||||
},
|
||||
"required": ["column", "op"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["table"],
|
||||
"additionalProperties": false
|
||||
}"#,
|
||||
annotations: Annotations::READ,
|
||||
hints: Hints {
|
||||
when_to_use: &["只想确认「有没有数据」而不关心内容", "大表核对条数"],
|
||||
when_not_to_use: &["要看具体行(用 data.query)"],
|
||||
preconditions: &["表名必须是物理表名"],
|
||||
pitfalls: &[Pitfall {
|
||||
severity: Severity::P2,
|
||||
wrong: "用 data.query 拉全量再自己数",
|
||||
right: "用本工具,SQL 层 count(*)",
|
||||
rationale: "拉全量再数是内存与带宽的双重浪费,且 limit 上限会让人误以为「就只有 200 条」。",
|
||||
}],
|
||||
examples: &[Example {
|
||||
args: r#"{"table":"base_user"}"#,
|
||||
note: "数用户总数",
|
||||
}],
|
||||
},
|
||||
handler: data_count_handler,
|
||||
};
|
||||
|
||||
// ================================================================ schema.index.list
|
||||
|
||||
passthrough!(index_list_handler, "schema.index.list");
|
||||
|
||||
pub const INDEX_LIST: ToolDef = ToolDef {
|
||||
id: "schema.index.list",
|
||||
category: Category::Schema,
|
||||
title: "索引清单",
|
||||
one_liner: "列出表上的索引与唯一约束(查重/性能排查)",
|
||||
input_schema: r#"{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"table": { "type": "string", "description": "物理表名;不传则列全库索引" }
|
||||
},
|
||||
"additionalProperties": false
|
||||
}"#,
|
||||
annotations: Annotations::READ,
|
||||
hints: Hints {
|
||||
when_to_use: &["怀疑某列该有唯一约束却没有", "慢查询先看有没有索引"],
|
||||
when_not_to_use: &["只要表清单(schema.table.list)"],
|
||||
preconditions: &[],
|
||||
pitfalls: &[Pitfall {
|
||||
severity: Severity::P1,
|
||||
wrong: "假设 f_account 有唯一索引",
|
||||
right: "先查一次 —— 基线平台 DDL 里它没有 UNIQUE",
|
||||
rationale: "官方 DDL 大量列没有唯一约束(唯一性靠应用层);\
|
||||
按「应该有」去写代码会造出重复数据。",
|
||||
}],
|
||||
examples: &[Example {
|
||||
args: r#"{"table":"base_user"}"#,
|
||||
note: "看用户表的索引",
|
||||
}],
|
||||
},
|
||||
handler: index_list_handler,
|
||||
};
|
||||
|
||||
/// P1 第二批的业务工具(8 个)。
|
||||
pub static BUSINESS_TOOLS: &[ToolDef] = &[
|
||||
ROLE_LIST,
|
||||
USER_LIST,
|
||||
AUTHORIZE_LIST,
|
||||
DICT_TYPE_LIST,
|
||||
DICT_DATA_LIST,
|
||||
DATA_QUERY,
|
||||
DATA_COUNT,
|
||||
INDEX_LIST,
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn business_tools_are_well_formed() {
|
||||
assert_eq!(BUSINESS_TOOLS.len(), 8);
|
||||
for t in BUSINESS_TOOLS {
|
||||
let s = t.schema_value();
|
||||
assert!(s.get("x-schema-error").is_none(), "{} schema 非法", t.id);
|
||||
assert_eq!(s["type"], "object", "{} schema 必须是 object", t.id);
|
||||
assert!(
|
||||
t.one_liner.chars().count() <= 40,
|
||||
"{} one_liner 超 40 字(当前 {})",
|
||||
t.id,
|
||||
t.one_liner.chars().count()
|
||||
);
|
||||
assert!(!t.hints.when_to_use.is_empty(), "{} 缺 when_to_use", t.id);
|
||||
assert!(!t.hints.when_not_to_use.is_empty(), "{} 缺 when_not_to_use", t.id);
|
||||
assert!(!t.hints.examples.is_empty(), "{} 缺 examples", t.id);
|
||||
for ex in t.hints.examples {
|
||||
serde_json::from_str::<Value>(ex.args)
|
||||
.unwrap_or_else(|e| panic!("{} 的示例不是合法 JSON: {e}", t.id));
|
||||
}
|
||||
for p in t.hints.pitfalls {
|
||||
assert!(!p.rationale.trim().is_empty(), "{} 的坑缺 rationale", t.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔴 这批工具全部只读 —— 写工具等 P2 元数据引擎。
|
||||
#[test]
|
||||
fn all_business_tools_are_read_only() {
|
||||
for t in BUSINESS_TOOLS {
|
||||
assert!(t.annotations.read_only, "{} 不该在这批里做写操作", t.id);
|
||||
assert!(!t.annotations.destructive, "{} 不该是破坏性的", t.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// 工具 id 的域必须与 category 一致。
|
||||
#[test]
|
||||
fn domain_matches_category() {
|
||||
for t in BUSINESS_TOOLS {
|
||||
let (domain, _) = t.id.split_once('.').expect("必须是 域.动作");
|
||||
assert_eq!(domain, t.category.as_str(), "{} 域与 category 不一致", t.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
//!
|
||||
//! 🔴 **不需要改 `META_TOOLS`,也不需要改协议层** —— 这是加工具的正常成本。
|
||||
|
||||
pub mod business;
|
||||
pub mod meta;
|
||||
|
||||
use serde_json::Value;
|
||||
@@ -179,12 +180,23 @@ const MENU_TREE_TOOL: ToolDef = ToolDef {
|
||||
|
||||
/// 全部业务工具。
|
||||
///
|
||||
/// P1 首批 4 个(context / schema ×2 / menu),后续按 `PLAN.md` §6.3 的 12 域补齐到约 55 个。
|
||||
/// P1 首批 4 个(context / schema ×2 / menu)+ 第二批 8 个(permission ×3 / dict ×2 / data ×2 / schema ×1)
|
||||
/// = **12 个**。后续按 `PLAN.md` §6.3 的 12 域补齐到约 55 个。
|
||||
pub static ALL_TOOLS: &[ToolDef] = &[
|
||||
// —— 首批(P1-a)——
|
||||
CONTEXT_GET_TOOL,
|
||||
SCHEMA_TABLE_LIST_TOOL,
|
||||
SCHEMA_TABLE_DESCRIBE_TOOL,
|
||||
MENU_TREE_TOOL,
|
||||
// —— 第二批(P1-b):全部只读 ——
|
||||
business::ROLE_LIST,
|
||||
business::USER_LIST,
|
||||
business::AUTHORIZE_LIST,
|
||||
business::DICT_TYPE_LIST,
|
||||
business::DICT_DATA_LIST,
|
||||
business::DATA_QUERY,
|
||||
business::DATA_COUNT,
|
||||
business::INDEX_LIST,
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -243,13 +255,29 @@ mod tests {
|
||||
}
|
||||
|
||||
/// 注册表能按分类检索到对应工具。
|
||||
///
|
||||
/// 🔴 断言「每个域至少一个」而**不是固定数量** —— 工具数会随迭代增长,
|
||||
/// 写死数字等于每次加工具都要改测试(那测试就从护栏变成了绊脚石)。
|
||||
#[test]
|
||||
fn registry_finds_tools_by_category() {
|
||||
let reg = Registry::with_tools(ALL_TOOLS);
|
||||
let schema_tools = reg.search(None, Some(Category::Schema), 50);
|
||||
assert_eq!(schema_tools.len(), 2, "schema 域应有 2 个工具");
|
||||
assert!(reg.find("menu.tree").is_some());
|
||||
assert!(reg.find("context.get").is_some());
|
||||
for cat in [
|
||||
Category::Context,
|
||||
Category::Schema,
|
||||
Category::Menu,
|
||||
Category::Permission,
|
||||
Category::Dict,
|
||||
Category::Data,
|
||||
] {
|
||||
assert!(
|
||||
!reg.search(None, Some(cat), 200).is_empty(),
|
||||
"{} 域应有至少一个工具",
|
||||
cat.as_str()
|
||||
);
|
||||
}
|
||||
for id in ["context.get", "menu.tree", "data.query", "permission.role.list"] {
|
||||
assert!(reg.find(id).is_some(), "缺工具 {id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 只读工具的注解必须真的标 read_only(AI 据此决定要不要问人)。
|
||||
|
||||
+38
-5
@@ -37,9 +37,21 @@ printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
|
||||
🔴 **`PGLITE_DIR` 必须写绝对路径**:MCP 客户端启动子进程时 cwd 不确定,
|
||||
相对路径会把库建到奇怪的地方(默认值依赖「从可执行文件向上找锚点」,MCP 下也不稳)。
|
||||
|
||||
🔴 **一个数据目录只能被一个进程打开**(pglite 独占)。
|
||||
若 HTTP 后端已经在跑,MCP 要么复用同一个进程(暂不支持,见 §5),
|
||||
要么用**另一个数据目录**(推荐:开发期用独立库,避免和前端联调互相干扰)。
|
||||
### 想同时用浏览器看效果?
|
||||
|
||||
```bash
|
||||
./target/release/ssw-platform --mcp --with-http
|
||||
```
|
||||
|
||||
**同一进程、同一个 `AppState`、同一个库**:AI 通过 MCP 建的表 / 写的菜单,
|
||||
浏览器刷新就能看到;反之亦然。这才是「人 + AI 协作」该有的手感 ——
|
||||
不用来回切进程、切数据目录。
|
||||
|
||||
MCP 客户端里加 `"args": ["--mcp", "--with-http"]` 即可,
|
||||
HTTP 默认监听 30010(`PORT` 可改),前端代理指过来就行。
|
||||
|
||||
⚠️ **一个数据目录只能被一个进程打开**(pglite 独占)。
|
||||
已经用 `--with-http` 起了服务,就别再单独起一个 `ssw-platform`。
|
||||
|
||||
---
|
||||
|
||||
@@ -68,6 +80,27 @@ sspf_context # 1. 先确认环境
|
||||
→ 失败则读 error.hints / next_actions 自纠
|
||||
```
|
||||
|
||||
### 当前业务工具(12 个,全部只读)
|
||||
|
||||
| 域 | 工具 | 一句话 |
|
||||
|---|---|---|
|
||||
| context | `context.get` | 取后端/应用/表数 |
|
||||
| schema | `schema.table.list` | 列出物理表 |
|
||||
| schema | `schema.table.describe` | 看表的列与类型 |
|
||||
| schema | `schema.index.list` | 索引与唯一约束 |
|
||||
| menu | `menu.tree` | 菜单树(按应用隔离) |
|
||||
| permission | `permission.user.list` | 用户(**不含口令字段**) |
|
||||
| permission | `permission.role.list` | 角色 |
|
||||
| permission | `permission.authorize.list` | 查某对象的直授 |
|
||||
| dict | `dict.type.list` | 字典分类 |
|
||||
| dict | `dict.data.list` | 字典项 |
|
||||
| data | `data.query` | 按表名查数据(结构化条件) |
|
||||
| data | `data.count` | 按表名计数 |
|
||||
|
||||
**为什么这批全是只读**:写工具的正确性依赖平台约束(enCode 唯一、菜单三处一致、
|
||||
授权四源合并),这些在 P2 元数据引擎里才成体系。现在硬写「建菜单」会造出一堆
|
||||
「能跑但会埋雷」的工具 —— 不如先把「看清现状」做扎实。
|
||||
|
||||
---
|
||||
|
||||
## 3. 失败返回长什么样(比成功更重要)
|
||||
@@ -114,10 +147,10 @@ sspf_context # 1. 先确认环境
|
||||
|
||||
| 限制 | 说明 | 计划 |
|
||||
|---|---|---|
|
||||
| 不与 HTTP 后端共用进程 | MCP 与 HTTP 是两个进程,各自独占数据目录 | P1.5 加 `--mcp --with-http` 双形态 |
|
||||
| 没有登录态 | 进程内适配器是**管理员视角**,绕过菜单守卫 | 刻意如此(本地开发);对外暴露必须换 `BaselineHttpAdapter` |
|
||||
| 业务工具只有 4 个 | `context.get` / `schema.table.list` / `schema.table.describe` / `menu.tree` | P1 后续补到约 55 个 |
|
||||
| 业务工具 12 个,全只读 | 见上面清单 | P1 后续补写工具;P2 补 form / model / workflow |
|
||||
| `prompts/*` 返回空 | 多步流程模板还没写 | P2 |
|
||||
| 没有 `BaselineHttpAdapter` | 只能驱动自身内核,不能打远端 Java 后端 | P4 对账前必须有 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+62
-3
@@ -69,6 +69,13 @@ cat > "$REQ" <<'NDJSON'
|
||||
{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"nope.nope","args":{}}}}
|
||||
{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"schema.table.describe","args":{},"dry_run":true}}}
|
||||
{"jsonrpc":"2.0","id":10,"method":"ping","params":{}}
|
||||
{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.user.list","args":{}}}}
|
||||
{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"permission.role.list","args":{}}}}
|
||||
{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"dict.type.list","args":{}}}}
|
||||
{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"data.count","args":{"table":"base_user"}}}}
|
||||
{"jsonrpc":"2.0","id":15,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"data.query","args":{"table":"base_user","columns":["f_account"],"limit":3}}}}
|
||||
{"jsonrpc":"2.0","id":16,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"schema.index.list","args":{"table":"base_user"}}}}
|
||||
{"jsonrpc":"2.0","id":17,"method":"tools/call","params":{"name":"sspf_call","arguments":{"tool_id":"data.query","args":{"table":"base_user","where":[{"column":"f_account; DROP TABLE x","op":"eq","value":"a"}]}}}}
|
||||
NDJSON
|
||||
|
||||
echo "── MCP 工具层契约尺子(4 元工具 + 分层加载)──"
|
||||
@@ -146,10 +153,10 @@ else:
|
||||
ok("M3 业务工具不在 tools/list(只能经 discover 访问)")
|
||||
|
||||
# ---- M4 通知不回复 ----
|
||||
if len(parsed) == 10:
|
||||
ok("M4 10 条带 id 的请求各一个回复;通知无回复")
|
||||
if len(parsed) == 17:
|
||||
ok("M4 17 条带 id 的请求各一个回复;通知无回复")
|
||||
else:
|
||||
bad(f"M4 回复数 {len(parsed)},期望 10(通知不该有回复)")
|
||||
bad(f"M4 回复数 {len(parsed)},期望 17(通知不该有回复)")
|
||||
|
||||
# ---- M5 context ----
|
||||
sc = (result(3) or {}).get("structuredContent", {})
|
||||
@@ -201,6 +208,58 @@ if c3.get("dry_run") is True and isinstance(c3.get("problems"), list) and len(c3
|
||||
else:
|
||||
bad(f"M10 dry_run 应报缺参,实际: {json.dumps(c3, ensure_ascii=False)[:120]}")
|
||||
|
||||
def payload(rid):
|
||||
"""取 sspf_call 的 data 段(业务工具的真实返回)。"""
|
||||
return ((result(rid) or {}).get("structuredContent") or {}).get("data", {})
|
||||
|
||||
# ---- M13~M16 四域只读工具 ----
|
||||
u = payload(11)
|
||||
if isinstance(u.get("users"), list) and "password" not in json.dumps(u).lower():
|
||||
ok(f"M13 permission.user.list 返回 {u.get('count')} 个用户且**不含口令字段**")
|
||||
else:
|
||||
bad(f"M13 permission.user.list 异常或泄漏口令: {json.dumps(u, ensure_ascii=False)[:120]}")
|
||||
|
||||
r = payload(12)
|
||||
if isinstance(r.get("roles"), list) and r.get("count", 0) >= 1:
|
||||
ok(f"M14 permission.role.list 返回 {r.get('count')} 个角色")
|
||||
else:
|
||||
bad("M14 permission.role.list 应至少有一个角色(种子里有 admin)")
|
||||
|
||||
dt = payload(13)
|
||||
if isinstance(dt.get("types"), list):
|
||||
ok(f"M15 dict.type.list 返回 {dt.get('count')} 个字典分类")
|
||||
else:
|
||||
bad("M15 dict.type.list 返回形状不对")
|
||||
|
||||
dc = payload(14)
|
||||
if isinstance(dc.get("count"), int):
|
||||
ok(f"M16 data.count(base_user) = {dc['count']}")
|
||||
else:
|
||||
bad(f"M16 data.count 应返回整数 count,实际: {json.dumps(dc, ensure_ascii=False)[:100]}")
|
||||
|
||||
# ---- M17 列白名单确实生效(只返回请求的列;键是去 f_ 前缀的 camelCase)----
|
||||
dq = payload(15)
|
||||
rows = dq.get("rows") or []
|
||||
if isinstance(rows, list) and rows and all(set(row.keys()) == {"account"} for row in rows):
|
||||
ok(f"M17 data.query 只返回白名单内的列({len(rows)} 行 × 1 列,键已转 camelCase)")
|
||||
else:
|
||||
bad(f"M17 data.query 列裁剪失效: {json.dumps(rows[:1], ensure_ascii=False)[:120]}")
|
||||
|
||||
# ---- M18 索引清单 ----
|
||||
ix = payload(16)
|
||||
if isinstance(ix.get("indexes"), list) and ix.get("count", 0) >= 1:
|
||||
ok(f"M18 schema.index.list 返回 {ix.get('count')} 条索引")
|
||||
else:
|
||||
bad("M18 schema.index.list 至少应有主键索引")
|
||||
|
||||
# ---- M19 🔴 结构注入防护:列名里带 SQL 必须被拒 ----
|
||||
r17 = parsed.get(17, {})
|
||||
c17 = (r17.get("result") or {}).get("structuredContent", {})
|
||||
if c17.get("ok") is False and c17.get("error", {}).get("code") == "UNKNOWN_COLUMN":
|
||||
ok("M19 列名带 SQL 片段 ⇒ UNKNOWN_COLUMN(结构注入被挡)")
|
||||
else:
|
||||
bad(f"M19 结构注入未被挡住: {json.dumps(c17, ensure_ascii=False)[:160]}")
|
||||
|
||||
print()
|
||||
print(f"PASS={PASS} FAIL={FAIL}")
|
||||
sys.exit(0 if FAIL == 0 else 1)
|
||||
|
||||
+42
-17
@@ -72,21 +72,24 @@ enum Cmd {
|
||||
EncMissing,
|
||||
/// `--help` / `-h` ⇒ 打印用法,退出码 **0**。
|
||||
Help,
|
||||
/// `--mcp` ⇒ 起 MCP stdio 服务(不监听端口),退出码 **0**。
|
||||
Mcp,
|
||||
/// `--mcp [--with-http]` ⇒ 起 MCP stdio 服务(不监听端口),退出码 **0**。
|
||||
///
|
||||
/// `with_http` 为真时**同时**起 HTTP —— 同一个进程、同一个 `AppState`、同一个库,
|
||||
/// AI 通过 MCP 写完数据,浏览器刷新就能看到(人机协作的关键手感)。
|
||||
Mcp { with_http: bool },
|
||||
/// 未知参数 ⇒ 用法错,退出码 **2**。
|
||||
Unknown(String),
|
||||
/// 无参数 ⇒ 起服务。
|
||||
Serve,
|
||||
}
|
||||
|
||||
/// 运行时形态(`run()` 的两个分支)。
|
||||
/// 运行时形态(`run()` 的分支)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum RunMode {
|
||||
/// HTTP 服务(默认)。
|
||||
Serve,
|
||||
/// MCP stdio 服务(`--mcp`)—— 与 HTTP 共用同一套装配与同一个库。
|
||||
Mcp,
|
||||
/// MCP stdio 服务;`with_http` 时附带 HTTP。
|
||||
Mcp { with_http: bool },
|
||||
}
|
||||
|
||||
/// 解析命令行参数(**纯函数**:不读环境变量、不退出进程、不打日志)。
|
||||
@@ -103,7 +106,10 @@ fn parse_args(args: &[String]) -> Cmd {
|
||||
Some(plain) => Cmd::Enc(plain.clone()),
|
||||
None => Cmd::EncMissing,
|
||||
},
|
||||
Some("--mcp") => Cmd::Mcp,
|
||||
Some("--mcp") => Cmd::Mcp {
|
||||
// `--with-http` 只在 `--mcp` 之后有意义;位置写错就当没给。
|
||||
with_http: args.get(1).map(String::as_str) == Some("--with-http"),
|
||||
},
|
||||
Some("--help") | Some("-h") => Cmd::Help,
|
||||
Some(other) => Cmd::Unknown(other.to_string()),
|
||||
None => Cmd::Serve,
|
||||
@@ -117,7 +123,7 @@ fn exit_code(cmd: &Cmd) -> i32 {
|
||||
match cmd {
|
||||
Cmd::Enc(_) | Cmd::Help => 0,
|
||||
Cmd::EncMissing | Cmd::Unknown(_) => 2,
|
||||
Cmd::Serve | Cmd::Mcp => 0,
|
||||
Cmd::Serve | Cmd::Mcp { .. } => 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,13 +153,12 @@ async fn main() {
|
||||
std::process::exit(exit_code(&cmd));
|
||||
}
|
||||
// 两个「起服务」形态共用同一套装配(见 `run`),只是收尾不同。
|
||||
Cmd::Serve | Cmd::Mcp => {}
|
||||
Cmd::Serve | Cmd::Mcp { .. } => {}
|
||||
}
|
||||
|
||||
let mode = if cmd == Cmd::Mcp {
|
||||
RunMode::Mcp
|
||||
} else {
|
||||
RunMode::Serve
|
||||
let mode = match cmd {
|
||||
Cmd::Mcp { with_http } => RunMode::Mcp { with_http },
|
||||
_ => RunMode::Serve,
|
||||
};
|
||||
|
||||
if let Err(msg) = run(mode).await {
|
||||
@@ -170,10 +175,11 @@ fn print_usage() {
|
||||
);
|
||||
println!();
|
||||
println!("用法:");
|
||||
println!(" ssw-platform 启动 HTTP 服务(默认端口 30010)");
|
||||
println!(" ssw-platform --mcp 启动 MCP stdio 服务(供 AI 直接驱动,不监听端口)");
|
||||
println!(" ssw-platform --enc <明文> 打印登录口令密文(hex),退出码 0");
|
||||
println!(" ssw-platform --help 打印本用法,退出码 0");
|
||||
println!(" ssw-platform 启动 HTTP 服务(默认端口 30010)");
|
||||
println!(" ssw-platform --mcp 启动 MCP stdio 服务(供 AI 驱动,不监听端口)");
|
||||
println!(" ssw-platform --mcp --with-http 同时起 MCP 与 HTTP(同一进程、同一个库)");
|
||||
println!(" ssw-platform --enc <明文> 打印登录口令密文(hex),退出码 0");
|
||||
println!(" ssw-platform --help 打印本用法,退出码 0");
|
||||
println!();
|
||||
println!("环境变量:");
|
||||
println!(" PORT 监听端口(缺省 30010)");
|
||||
@@ -251,7 +257,7 @@ async fn run(mode: RunMode) -> Result<(), String> {
|
||||
// 🔴 见 `detach_stdio_for_mcp` 的注释:PG 的 single-user 后端会同时占用
|
||||
// stdin(读 SQL)与 stdout(打 `backend>`)。不抢在开库前处理,
|
||||
// MCP 的 NDJSON 流第一时间就被污染,读 stdin 也会 ENXIO。
|
||||
let mcp_io = if mode == RunMode::Mcp {
|
||||
let mcp_io = if matches!(mode, RunMode::Mcp { .. }) {
|
||||
Some(detach_stdio_for_mcp().map_err(|e| format!("MCP 模式接管标准流失败: {e}"))?)
|
||||
} else {
|
||||
None
|
||||
@@ -322,6 +328,25 @@ async fn run(mode: RunMode) -> Result<(), String> {
|
||||
// 🔴 工具层与 HTTP 层共用同一个 `AppState` ⇒ AI 通过 MCP 改的数据,
|
||||
// 前端刷新就能看到;反之亦然。这是「人机协作」在架构上的前提。
|
||||
if let Some((reader, writer)) = mcp_io {
|
||||
// ---- `--with-http`:同一进程里再起一个 HTTP 监听 ----
|
||||
//
|
||||
// 🔴 关键在于**共用同一个 `AppState`**(同一个库、同一张会话表):
|
||||
// AI 通过 MCP 建的表 / 写的菜单,浏览器刷新就能看到;反之亦然。
|
||||
// 这才是「人 + AI 协作」的手感 —— 不用来回切进程、切数据目录。
|
||||
if let RunMode::Mcp { with_http: true } = mode {
|
||||
let addr = std::net::SocketAddr::new(config.bind_addr, config.port);
|
||||
let app = routes::build_app(state.clone());
|
||||
let listener = tokio::net::TcpListener::bind(addr)
|
||||
.await
|
||||
.map_err(|e| format!("MCP+HTTP 模式绑定 {addr} 失败: {e}"))?;
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = axum::serve(listener, app).await {
|
||||
eprintln!("[mcp] HTTP 服务异常退出: {e}");
|
||||
}
|
||||
});
|
||||
eprintln!("[mcp] HTTP 同时监听 http://{addr}(与 MCP 共用同一个库)");
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"[mcp] sspf-mcp v{} 已就绪(stdio / NDJSON,数据目录 {})",
|
||||
sspf_mcp::VERSION,
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
//! 在多用户部署是风险。⇒ 未来若把 MCP 暴露到网络,必须走 `BaselineHttpAdapter`
|
||||
//! 带上真实 token,不能用本适配器。
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use pglite::ToSql;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::platform::db::valid_table;
|
||||
@@ -63,6 +66,478 @@ impl NativeAdapter {
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 取一张表的全部列名(白名单来源)。
|
||||
///
|
||||
/// 🔴 这是 `data.query` / `data.count` 的**唯一安全边界**:
|
||||
/// 表名、列名、排序字段都必须先在这里查到,才允许进 SQL。
|
||||
/// 参数化只能防「值注入」,防不了「结构注入」。
|
||||
async fn columns_of(&self, table: &str) -> Result<Vec<String>, ToolError> {
|
||||
let t = table.to_string();
|
||||
let rows = self
|
||||
.state
|
||||
.db
|
||||
.query_json_params(
|
||||
"SELECT column_name AS \"name\" FROM information_schema.columns \
|
||||
WHERE table_schema = 'public' AND table_name = $1 \
|
||||
ORDER BY ordinal_position",
|
||||
&[&t],
|
||||
)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.filter_map(|r| r["name"].as_str().map(str::to_string))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 把结构化的 `where` 数组拼成 SQL 片段;**值全部进 `params`**,列名必须过白名单。
|
||||
///
|
||||
/// 占位符编号 = `params` 的长度(`$1` 起),所以调用方要先把前置参数 push 进去。
|
||||
fn build_where(
|
||||
conds: &[Value],
|
||||
allowed: &HashSet<String>,
|
||||
params: &mut Vec<String>,
|
||||
) -> Result<String, ToolError> {
|
||||
let mut clauses: Vec<String> = Vec::new();
|
||||
|
||||
for c in conds {
|
||||
let col = c.get("column").and_then(Value::as_str).unwrap_or("");
|
||||
if !allowed.contains(col) {
|
||||
return Err(ToolError::new(
|
||||
"UNKNOWN_COLUMN",
|
||||
format!("列不存在: {col}"),
|
||||
)
|
||||
.field("where.column")
|
||||
.hint("先 schema.table.describe 确认列名(列名是 f_ 前缀)"));
|
||||
}
|
||||
let qcol = format!("\"{col}\"");
|
||||
let op = c.get("op").and_then(Value::as_str).unwrap_or("eq");
|
||||
|
||||
match op {
|
||||
"isnull" => clauses.push(format!("{qcol} IS NULL")),
|
||||
"notnull" => clauses.push(format!("{qcol} IS NOT NULL")),
|
||||
sym @ ("eq" | "ne" | "like" | "gt" | "ge" | "lt" | "le") => {
|
||||
let mut v = c
|
||||
.get("value")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if sym == "like" {
|
||||
v = format!("%{v}%");
|
||||
}
|
||||
params.push(v);
|
||||
let n = params.len();
|
||||
let sql_op = match sym {
|
||||
"eq" => "=",
|
||||
"ne" => "<>",
|
||||
"like" => "ILIKE",
|
||||
"gt" => ">",
|
||||
"ge" => ">=",
|
||||
"lt" => "<",
|
||||
_ => "<=",
|
||||
};
|
||||
clauses.push(format!("{qcol} {sql_op} ${n}"));
|
||||
}
|
||||
other => {
|
||||
return Err(ToolError::new(
|
||||
"BAD_OPERATOR",
|
||||
format!("不支持的比较符: {other}"),
|
||||
)
|
||||
.field("where.op")
|
||||
.hint("可用:eq / ne / like / gt / ge / lt / le / isnull / notnull"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(if clauses.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" AND {}", clauses.join(" AND "))
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 权限
|
||||
|
||||
async fn role_list(&self, args: &Value) -> Result<Value, ToolError> {
|
||||
let keyword = args.get("keyword").and_then(Value::as_str).unwrap_or("");
|
||||
let enabled_only = args
|
||||
.get("enabledOnly")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(true);
|
||||
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50).clamp(1, 200);
|
||||
|
||||
let mut params: Vec<String> = Vec::new();
|
||||
let mut extra = String::new();
|
||||
if !keyword.is_empty() {
|
||||
params.push(format!("%{keyword}%"));
|
||||
let n = params.len();
|
||||
extra.push_str(&format!(
|
||||
" AND (f_full_name ILIKE ${n} OR f_en_code ILIKE ${n})"
|
||||
));
|
||||
}
|
||||
if enabled_only {
|
||||
extra.push_str(" AND f_enabled_mark = 1");
|
||||
}
|
||||
|
||||
let sql = format!(
|
||||
"SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \
|
||||
f_type AS \"type\", COALESCE(f_enabled_mark, 0) AS \"enabledMark\", \
|
||||
COALESCE(f_sort_code, 0) AS \"sortCode\" \
|
||||
FROM base_role WHERE f_delete_mark = 0{extra} \
|
||||
ORDER BY f_sort_code, f_full_name LIMIT {limit}"
|
||||
);
|
||||
|
||||
let refs: Vec<&(dyn ToSql + Sync)> =
|
||||
params.iter().map(|s| s as &(dyn ToSql + Sync)).collect();
|
||||
let rows = self
|
||||
.state
|
||||
.db
|
||||
.query_json_params(&sql, &refs)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
Ok(json!({ "count": rows.len(), "roles": rows }))
|
||||
}
|
||||
|
||||
async fn user_list(&self, args: &Value) -> Result<Value, ToolError> {
|
||||
let keyword = args.get("keyword").and_then(Value::as_str).unwrap_or("");
|
||||
let organize = args
|
||||
.get("organizeId")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50).clamp(1, 200);
|
||||
|
||||
let mut params: Vec<String> = Vec::new();
|
||||
let mut extra = String::new();
|
||||
if !keyword.is_empty() {
|
||||
params.push(format!("%{keyword}%"));
|
||||
let n = params.len();
|
||||
extra.push_str(&format!(
|
||||
" AND (f_account ILIKE ${n} OR f_real_name ILIKE ${n} OR f_mobile_phone ILIKE ${n})"
|
||||
));
|
||||
}
|
||||
if !organize.is_empty() {
|
||||
params.push(organize.to_string());
|
||||
let n = params.len();
|
||||
extra.push_str(&format!(" AND f_organize_id = ${n}"));
|
||||
}
|
||||
|
||||
// 🔴 绝不选 f_password / f_secretkey
|
||||
let sql = format!(
|
||||
"SELECT f_id AS \"id\", f_account AS \"account\", f_real_name AS \"realName\", \
|
||||
COALESCE(f_mobile_phone, '') AS \"mobilePhone\", \
|
||||
COALESCE(f_organize_id, '') AS \"organizeId\", \
|
||||
COALESCE(f_role_id, '') AS \"roleId\", \
|
||||
COALESCE(f_is_administrator, 0) AS \"isAdministrator\", \
|
||||
COALESCE(f_enabled_mark, 0) AS \"enabledMark\", \
|
||||
COALESCE(f_lock_mark, 0) AS \"lockMark\" \
|
||||
FROM base_user WHERE f_delete_mark = 0{extra} \
|
||||
ORDER BY f_account LIMIT {limit}"
|
||||
);
|
||||
|
||||
let refs: Vec<&(dyn ToSql + Sync)> =
|
||||
params.iter().map(|s| s as &(dyn ToSql + Sync)).collect();
|
||||
let rows = self
|
||||
.state
|
||||
.db
|
||||
.query_json_params(&sql, &refs)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
Ok(json!({ "count": rows.len(), "users": rows }))
|
||||
}
|
||||
|
||||
async fn authorize_list(&self, args: &Value) -> Result<Value, ToolError> {
|
||||
let object_type = args
|
||||
.get("objectType")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
let object_id = args.get("objectId").and_then(Value::as_str).unwrap_or("");
|
||||
|
||||
if object_type.is_empty() || object_id.is_empty() {
|
||||
return Err(ToolError::new(
|
||||
"MISSING_ARG",
|
||||
"objectType 与 objectId 都必填",
|
||||
)
|
||||
.field("objectType")
|
||||
.hint("先 permission.role.list 拿 roleId,或用 permission.user.list 拿 userId"));
|
||||
}
|
||||
|
||||
let (ot, oid) = (object_type.to_string(), object_id.to_string());
|
||||
let rows = self
|
||||
.state
|
||||
.db
|
||||
.query_json_params(
|
||||
"SELECT f_id AS \"id\", f_item_type AS \"itemType\", f_item_id AS \"itemId\", \
|
||||
f_object_type AS \"objectType\", f_object_id AS \"objectId\" \
|
||||
FROM base_authorize \
|
||||
WHERE f_delete_mark = 0 AND f_object_type = $1 AND f_object_id = $2 \
|
||||
ORDER BY f_item_type, f_item_id",
|
||||
&[&ot, &oid],
|
||||
)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
// 只查了「直授」这一源,提示 AI 别忘了另外三源
|
||||
Ok(json!({
|
||||
"count": rows.len(),
|
||||
"objectType": ot,
|
||||
"objectId": oid,
|
||||
"items": rows,
|
||||
"note": "这里只有**直授**;实际权限是四源合并(直授 + 角色 + 组织 + 岗位),管理员短路",
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 字典
|
||||
|
||||
async fn dict_type_list(&self, args: &Value) -> Result<Value, ToolError> {
|
||||
let keyword = args.get("keyword").and_then(Value::as_str).unwrap_or("");
|
||||
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(50).clamp(1, 200);
|
||||
|
||||
let mut params: Vec<String> = Vec::new();
|
||||
let mut extra = String::new();
|
||||
if !keyword.is_empty() {
|
||||
params.push(format!("%{keyword}%"));
|
||||
let n = params.len();
|
||||
extra.push_str(&format!(
|
||||
" AND (f_full_name ILIKE ${n} OR f_en_code ILIKE ${n})"
|
||||
));
|
||||
}
|
||||
|
||||
// 🔴 `f_type` 是 **INTEGER**(官方 DDL)—— `COALESCE(f_type, '')` 会报
|
||||
// `invalid input syntax for type integer: ""`。默认值必须是 0 不是空串。
|
||||
let sql = format!(
|
||||
"SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \
|
||||
COALESCE(f_type, 0) AS \"type\", COALESCE(f_is_tree, 0) AS \"isTree\", \
|
||||
COALESCE(f_enabled_mark, 0) AS \"enabledMark\" \
|
||||
FROM base_dictionary_type WHERE f_delete_mark = 0{extra} \
|
||||
ORDER BY f_sort_code, f_full_name LIMIT {limit}"
|
||||
);
|
||||
|
||||
let refs: Vec<&(dyn ToSql + Sync)> =
|
||||
params.iter().map(|s| s as &(dyn ToSql + Sync)).collect();
|
||||
let rows = self
|
||||
.state
|
||||
.db
|
||||
.query_json_params(&sql, &refs)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
Ok(json!({ "count": rows.len(), "types": rows }))
|
||||
}
|
||||
|
||||
async fn dict_data_list(&self, args: &Value) -> Result<Value, ToolError> {
|
||||
let type_id = args
|
||||
.get("dictionaryTypeId")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
if type_id.is_empty() {
|
||||
return Err(ToolError::new("MISSING_ARG", "缺少 dictionaryTypeId")
|
||||
.field("dictionaryTypeId")
|
||||
.hint("先 dict.type.list 拿分类 id"));
|
||||
}
|
||||
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(100).clamp(1, 500);
|
||||
|
||||
let tid = type_id.to_string();
|
||||
let sql = format!(
|
||||
"SELECT f_id AS \"id\", f_full_name AS \"fullName\", f_en_code AS \"enCode\", \
|
||||
COALESCE(f_is_default, 0) AS \"isDefault\", \
|
||||
COALESCE(f_enabled_mark, 0) AS \"enabledMark\", \
|
||||
COALESCE(f_sort_code, 0) AS \"sortCode\" \
|
||||
FROM base_dictionary_data \
|
||||
WHERE f_delete_mark = 0 AND f_dictionary_type_id = $1 \
|
||||
ORDER BY f_sort_code, f_full_name LIMIT {limit}"
|
||||
);
|
||||
|
||||
let rows = self
|
||||
.state
|
||||
.db
|
||||
.query_json_params(&sql, &[&tid])
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
Ok(json!({
|
||||
"dictionaryTypeId": tid,
|
||||
"count": rows.len(),
|
||||
"items": rows,
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 数据
|
||||
|
||||
async fn data_query(&self, args: &Value) -> Result<Value, ToolError> {
|
||||
let raw = args.get("table").and_then(Value::as_str).unwrap_or("");
|
||||
let table = valid_table(raw).ok_or_else(|| {
|
||||
ToolError::new("INVALID_TABLE", format!("表名不合法: {raw}"))
|
||||
.field("table")
|
||||
.hint("只接受小写字母/数字/下划线")
|
||||
.next("schema.table.list", json!({}), "先列出所有表")
|
||||
})?;
|
||||
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(20).clamp(1, 200);
|
||||
|
||||
let cols = self.columns_of(&table).await?;
|
||||
if cols.is_empty() {
|
||||
return Err(ToolError::new("TABLE_NOT_FOUND", format!("表 {table} 不存在"))
|
||||
.field("table")
|
||||
.next("schema.table.list", json!({}), "确认表名"));
|
||||
}
|
||||
let allowed: HashSet<String> = cols.iter().cloned().collect();
|
||||
|
||||
// 选列:缺省全选;显式给了就逐个校验
|
||||
let select = match args.get("columns").and_then(Value::as_array) {
|
||||
Some(arr) if !arr.is_empty() => {
|
||||
let mut v = Vec::with_capacity(arr.len());
|
||||
for c in arr {
|
||||
let name = c.as_str().unwrap_or("");
|
||||
if !allowed.contains(name) {
|
||||
return Err(ToolError::new(
|
||||
"UNKNOWN_COLUMN",
|
||||
format!("列不存在: {name}"),
|
||||
)
|
||||
.field("columns")
|
||||
.hint("先 schema.table.describe 看列名"));
|
||||
}
|
||||
v.push(format!("\"{name}\""));
|
||||
}
|
||||
v.join(", ")
|
||||
}
|
||||
_ => cols
|
||||
.iter()
|
||||
.map(|c| format!("\"{c}\""))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
};
|
||||
|
||||
// 条件
|
||||
let conds = args
|
||||
.get("where")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut params: Vec<String> = Vec::new();
|
||||
let where_sql = Self::build_where(&conds, &allowed, &mut params)?;
|
||||
|
||||
// 排序(列名同样走白名单)
|
||||
let order_sql = match args.get("orderBy").and_then(Value::as_str) {
|
||||
Some(ob) if !ob.is_empty() => {
|
||||
if !allowed.contains(ob) {
|
||||
return Err(ToolError::new("UNKNOWN_COLUMN", format!("排序列不存在: {ob}"))
|
||||
.field("orderBy"));
|
||||
}
|
||||
let dir = if args.get("desc").and_then(Value::as_bool).unwrap_or(true) {
|
||||
"DESC"
|
||||
} else {
|
||||
"ASC"
|
||||
};
|
||||
format!(" ORDER BY \"{ob}\" {dir}")
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
|
||||
// table 已过 valid_table(仅 [a-z0-9_])⇒ 双引号包裹安全
|
||||
let sql = format!(
|
||||
"SELECT {select} FROM \"{table}\" WHERE 1 = 1{where_sql}{order_sql} LIMIT {limit}"
|
||||
);
|
||||
|
||||
let refs: Vec<&(dyn ToSql + Sync)> =
|
||||
params.iter().map(|s| s as &(dyn ToSql + Sync)).collect();
|
||||
let rows = self
|
||||
.state
|
||||
.db
|
||||
.query_json_params(&sql, &refs)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
Ok(json!({
|
||||
"table": table,
|
||||
"count": rows.len(),
|
||||
"limit": limit,
|
||||
"rows": rows,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn data_count(&self, args: &Value) -> Result<Value, ToolError> {
|
||||
let raw = args.get("table").and_then(Value::as_str).unwrap_or("");
|
||||
let table = valid_table(raw).ok_or_else(|| {
|
||||
ToolError::new("INVALID_TABLE", format!("表名不合法: {raw}")).field("table")
|
||||
})?;
|
||||
|
||||
let cols = self.columns_of(&table).await?;
|
||||
if cols.is_empty() {
|
||||
return Err(ToolError::new("TABLE_NOT_FOUND", format!("表 {table} 不存在"))
|
||||
.field("table"));
|
||||
}
|
||||
let allowed: HashSet<String> = cols.into_iter().collect();
|
||||
|
||||
let conds = args
|
||||
.get("where")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut params: Vec<String> = Vec::new();
|
||||
let where_sql = Self::build_where(&conds, &allowed, &mut params)?;
|
||||
|
||||
let sql = format!("SELECT count(*)::text AS \"count\" FROM \"{table}\" WHERE 1 = 1{where_sql}");
|
||||
let refs: Vec<&(dyn ToSql + Sync)> =
|
||||
params.iter().map(|s| s as &(dyn ToSql + Sync)).collect();
|
||||
let rows = self
|
||||
.state
|
||||
.db
|
||||
.query_json_params(&sql, &refs)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
|
||||
let count = rows
|
||||
.first()
|
||||
.and_then(|r| r["count"].as_str())
|
||||
.and_then(|s| s.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
|
||||
Ok(json!({ "table": table, "count": count }))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 索引
|
||||
|
||||
async fn index_list(&self, args: &Value) -> Result<Value, ToolError> {
|
||||
let raw = args.get("table").and_then(Value::as_str).unwrap_or("");
|
||||
let table = if raw.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(valid_table(raw).ok_or_else(|| {
|
||||
ToolError::new("INVALID_TABLE", format!("表名不合法: {raw}")).field("table")
|
||||
})?)
|
||||
};
|
||||
|
||||
let rows = match &table {
|
||||
Some(t) => {
|
||||
let tt = t.clone();
|
||||
self.state
|
||||
.db
|
||||
.query_json_params(
|
||||
"SELECT tablename AS \"table\", indexname AS \"name\", indexdef AS \"definition\" \
|
||||
FROM pg_indexes WHERE schemaname = 'public' AND tablename = $1 \
|
||||
ORDER BY indexname",
|
||||
&[&tt],
|
||||
)
|
||||
.await
|
||||
}
|
||||
None => {
|
||||
self.state
|
||||
.db
|
||||
.query_json(
|
||||
"SELECT tablename AS \"table\", indexname AS \"name\", indexdef AS \"definition\" \
|
||||
FROM pg_indexes WHERE schemaname = 'public' \
|
||||
ORDER BY tablename, indexname",
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
.map_err(db_err)?;
|
||||
|
||||
Ok(json!({ "count": rows.len(), "indexes": rows }))
|
||||
}
|
||||
}
|
||||
|
||||
/// 把 pglite 错误转成结构化的工具错误(AI 能看懂的那种)。
|
||||
@@ -284,6 +759,22 @@ impl PlatformAdapter for NativeAdapter {
|
||||
}))
|
||||
}
|
||||
|
||||
// ------------------------------------------------ 权限(只读)
|
||||
"permission.role.list" => self.role_list(&args).await,
|
||||
"permission.user.list" => self.user_list(&args).await,
|
||||
"permission.authorize.list" => self.authorize_list(&args).await,
|
||||
|
||||
// ------------------------------------------------ 字典(只读)
|
||||
"dict.type.list" => self.dict_type_list(&args).await,
|
||||
"dict.data.list" => self.dict_data_list(&args).await,
|
||||
|
||||
// ------------------------------------------------ 数据(只读)
|
||||
"data.query" => self.data_query(&args).await,
|
||||
"data.count" => self.data_count(&args).await,
|
||||
|
||||
// ------------------------------------------------ 索引
|
||||
"schema.index.list" => self.index_list(&args).await,
|
||||
|
||||
other => Err(ToolError::new(
|
||||
"OP_NOT_IMPLEMENTED",
|
||||
format!("原生适配器还没实现 op: {other}"),
|
||||
|
||||
Reference in new issue
Block a user