@qingflow-tech/qingflow-cli 1.1.58 → 1.1.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/npm/lib/runtime.mjs +29 -13
- package/package.json +1 -1
- package/pyproject.toml +1 -1
- package/skills/qingflow-cli/SKILL.md +92 -430
- package/skills/qingflow-cli/manifest.yaml +1 -1
- package/skills/qingflow-cli/reference/00-INDEX.md +4 -4
- package/skills/qingflow-cli/reference/QINGFLOW_CLI_ADMIN_CHEATSHEET.md +1 -1
- package/skills/qingflow-cli/reference/QINGFLOW_CLI_DATA_RETRIEVAL_WORKFLOW.md +3 -137
- package/skills/qingflow-cli/reference/QINGFLOW_CLI_EXPLORATION_REPORT.md +6 -4
- package/skills/qingflow-cli/reference/QINGFLOW_CLI_FIELD_DATA_TYPES.md +14 -14
- package/skills/qingflow-cli/reference/QINGFLOW_CLI_MEMBER_CHEATSHEET.md +20 -19
- package/skills/qingflow-cli/reference/QINGFLOW_CLI_ONE_SHOT_CHEATSHEET.md +18 -14
- package/skills/qingflow-cli/reference/QINGFLOW_CLI_RECORD_CREATE_WORKFLOW.md +7 -12
- package/skills/qingflow-cli/reference/QINGFLOW_CLI_RECORD_UPDATE_WORKFLOW.md +2 -1
- package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_ADMIN_CHEATSHEET.md +1 -1
- package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_DATA_RETRIEVAL_WORKFLOW.md +76 -95
- package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_EXPLORATION_REPORT.md +6 -4
- package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_FIELD_DATA_TYPES.md +13 -13
- package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_MEMBER_CHEATSHEET.md +20 -19
- package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_ONE_SHOT_CHEATSHEET.md +18 -14
- package/skills/qingflow-cli/reference/data/README.md +32 -0
- package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_SPECIALIZED_WORKFLOW.md +50 -0
- package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_UPDATE_WORKFLOW.md +2 -1
- package/skills/qingflow-cli/reference/record/analysis/README.md +21 -113
- package/skills/qingflow-cli/reference/record/analysis/analysis-gotchas.md +10 -10
- package/skills/qingflow-cli/reference/record/analysis/analysis-patterns.md +9 -9
- package/skills/qingflow-cli/reference/record/analysis/business-context.md +1 -1
- package/skills/qingflow-cli/reference/record/analysis/confidence-reporting.md +10 -10
- package/skills/qingflow-cli/reference/record/analysis/data-access-playbook.md +52 -80
- package/skills/qingflow-cli/reference/record/analysis/pandas-recipes.md +2 -2
- package/skills/qingflow-common/SKILL.md +7 -4
- package/src/qingflow_mcp/cli/commands/__init__.py +2 -1
- package/src/qingflow_mcp/cli/commands/data.py +134 -0
- package/src/qingflow_mcp/cli/commands/record.py +1 -1
- package/src/qingflow_mcp/cli/context.py +3 -0
- package/src/qingflow_mcp/cli/formatters.py +97 -1
- package/src/qingflow_mcp/public_surface.py +5 -0
- package/src/qingflow_mcp/server.py +2 -0
- package/src/qingflow_mcp/server_app_user.py +4 -0
- package/src/qingflow_mcp/tools/csv_export.py +168 -0
- package/src/qingflow_mcp/tools/data_tools.py +284 -0
- package/src/qingflow_mcp/tools/record_tools.py +11 -46
|
@@ -11,6 +11,7 @@ from ..tools.ai_builder_tools import AiBuilderTools
|
|
|
11
11
|
from ..tools.app_tools import AppTools
|
|
12
12
|
from ..tools.auth_tools import AuthTools
|
|
13
13
|
from ..tools.code_block_tools import CodeBlockTools
|
|
14
|
+
from ..tools.data_tools import DataTools
|
|
14
15
|
from ..tools.export_tools import ExportTools
|
|
15
16
|
from ..tools.feedback_tools import FeedbackTools
|
|
16
17
|
from ..tools.file_tools import FileTools
|
|
@@ -33,6 +34,7 @@ class CliContext:
|
|
|
33
34
|
app: AppTools
|
|
34
35
|
resource: ResourceReadTools
|
|
35
36
|
record: RecordTools
|
|
37
|
+
data: DataTools
|
|
36
38
|
code_block: CodeBlockTools
|
|
37
39
|
imports: ImportTools
|
|
38
40
|
exports: ExportTools
|
|
@@ -64,6 +66,7 @@ def build_cli_context() -> CliContext:
|
|
|
64
66
|
app=AppTools(sessions, backend),
|
|
65
67
|
resource=ResourceReadTools(sessions, backend),
|
|
66
68
|
record=RecordTools(sessions, backend),
|
|
69
|
+
data=DataTools(sessions, backend),
|
|
67
70
|
code_block=CodeBlockTools(sessions, backend),
|
|
68
71
|
imports=ImportTools(sessions, backend),
|
|
69
72
|
exports=ExportTools(sessions, backend),
|
|
@@ -8,7 +8,10 @@ from typing import Any, TextIO
|
|
|
8
8
|
def emit_text_result(result: dict[str, Any], *, hint: str, stream: TextIO) -> None:
|
|
9
9
|
text = _format_cancelled_result(result)
|
|
10
10
|
if text is None:
|
|
11
|
-
if
|
|
11
|
+
if hint in _DATA_FORMAT_HINTS:
|
|
12
|
+
# 数据面失败也必须保留 field_errors 与列表型 hints,不能先走通用失败裁剪。
|
|
13
|
+
text = _format_data_result(result)
|
|
14
|
+
elif _is_failed_result(result) and hint != "task_action_execute":
|
|
12
15
|
text = _format_failed_result(result)
|
|
13
16
|
else:
|
|
14
17
|
formatter = _FORMATTERS.get(hint, _format_generic)
|
|
@@ -90,6 +93,92 @@ def _format_generic(result: dict[str, Any]) -> str:
|
|
|
90
93
|
return "\n".join(lines) + "\n"
|
|
91
94
|
|
|
92
95
|
|
|
96
|
+
def _format_data_result(result: dict[str, Any]) -> str:
|
|
97
|
+
lines = [f"Status: {result.get('status') or ('success' if result.get('ok') is not False else 'failed')}"]
|
|
98
|
+
if result.get("format") == "csv":
|
|
99
|
+
files = result.get("files") if isinstance(result.get("files"), list) else []
|
|
100
|
+
lines.extend(
|
|
101
|
+
[
|
|
102
|
+
f"Local dir: {result.get('local_dir') or '-'}",
|
|
103
|
+
f"Files: {len(files)}",
|
|
104
|
+
]
|
|
105
|
+
)
|
|
106
|
+
for item in files:
|
|
107
|
+
if isinstance(item, dict):
|
|
108
|
+
lines.append(
|
|
109
|
+
f"- part {item.get('part')}: {item.get('local_path')} ({item.get('row_count')} rows)"
|
|
110
|
+
)
|
|
111
|
+
lines.extend(
|
|
112
|
+
[
|
|
113
|
+
f"Rows: {result.get('row_count')}",
|
|
114
|
+
f"Complete: {result.get('complete')}",
|
|
115
|
+
f"Truncated: {result.get('truncated')}",
|
|
116
|
+
f"Safe for final conclusion: {result.get('safe_for_final_conclusion')}",
|
|
117
|
+
f"Stopped reason: {result.get('stopped_reason') or '-'}",
|
|
118
|
+
]
|
|
119
|
+
)
|
|
120
|
+
access = result.get("access") if isinstance(result.get("access"), dict) else {}
|
|
121
|
+
if access:
|
|
122
|
+
sources = access.get("scope_sources") if isinstance(access.get("scope_sources"), list) else []
|
|
123
|
+
lines.append(
|
|
124
|
+
f"Access: level={access.get('level') or '-'} / can_write={access.get('can_write')}"
|
|
125
|
+
f" / scope_sources={','.join(str(item) for item in sources) or '-'}"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
records = result.get("records") if isinstance(result.get("records"), dict) else {}
|
|
129
|
+
if records:
|
|
130
|
+
items = records.get("items") if isinstance(records.get("items"), list) else []
|
|
131
|
+
lines.append(
|
|
132
|
+
"Pagination: "
|
|
133
|
+
f"page={records.get('page')} / requested_page_size={records.get('requested_page_size')} / "
|
|
134
|
+
f"page_size={records.get('page_size')} / total={records.get('total')} / "
|
|
135
|
+
f"has_more={records.get('has_more')} / returned={len(items)}"
|
|
136
|
+
)
|
|
137
|
+
record = result.get("record") if isinstance(result.get("record"), dict) else {}
|
|
138
|
+
if record:
|
|
139
|
+
lines.append(f"Record ID: {record.get('record_id') or '-'}")
|
|
140
|
+
items = result.get("items") if isinstance(result.get("items"), list) else []
|
|
141
|
+
if items:
|
|
142
|
+
lines.append(f"Items: {len(items)}")
|
|
143
|
+
|
|
144
|
+
for key, label in (
|
|
145
|
+
("error_code", "Error Code"),
|
|
146
|
+
("message", "Message"),
|
|
147
|
+
("write_executed", "Write Executed"),
|
|
148
|
+
("retry_safe", "Retry Safe"),
|
|
149
|
+
):
|
|
150
|
+
if key in result:
|
|
151
|
+
lines.append(f"{label}: {result.get(key)}")
|
|
152
|
+
|
|
153
|
+
field_errors = result.get("field_errors") if isinstance(result.get("field_errors"), list) else []
|
|
154
|
+
if field_errors:
|
|
155
|
+
lines.append("Field Errors:")
|
|
156
|
+
_append_data_field_errors(lines, field_errors)
|
|
157
|
+
for index, item in enumerate(items):
|
|
158
|
+
if not isinstance(item, dict) or not isinstance(item.get("field_errors"), list):
|
|
159
|
+
continue
|
|
160
|
+
lines.append(f"Item {index} Field Errors:")
|
|
161
|
+
_append_data_field_errors(lines, item["field_errors"])
|
|
162
|
+
|
|
163
|
+
hints = result.get("hints") if isinstance(result.get("hints"), list) else []
|
|
164
|
+
lines.append(f"Hints: {len(hints)}")
|
|
165
|
+
for hint in hints:
|
|
166
|
+
if isinstance(hint, dict):
|
|
167
|
+
lines.append(f"- {hint.get('code') or '-'}: {hint.get('message') or '-'}")
|
|
168
|
+
else:
|
|
169
|
+
lines.append(f"- {hint}")
|
|
170
|
+
return "\n".join(lines) + "\n"
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _append_data_field_errors(lines: list[str], field_errors: list[Any]) -> None:
|
|
174
|
+
for error in field_errors:
|
|
175
|
+
if isinstance(error, dict):
|
|
176
|
+
lines.append(
|
|
177
|
+
f"- {error.get('path') or '-'}: {error.get('message') or '-'}"
|
|
178
|
+
f" / fix_hint={error.get('fix_hint') or '-'}"
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
93
182
|
def _format_whoami(result: dict[str, Any]) -> str:
|
|
94
183
|
lines = [
|
|
95
184
|
f"User: {result.get('nick_name') or '-'} ({result.get('email') or '-'})",
|
|
@@ -1669,4 +1758,11 @@ _FORMATTERS = {
|
|
|
1669
1758
|
"builder_summary": _format_builder_summary,
|
|
1670
1759
|
"file_upload_local": _format_file_upload_local,
|
|
1671
1760
|
"feedback_submit": _format_feedback_submit,
|
|
1761
|
+
"data_query": _format_data_result,
|
|
1762
|
+
"data_get": _format_data_result,
|
|
1763
|
+
"data_insert": _format_data_result,
|
|
1764
|
+
"data_update": _format_data_result,
|
|
1765
|
+
"data_delete": _format_data_result,
|
|
1672
1766
|
}
|
|
1767
|
+
|
|
1768
|
+
_DATA_FORMAT_HINTS = {"data_query", "data_get", "data_insert", "data_update", "data_delete"}
|
|
@@ -40,6 +40,11 @@ USER_PUBLIC_TOOL_SPECS: tuple[PublicToolSpec, ...] = (
|
|
|
40
40
|
PublicToolSpec(USER_DOMAIN, "workspace_select", ("workspace_select",), ("workspace", "select")),
|
|
41
41
|
PublicToolSpec(USER_DOMAIN, "app_list", ("app_list",), ("app", "list"), cli_show_effective_context=True),
|
|
42
42
|
PublicToolSpec(USER_DOMAIN, "app_get", ("app_get",), ("app", "get"), cli_show_effective_context=True),
|
|
43
|
+
PublicToolSpec(USER_DOMAIN, "data_query", ("data_query",), ("data", "query"), cli_show_effective_context=True),
|
|
44
|
+
PublicToolSpec(USER_DOMAIN, "data_get", ("data_get",), ("data", "get"), cli_show_effective_context=True),
|
|
45
|
+
PublicToolSpec(USER_DOMAIN, "data_insert", ("data_insert",), ("data", "insert"), cli_show_effective_context=True, cli_context_write=True),
|
|
46
|
+
PublicToolSpec(USER_DOMAIN, "data_update", ("data_update",), ("data", "update"), cli_show_effective_context=True, cli_context_write=True),
|
|
47
|
+
PublicToolSpec(USER_DOMAIN, "data_delete", ("data_delete",), ("data", "delete"), cli_show_effective_context=True, cli_context_write=True),
|
|
43
48
|
PublicToolSpec(USER_DOMAIN, "portal_list", ("portal_list",), ("portal", "list"), cli_show_effective_context=True),
|
|
44
49
|
PublicToolSpec(USER_DOMAIN, "portal_get", ("portal_get",), ("portal", "get"), cli_show_effective_context=True),
|
|
45
50
|
PublicToolSpec(USER_DOMAIN, "view_get", ("view_get",), ("view", "get"), cli_show_effective_context=True),
|
|
@@ -7,6 +7,7 @@ from mcp.server.fastmcp import FastMCP
|
|
|
7
7
|
from .backend_client import BackendClient
|
|
8
8
|
from .session_store import SessionStore
|
|
9
9
|
from .tools.app_tools import AppTools
|
|
10
|
+
from .tools.data_tools import DataTools
|
|
10
11
|
from .tools.auth_tools import AuthTools
|
|
11
12
|
from .tools.code_block_tools import CodeBlockTools
|
|
12
13
|
from .tools.feedback_tools import FeedbackTools
|
|
@@ -249,6 +250,7 @@ If the current MCP capability is unsupported, the workflow is awkward, or the us
|
|
|
249
250
|
TaskContextTools(sessions, backend).register(server)
|
|
250
251
|
RoleTools(sessions, backend).register(server)
|
|
251
252
|
AppTools(sessions, backend).register(server)
|
|
253
|
+
DataTools(sessions, backend).register(server)
|
|
252
254
|
QingbiReportTools(sessions, backend).register(server)
|
|
253
255
|
PackageTools(sessions, backend).register(server)
|
|
254
256
|
NavigationTools(sessions, backend).register(server)
|
|
@@ -10,6 +10,7 @@ from .config import DEFAULT_PROFILE
|
|
|
10
10
|
from .response_trim import USER_SERVER_METHOD_MAP, trim_error_response, trim_public_response, wrap_trimmed_methods
|
|
11
11
|
from .session_store import SessionStore
|
|
12
12
|
from .tools.app_tools import AppTools
|
|
13
|
+
from .tools.data_tools import DataTools
|
|
13
14
|
from .tools.auth_tools import AuthTools
|
|
14
15
|
from .tools.code_block_tools import CodeBlockTools
|
|
15
16
|
from .tools.directory_tools import DirectoryTools
|
|
@@ -242,6 +243,7 @@ If the current MCP capability is unsupported, the workflow is awkward, or the us
|
|
|
242
243
|
backend = BackendClient()
|
|
243
244
|
auth = wrap_trimmed_methods(AuthTools(sessions, backend), USER_SERVER_METHOD_MAP)
|
|
244
245
|
apps = wrap_trimmed_methods(AppTools(sessions, backend), USER_SERVER_METHOD_MAP)
|
|
246
|
+
data_tools = wrap_trimmed_methods(DataTools(sessions, backend), USER_SERVER_METHOD_MAP)
|
|
245
247
|
workspace = wrap_trimmed_methods(WorkspaceTools(sessions, backend), USER_SERVER_METHOD_MAP)
|
|
246
248
|
file_tools = wrap_trimmed_methods(FileTools(sessions, backend), USER_SERVER_METHOD_MAP)
|
|
247
249
|
imports = wrap_trimmed_methods(ImportTools(sessions, backend), USER_SERVER_METHOD_MAP)
|
|
@@ -395,6 +397,8 @@ If the current MCP capability is unsupported, the workflow is awkward, or the us
|
|
|
395
397
|
def app_get(profile: str = DEFAULT_PROFILE, app_key: str = "") -> dict:
|
|
396
398
|
return apps.app_get(profile=profile, app_key=app_key)
|
|
397
399
|
|
|
400
|
+
data_tools.register(server)
|
|
401
|
+
|
|
398
402
|
@server.tool()
|
|
399
403
|
def portal_list(profile: str = DEFAULT_PROFILE) -> dict:
|
|
400
404
|
return resources.portal_list(profile=profile)
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
|
|
9
|
+
from ..json_types import JSONObject
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
PageFetcher = Callable[[int, int], JSONObject]
|
|
13
|
+
RowProjector = Callable[[JSONObject], list[str]]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CsvPageFailure(RuntimeError):
|
|
17
|
+
"""后续分页返回结构化业务错误;已写文件保留为不完整结果。"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, payload: JSONObject) -> None:
|
|
20
|
+
super().__init__(str(payload.get("message") or "分页请求失败"))
|
|
21
|
+
self.payload = payload
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CsvShardWriter:
|
|
25
|
+
"""视图无关的 UTF-8 BOM CSV 分片写入器。"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, *, output_dir: Path, file_prefix: str, header: list[str], shard_rows: int) -> None:
|
|
28
|
+
self.output_dir = output_dir
|
|
29
|
+
self.file_prefix = file_prefix
|
|
30
|
+
self.header = header
|
|
31
|
+
self.shard_rows = shard_rows
|
|
32
|
+
self.files: list[JSONObject] = []
|
|
33
|
+
self.row_count = 0
|
|
34
|
+
self._part = 0
|
|
35
|
+
self._current_rows = 0
|
|
36
|
+
self._file: Any | None = None
|
|
37
|
+
self._writer: Any | None = None
|
|
38
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
|
|
40
|
+
def write(self, values: list[str]) -> None:
|
|
41
|
+
if self._current_rows >= self.shard_rows:
|
|
42
|
+
self.close_shard()
|
|
43
|
+
self._ensure_writer().writerow(values)
|
|
44
|
+
self._current_rows += 1
|
|
45
|
+
self.row_count += 1
|
|
46
|
+
|
|
47
|
+
def close_shard(self) -> None:
|
|
48
|
+
if self._file is None:
|
|
49
|
+
return
|
|
50
|
+
path = Path(self._file.name)
|
|
51
|
+
self._file.close()
|
|
52
|
+
self.files.append({"local_path": str(path), "row_count": self._current_rows, "part": len(self.files) + 1})
|
|
53
|
+
self._file = None
|
|
54
|
+
self._writer = None
|
|
55
|
+
self._current_rows = 0
|
|
56
|
+
|
|
57
|
+
def _ensure_writer(self) -> Any:
|
|
58
|
+
if self._writer is not None:
|
|
59
|
+
return self._writer
|
|
60
|
+
self._part += 1
|
|
61
|
+
path = self.output_dir / f"{self.file_prefix}-{self._part:04d}.csv"
|
|
62
|
+
self._file = path.open("w", newline="", encoding="utf-8-sig")
|
|
63
|
+
self._writer = csv.writer(self._file)
|
|
64
|
+
self._writer.writerow(self.header)
|
|
65
|
+
return self._writer
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def export_csv_pages(
|
|
69
|
+
*,
|
|
70
|
+
fetch_page: PageFetcher,
|
|
71
|
+
header: list[str],
|
|
72
|
+
project_row: RowProjector,
|
|
73
|
+
output_dir: Path,
|
|
74
|
+
file_prefix: str,
|
|
75
|
+
page_size: int,
|
|
76
|
+
shard_rows: int,
|
|
77
|
+
time_budget_seconds: float,
|
|
78
|
+
) -> JSONObject:
|
|
79
|
+
"""执行与业务权限无关的分页、CSV 分片和时间预算控制。"""
|
|
80
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
deadline = time.monotonic() + time_budget_seconds
|
|
82
|
+
files: list[JSONObject] = []
|
|
83
|
+
row_count = 0
|
|
84
|
+
fetched_pages = 0
|
|
85
|
+
current_page = 1
|
|
86
|
+
file_handle: Any | None = None
|
|
87
|
+
writer: Any | None = None
|
|
88
|
+
current_rows = 0
|
|
89
|
+
part = 0
|
|
90
|
+
has_more = False
|
|
91
|
+
stopped_reason: str | None = None
|
|
92
|
+
page_error: JSONObject | None = None
|
|
93
|
+
|
|
94
|
+
def close_file() -> None:
|
|
95
|
+
nonlocal file_handle, writer, current_rows
|
|
96
|
+
if file_handle is None:
|
|
97
|
+
return
|
|
98
|
+
path = Path(file_handle.name)
|
|
99
|
+
file_handle.close()
|
|
100
|
+
files.append({"local_path": str(path), "row_count": current_rows, "part": len(files) + 1})
|
|
101
|
+
file_handle = None
|
|
102
|
+
writer = None
|
|
103
|
+
current_rows = 0
|
|
104
|
+
|
|
105
|
+
def get_writer() -> Any:
|
|
106
|
+
nonlocal file_handle, writer, part
|
|
107
|
+
if writer is not None:
|
|
108
|
+
return writer
|
|
109
|
+
part += 1
|
|
110
|
+
path = output_dir / f"{file_prefix}-{part:04d}.csv"
|
|
111
|
+
file_handle = path.open("w", newline="", encoding="utf-8-sig")
|
|
112
|
+
writer = csv.writer(file_handle)
|
|
113
|
+
writer.writerow(header)
|
|
114
|
+
return writer
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
while True:
|
|
118
|
+
page = fetch_page(current_page, page_size)
|
|
119
|
+
records = page.get("records") if isinstance(page, dict) else None
|
|
120
|
+
container = records if isinstance(records, dict) else page
|
|
121
|
+
raw_items = container.get("items", container.get("list", [])) if isinstance(container, dict) else []
|
|
122
|
+
items = raw_items if isinstance(raw_items, list) else []
|
|
123
|
+
has_more = bool(container.get("has_more")) if isinstance(container, dict) else False
|
|
124
|
+
for item in items:
|
|
125
|
+
if not isinstance(item, dict):
|
|
126
|
+
continue
|
|
127
|
+
if current_rows >= shard_rows:
|
|
128
|
+
close_file()
|
|
129
|
+
get_writer().writerow(project_row(item))
|
|
130
|
+
current_rows += 1
|
|
131
|
+
row_count += 1
|
|
132
|
+
fetched_pages += 1
|
|
133
|
+
if not has_more:
|
|
134
|
+
break
|
|
135
|
+
if time.monotonic() >= deadline:
|
|
136
|
+
stopped_reason = "TIME_BUDGET_EXCEEDED"
|
|
137
|
+
break
|
|
138
|
+
current_page += 1
|
|
139
|
+
except CsvPageFailure as exception:
|
|
140
|
+
stopped_reason = "PAGE_FETCH_FAILED"
|
|
141
|
+
page_error = exception.payload
|
|
142
|
+
except Exception:
|
|
143
|
+
# 已落盘分片仍是有效的部分结果;调用方据此禁止形成完整性结论。
|
|
144
|
+
stopped_reason = "PAGE_FETCH_FAILED"
|
|
145
|
+
finally:
|
|
146
|
+
close_file()
|
|
147
|
+
|
|
148
|
+
complete = stopped_reason is None and not has_more
|
|
149
|
+
result: JSONObject = {
|
|
150
|
+
"files": files,
|
|
151
|
+
"row_count": row_count,
|
|
152
|
+
"complete": complete,
|
|
153
|
+
"truncated": not complete,
|
|
154
|
+
"safe_for_final_conclusion": complete,
|
|
155
|
+
"fetched_pages": fetched_pages,
|
|
156
|
+
"stopped_reason": stopped_reason,
|
|
157
|
+
}
|
|
158
|
+
if page_error is not None:
|
|
159
|
+
result["page_error"] = page_error
|
|
160
|
+
return result
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def csv_cell(value: Any) -> str:
|
|
164
|
+
if value is None:
|
|
165
|
+
return ""
|
|
166
|
+
if isinstance(value, (dict, list)):
|
|
167
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
|
168
|
+
return str(value)
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Literal, TypedDict
|
|
6
|
+
|
|
7
|
+
from mcp.server.fastmcp import FastMCP
|
|
8
|
+
|
|
9
|
+
from ..backend_client import BackendRequestContext
|
|
10
|
+
from ..config import DEFAULT_PROFILE
|
|
11
|
+
from ..errors import QingflowApiError, raise_tool_error
|
|
12
|
+
from ..json_types import JSONObject, JSONValue
|
|
13
|
+
from .base import ToolBase
|
|
14
|
+
from .csv_export import CsvPageFailure, csv_cell, export_csv_pages
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
DATA_PAGE_SIZE = 1000
|
|
18
|
+
DATA_CSV_SHARD_ROWS = 20_000
|
|
19
|
+
DATA_UNBOUNDED_ROW_THRESHOLD = 50_000
|
|
20
|
+
DATA_CSV_TIME_BUDGET_SECONDS = 55.0
|
|
21
|
+
|
|
22
|
+
DataFilterOperator = Literal[
|
|
23
|
+
"eq", "ne", "contains", "not_contains", "gt", "gte", "lt", "lte", "in", "not_in"
|
|
24
|
+
]
|
|
25
|
+
DataSortDirection = Literal["asc", "desc"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DataWhereItem(TypedDict):
|
|
29
|
+
"""数据面筛选项;in/not_in 使用数组,其余操作符使用单值。"""
|
|
30
|
+
|
|
31
|
+
field_id: int
|
|
32
|
+
op: DataFilterOperator
|
|
33
|
+
value: JSONValue
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class DataSortItem(TypedDict):
|
|
37
|
+
"""数据面排序项。"""
|
|
38
|
+
|
|
39
|
+
field_id: int
|
|
40
|
+
direction: DataSortDirection
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class DataInsertItem(TypedDict):
|
|
44
|
+
"""数据面新增项,fields 的键为字符串形式 field_id。"""
|
|
45
|
+
|
|
46
|
+
fields: dict[str, JSONValue]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class DataTools(ToolBase):
|
|
50
|
+
"""视图无关的应用数据面工具。"""
|
|
51
|
+
|
|
52
|
+
def register(self, mcp: FastMCP) -> None:
|
|
53
|
+
@mcp.tool()
|
|
54
|
+
def data_query(
|
|
55
|
+
profile: str = DEFAULT_PROFILE,
|
|
56
|
+
app_key: str = "",
|
|
57
|
+
columns: list[int] | None = None,
|
|
58
|
+
where: list[DataWhereItem] | None = None,
|
|
59
|
+
sort: list[DataSortItem] | None = None,
|
|
60
|
+
search: str = "",
|
|
61
|
+
page: int = 1,
|
|
62
|
+
page_size: int = 100,
|
|
63
|
+
include_schema: bool = True,
|
|
64
|
+
all_pages: bool = False,
|
|
65
|
+
output: str = "json",
|
|
66
|
+
) -> JSONObject:
|
|
67
|
+
"""按字段 ID 查询应用数据;先读取 field_capabilities 再构造 where 和 sort。"""
|
|
68
|
+
return self.data_query(
|
|
69
|
+
profile=profile, app_key=app_key, columns=columns or [], where=where or [], sort=sort or [],
|
|
70
|
+
search=search, page=page, page_size=page_size, include_schema=include_schema,
|
|
71
|
+
all_pages=all_pages, output=output,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
@mcp.tool()
|
|
75
|
+
def data_get(
|
|
76
|
+
profile: str = DEFAULT_PROFILE, app_key: str = "", record_id: str = "", include_schema: bool = True
|
|
77
|
+
) -> JSONObject:
|
|
78
|
+
return self.data_get(profile=profile, app_key=app_key, record_id=record_id, include_schema=include_schema)
|
|
79
|
+
|
|
80
|
+
@mcp.tool()
|
|
81
|
+
def data_insert(
|
|
82
|
+
profile: str = DEFAULT_PROFILE, app_key: str = "", items: list[DataInsertItem] | None = None,
|
|
83
|
+
include_schema: bool = True,
|
|
84
|
+
) -> JSONObject:
|
|
85
|
+
"""新增应用数据;每项形如 {"fields": {"字段ID": 值}}。"""
|
|
86
|
+
return self.data_insert(profile=profile, app_key=app_key, items=items or [], include_schema=include_schema)
|
|
87
|
+
|
|
88
|
+
@mcp.tool()
|
|
89
|
+
def data_update(
|
|
90
|
+
profile: str = DEFAULT_PROFILE, app_key: str = "", record_id: str = "",
|
|
91
|
+
fields: dict | None = None, include_schema: bool = True,
|
|
92
|
+
) -> JSONObject:
|
|
93
|
+
return self.data_update(
|
|
94
|
+
profile=profile, app_key=app_key, record_id=record_id, fields=fields or {},
|
|
95
|
+
include_schema=include_schema,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
@mcp.tool()
|
|
99
|
+
def data_delete(
|
|
100
|
+
profile: str = DEFAULT_PROFILE, app_key: str = "", record_ids: list[str | int] | None = None,
|
|
101
|
+
) -> JSONObject:
|
|
102
|
+
return self.data_delete(profile=profile, app_key=app_key, record_ids=record_ids or [])
|
|
103
|
+
|
|
104
|
+
def data_query(
|
|
105
|
+
self, *, profile: str, app_key: str, columns: list[int], where: list[DataWhereItem],
|
|
106
|
+
sort: list[DataSortItem],
|
|
107
|
+
search: str = "", page: int = 1, page_size: int = 100, include_schema: bool = True,
|
|
108
|
+
all_pages: bool = False, output: str = "json",
|
|
109
|
+
) -> JSONObject:
|
|
110
|
+
self._require_app_key(app_key)
|
|
111
|
+
if all_pages and output != "csv":
|
|
112
|
+
raise_tool_error(QingflowApiError.config_error("all_pages 仅支持 output=csv"))
|
|
113
|
+
|
|
114
|
+
def runner(session_profile, context):
|
|
115
|
+
body: JSONObject = {
|
|
116
|
+
"page": page, "page_size": page_size, "columns": columns, "where": where, "sort": sort,
|
|
117
|
+
"search": search, "include_schema": include_schema,
|
|
118
|
+
}
|
|
119
|
+
if not all_pages:
|
|
120
|
+
return self._attach_context(
|
|
121
|
+
self._request_data_plane(context, "POST", self._base_path(app_key) + "/query", json_body=body),
|
|
122
|
+
profile, session_profile.selected_ws_id,
|
|
123
|
+
)
|
|
124
|
+
return self._export_all(
|
|
125
|
+
context=context, profile=profile, ws_id=session_profile.selected_ws_id, app_key=app_key,
|
|
126
|
+
body=body, has_scope=bool(where or search),
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
return self._run(profile, runner, tool_name="数据面查询")
|
|
130
|
+
|
|
131
|
+
def data_get(self, *, profile: str, app_key: str, record_id: str | int, include_schema: bool = True) -> JSONObject:
|
|
132
|
+
self._require_app_key(app_key)
|
|
133
|
+
self._require_record_id(record_id)
|
|
134
|
+
return self._run(
|
|
135
|
+
profile,
|
|
136
|
+
lambda session_profile, context: self._attach_context(
|
|
137
|
+
self._request_data_plane(
|
|
138
|
+
context, "GET", f"{self._base_path(app_key)}/{record_id}",
|
|
139
|
+
params={"include_schema": include_schema},
|
|
140
|
+
), profile, session_profile.selected_ws_id,
|
|
141
|
+
),
|
|
142
|
+
tool_name="数据面单条读取",
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def data_insert(
|
|
146
|
+
self, *, profile: str, app_key: str, items: list[DataInsertItem], include_schema: bool = True
|
|
147
|
+
) -> JSONObject:
|
|
148
|
+
self._require_app_key(app_key)
|
|
149
|
+
return self._write(profile, app_key, "POST", self._base_path(app_key), {"items": items, "include_schema": include_schema}, "数据面新增")
|
|
150
|
+
|
|
151
|
+
def data_update(
|
|
152
|
+
self, *, profile: str, app_key: str, record_id: str | int, fields: dict, include_schema: bool = True
|
|
153
|
+
) -> JSONObject:
|
|
154
|
+
self._require_app_key(app_key)
|
|
155
|
+
self._require_record_id(record_id)
|
|
156
|
+
return self._write(
|
|
157
|
+
profile, app_key, "POST", f"{self._base_path(app_key)}/{record_id}/update",
|
|
158
|
+
{"fields": fields, "include_schema": include_schema}, "数据面更新",
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def data_delete(self, *, profile: str, app_key: str, record_ids: list[str | int]) -> JSONObject:
|
|
162
|
+
self._require_app_key(app_key)
|
|
163
|
+
return self._write(profile, app_key, "POST", self._base_path(app_key) + "/delete", {"record_ids": record_ids}, "数据面删除")
|
|
164
|
+
|
|
165
|
+
def _write(self, profile: str, app_key: str, method: str, path: str, body: JSONObject, tool_name: str) -> JSONObject:
|
|
166
|
+
return self._run(
|
|
167
|
+
profile,
|
|
168
|
+
lambda session_profile, context: self._attach_context(
|
|
169
|
+
self._request_data_plane(context, method, path, json_body=body), profile, session_profile.selected_ws_id,
|
|
170
|
+
),
|
|
171
|
+
tool_name=tool_name,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def _request_data_plane(
|
|
175
|
+
self, context: BackendRequestContext, method: str, path: str, *, params: JSONObject | None = None,
|
|
176
|
+
json_body: JSONValue = None,
|
|
177
|
+
) -> JSONObject:
|
|
178
|
+
raw = self.backend.request(method, context, path, params=params, json_body=json_body, unwrap=False)
|
|
179
|
+
if not isinstance(raw, dict):
|
|
180
|
+
raise QingflowApiError(category="backend", message="数据面返回了非对象响应")
|
|
181
|
+
code = raw.get("code")
|
|
182
|
+
payload = raw.get("data")
|
|
183
|
+
result: JSONObject = dict(payload) if isinstance(payload, dict) else {}
|
|
184
|
+
success = code in (None, 0, 200, 20000) or str(code).lower() in {"success", "ok"}
|
|
185
|
+
result.setdefault("ok", success)
|
|
186
|
+
result.setdefault("status", "success" if success else "failed")
|
|
187
|
+
result.setdefault("hints", [])
|
|
188
|
+
if not success:
|
|
189
|
+
result.setdefault("message", str(raw.get("message") or raw.get("msg") or "数据面请求失败"))
|
|
190
|
+
result.setdefault("backend_code", code)
|
|
191
|
+
return result
|
|
192
|
+
|
|
193
|
+
def _export_all(
|
|
194
|
+
self, *, context: BackendRequestContext, profile: str, ws_id: int | None, app_key: str,
|
|
195
|
+
body: JSONObject, has_scope: bool,
|
|
196
|
+
) -> JSONObject:
|
|
197
|
+
probe_body = dict(body)
|
|
198
|
+
probe_body.update({"page": 1, "page_size": 1, "include_schema": True})
|
|
199
|
+
probe = self._request_data_plane(context, "POST", self._base_path(app_key) + "/query", json_body=probe_body)
|
|
200
|
+
if probe.get("ok") is False:
|
|
201
|
+
# 探测请求没有产生文件,保留后端结构化错误,不把失败误报为空数据成功。
|
|
202
|
+
return self._attach_context(probe, profile, ws_id)
|
|
203
|
+
records = probe.get("records") if isinstance(probe.get("records"), dict) else {}
|
|
204
|
+
total = records.get("total") if isinstance(records, dict) else None
|
|
205
|
+
if isinstance(total, int) and total > DATA_UNBOUNDED_ROW_THRESHOLD and not has_scope:
|
|
206
|
+
return self._attach_context({
|
|
207
|
+
"ok": True, "status": "needs_scope", "app_key": app_key, "format": "csv", "row_count": 0,
|
|
208
|
+
"complete": False, "truncated": True, "safe_for_final_conclusion": False, "files": [],
|
|
209
|
+
"hints": probe.get("hints", []),
|
|
210
|
+
"schema": probe.get("schema", {}),
|
|
211
|
+
"field_capabilities": probe.get("field_capabilities", []),
|
|
212
|
+
"scope": {"reported_total": total, "row_threshold": DATA_UNBOUNDED_ROW_THRESHOLD},
|
|
213
|
+
}, profile, ws_id)
|
|
214
|
+
schema = probe.get("schema") if isinstance(probe.get("schema"), dict) else {}
|
|
215
|
+
fields = schema.get("fields") if isinstance(schema, dict) else None
|
|
216
|
+
field_list = fields if isinstance(fields, list) else []
|
|
217
|
+
business_fields = [field for field in field_list if isinstance(field, dict) and field.get("field_id") is not None]
|
|
218
|
+
columns = [(str(field.get("field_id")), str(field.get("title") or field.get("field_id"))) for field in business_fields]
|
|
219
|
+
header = ["record_id"] + [f"{title}__field_{field_id}" for field_id, title in columns]
|
|
220
|
+
run_dir = Path.home() / ".qingflow" / "data-exports" / datetime.now().strftime("%Y%m%d-%H%M%S-%f")
|
|
221
|
+
latest_hints = probe.get("hints", [])
|
|
222
|
+
latest_schema = schema
|
|
223
|
+
latest_capabilities = probe.get("field_capabilities", [])
|
|
224
|
+
|
|
225
|
+
def fetch_page(page: int, page_size: int) -> JSONObject:
|
|
226
|
+
nonlocal latest_hints, latest_schema, latest_capabilities
|
|
227
|
+
request_body = dict(body)
|
|
228
|
+
# 每页都请求 schema,使最后一页的后端原始 hints 同时准确表达完整性和字段能力。
|
|
229
|
+
request_body.update({"page": page, "page_size": page_size, "include_schema": True})
|
|
230
|
+
response = self._request_data_plane(
|
|
231
|
+
context, "POST", self._base_path(app_key) + "/query", json_body=request_body
|
|
232
|
+
)
|
|
233
|
+
if response.get("ok") is False:
|
|
234
|
+
raise CsvPageFailure(response)
|
|
235
|
+
latest_hints = response.get("hints", [])
|
|
236
|
+
if isinstance(response.get("schema"), dict):
|
|
237
|
+
latest_schema = response["schema"]
|
|
238
|
+
if isinstance(response.get("field_capabilities"), list):
|
|
239
|
+
latest_capabilities = response["field_capabilities"]
|
|
240
|
+
return response
|
|
241
|
+
|
|
242
|
+
def project_row(record: JSONObject) -> list[str]:
|
|
243
|
+
values = record.get("fields") if isinstance(record.get("fields"), dict) else record
|
|
244
|
+
return [str(record.get("record_id") or "")] + [csv_cell(values.get(field_id)) for field_id, _ in columns]
|
|
245
|
+
|
|
246
|
+
exported = export_csv_pages(
|
|
247
|
+
fetch_page=fetch_page, header=header, project_row=project_row, output_dir=run_dir,
|
|
248
|
+
file_prefix="records", page_size=DATA_PAGE_SIZE, shard_rows=DATA_CSV_SHARD_ROWS,
|
|
249
|
+
time_budget_seconds=DATA_CSV_TIME_BUDGET_SECONDS,
|
|
250
|
+
)
|
|
251
|
+
page_error = exported.pop("page_error", None)
|
|
252
|
+
result: JSONObject = {
|
|
253
|
+
"ok": True, "status": "success" if exported["complete"] else "partial", "app_key": app_key,
|
|
254
|
+
"format": "csv", "local_dir": str(run_dir), "fields": business_fields,
|
|
255
|
+
"schema": latest_schema, "field_capabilities": latest_capabilities, "hints": latest_hints,
|
|
256
|
+
**exported,
|
|
257
|
+
}
|
|
258
|
+
if isinstance(page_error, dict):
|
|
259
|
+
# 后续页失败时保留已落盘分片,同时把后端稳定错误字段原样带回。
|
|
260
|
+
result["ok"] = False
|
|
261
|
+
for key in ("error_code", "message", "backend_code", "write_executed", "retry_safe", "field_errors"):
|
|
262
|
+
if key in page_error:
|
|
263
|
+
result[key] = page_error[key]
|
|
264
|
+
if "hints" in page_error:
|
|
265
|
+
result["hints"] = page_error["hints"]
|
|
266
|
+
return self._attach_context(result, profile, ws_id)
|
|
267
|
+
|
|
268
|
+
@staticmethod
|
|
269
|
+
def _base_path(app_key: str) -> str:
|
|
270
|
+
return f"/app/{app_key}/data/v1/records"
|
|
271
|
+
|
|
272
|
+
@staticmethod
|
|
273
|
+
def _attach_context(result: JSONObject, profile: str, ws_id: int | None) -> JSONObject:
|
|
274
|
+
return {"profile": profile, "ws_id": ws_id, **result}
|
|
275
|
+
|
|
276
|
+
@staticmethod
|
|
277
|
+
def _require_app_key(app_key: str) -> None:
|
|
278
|
+
if not str(app_key or "").strip():
|
|
279
|
+
raise_tool_error(QingflowApiError.config_error("app_key is required"))
|
|
280
|
+
|
|
281
|
+
@staticmethod
|
|
282
|
+
def _require_record_id(record_id: str | int) -> None:
|
|
283
|
+
if not str(record_id or "").strip():
|
|
284
|
+
raise_tool_error(QingflowApiError.config_error("record_id is required"))
|