dtflow 0.5.6__py3-none-any.whl → 0.5.8__py3-none-any.whl

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.
dtflow/mcp/cli.py DELETED
@@ -1,388 +0,0 @@
1
- """Datatron MCP CLI 命令
2
-
3
- 提供 MCP 服务的安装和管理命令。
4
- """
5
-
6
- import os
7
- import platform
8
- from pathlib import Path
9
- from typing import Literal
10
-
11
- import orjson
12
-
13
- try:
14
- from rich import print
15
- from rich.console import Console
16
-
17
- console = Console()
18
- except ImportError:
19
- console = None
20
-
21
- def print(*args, **kwargs):
22
- import builtins
23
-
24
- builtins.print(*args, **kwargs)
25
-
26
-
27
- # 支持的目标类型
28
- TargetType = Literal["desktop", "code", "all"]
29
-
30
-
31
- def get_claude_desktop_config_path() -> Path:
32
- """获取 Claude Desktop 配置文件路径"""
33
- system = platform.system()
34
-
35
- if system == "Darwin": # macOS
36
- return (
37
- Path.home()
38
- / "Library"
39
- / "Application Support"
40
- / "Claude"
41
- / "claude_desktop_config.json"
42
- )
43
- elif system == "Windows":
44
- return Path(os.environ.get("APPDATA", "")) / "Claude" / "claude_desktop_config.json"
45
- elif system == "Linux":
46
- return Path.home() / ".config" / "Claude" / "claude_desktop_config.json"
47
- else:
48
- raise RuntimeError(f"不支持的操作系统: {system}")
49
-
50
-
51
- def get_claude_code_config_path() -> Path:
52
- """获取 Claude Code 配置文件路径"""
53
- return Path.home() / ".claude.json"
54
-
55
-
56
- def get_dt_mcp_command() -> list[str]:
57
- """获取 dt-mcp 命令路径
58
-
59
- 使用 python -m 形式,更通用
60
- """
61
- return ["python", "-m", "dtflow.mcp"]
62
-
63
-
64
- def _install_to_config(config_path: Path, name: str, target_name: str) -> bool:
65
- """安装 MCP 服务到指定配置文件
66
-
67
- Returns:
68
- True 成功,False 失败
69
- """
70
- # 确保配置目录存在
71
- config_path.parent.mkdir(parents=True, exist_ok=True)
72
-
73
- # 读取现有配置
74
- config = {}
75
- if config_path.exists():
76
- try:
77
- with open(config_path, "rb") as f:
78
- config = orjson.loads(f.read())
79
- except orjson.JSONDecodeError:
80
- if console:
81
- console.print(
82
- f"[yellow]警告:[/yellow] {target_name} 配置文件格式错误,将创建新配置"
83
- )
84
- else:
85
- print(f"警告: {target_name} 配置文件格式错误,将创建新配置")
86
-
87
- # 确保 mcpServers 字段存在
88
- if "mcpServers" not in config:
89
- config["mcpServers"] = {}
90
-
91
- # 获取命令
92
- command = get_dt_mcp_command()
93
-
94
- # 添加 datatron MCP 服务配置
95
- config["mcpServers"][name] = {
96
- "type": "stdio",
97
- "command": command[0],
98
- "args": command[1:] if len(command) > 1 else [],
99
- }
100
-
101
- # 写入配置
102
- try:
103
- with open(config_path, "wb") as f:
104
- f.write(orjson.dumps(config, option=orjson.OPT_INDENT_2))
105
- return True
106
- except Exception as e:
107
- if console:
108
- console.print(f"[bold red]错误:[/bold red] 无法写入 {target_name} 配置文件: {e}")
109
- else:
110
- print(f"错误: 无法写入 {target_name} 配置文件: {e}")
111
- return False
112
-
113
-
114
- def _uninstall_from_config(config_path: Path, name: str, target_name: str) -> bool:
115
- """从指定配置文件移除 MCP 服务
116
-
117
- Returns:
118
- True 成功移除,False 未找到或失败
119
- """
120
- if not config_path.exists():
121
- return False
122
-
123
- try:
124
- with open(config_path, "rb") as f:
125
- config = orjson.loads(f.read())
126
- except orjson.JSONDecodeError:
127
- return False
128
-
129
- if "mcpServers" not in config or name not in config["mcpServers"]:
130
- return False
131
-
132
- del config["mcpServers"][name]
133
-
134
- try:
135
- with open(config_path, "wb") as f:
136
- f.write(orjson.dumps(config, option=orjson.OPT_INDENT_2))
137
- return True
138
- except Exception:
139
- return False
140
-
141
-
142
- def _show_config_status(config_path: Path, target_name: str):
143
- """显示单个配置文件的状态"""
144
- if console:
145
- console.print(f"\n[bold]{target_name} 配置:[/bold]")
146
- console.print(f" 路径: [bold blue]{config_path}[/bold blue]")
147
- console.print(
148
- f" 存在: {'[green]是[/green]' if config_path.exists() else '[yellow]否[/yellow]'}"
149
- )
150
- else:
151
- print(f"\n{target_name} 配置:")
152
- print(f" 路径: {config_path}")
153
- print(f" 存在: {'是' if config_path.exists() else '否'}")
154
-
155
- if not config_path.exists():
156
- return
157
-
158
- try:
159
- with open(config_path, "rb") as f:
160
- config = orjson.loads(f.read())
161
- except orjson.JSONDecodeError:
162
- if console:
163
- console.print(" [red]配置文件格式错误[/red]")
164
- else:
165
- print(" 配置文件格式错误")
166
- return
167
-
168
- mcp_servers = config.get("mcpServers", {})
169
- if mcp_servers:
170
- if console:
171
- console.print(" 已安装的 MCP 服务:")
172
- else:
173
- print(" 已安装的 MCP 服务:")
174
- for name, server_config in mcp_servers.items():
175
- command = server_config.get("command", "N/A")
176
- is_dt = "data" in name.lower() or "dt" in name.lower() or "transformer" in str(command)
177
- if console:
178
- marker = "[green]*[/green]" if is_dt else " "
179
- console.print(f" {marker} [cyan]{name}[/cyan]")
180
- else:
181
- marker = "*" if is_dt else " "
182
- print(f" {marker} {name}")
183
-
184
-
185
- class MCPCommands:
186
- """MCP 服务管理命令"""
187
-
188
- def install(self, name: str = "datatron", target: str = "code"):
189
- """
190
- 安装 Datatron MCP 服务
191
-
192
- Args:
193
- name: MCP 服务名称(默认: datatron)
194
- target: 安装目标 - 'desktop'(Claude Desktop), 'code'(Claude Code), 'all'(两者)
195
-
196
- 示例:
197
- # 安装到 Claude Code(推荐)
198
- dt mcp install
199
-
200
- # 安装到所有目标
201
- dt mcp install --target all
202
-
203
- # 仅安装到 Claude Desktop
204
- dt mcp install --target desktop
205
-
206
- # 自定义服务名称
207
- dt mcp install --name my-dt
208
- """
209
- command = get_dt_mcp_command()
210
- installed_targets = []
211
-
212
- # Claude Desktop
213
- if target in ("desktop", "all"):
214
- try:
215
- desktop_path = get_claude_desktop_config_path()
216
- if _install_to_config(desktop_path, name, "Claude Desktop"):
217
- installed_targets.append(("Claude Desktop", desktop_path))
218
- except RuntimeError:
219
- if target == "desktop":
220
- if console:
221
- console.print("[bold red]错误:[/bold red] 不支持的操作系统")
222
- else:
223
- print("错误: 不支持的操作系统")
224
- return
225
-
226
- # Claude Code
227
- if target in ("code", "all"):
228
- code_path = get_claude_code_config_path()
229
- if _install_to_config(code_path, name, "Claude Code"):
230
- installed_targets.append(("Claude Code", code_path))
231
-
232
- if not installed_targets:
233
- if console:
234
- console.print("[bold red]错误:[/bold red] 安装失败")
235
- else:
236
- print("错误: 安装失败")
237
- return
238
-
239
- if console:
240
- console.print(f"\n[bold green]Datatron MCP 服务安装成功[/bold green]\n")
241
- console.print(f"服务名称: [bold blue]{name}[/bold blue]")
242
- console.print(f"命令: [bold blue]{' '.join(command)}[/bold blue]")
243
- console.print(f"\n已安装到:")
244
- for target_name, config_path in installed_targets:
245
- console.print(f" - {target_name}: [dim]{config_path}[/dim]")
246
- console.print(f"\n[dim]请重启 Claude Desktop/Code 以使配置生效[/dim]")
247
- else:
248
- print(f"\nDatatron MCP 服务安装成功\n")
249
- print(f"服务名称: {name}")
250
- print(f"命令: {' '.join(command)}")
251
- print(f"\n已安装到:")
252
- for target_name, config_path in installed_targets:
253
- print(f" - {target_name}: {config_path}")
254
- print(f"\n请重启 Claude Desktop/Code 以使配置生效")
255
-
256
- def uninstall(self, name: str = "datatron", target: str = "all"):
257
- """
258
- 移除 Datatron MCP 服务
259
-
260
- Args:
261
- name: MCP 服务名称(默认: datatron)
262
- target: 移除目标 - 'desktop', 'code', 'all'
263
-
264
- 示例:
265
- dt mcp uninstall
266
- dt mcp uninstall --target code
267
- """
268
- removed_targets = []
269
-
270
- # Claude Desktop
271
- if target in ("desktop", "all"):
272
- try:
273
- desktop_path = get_claude_desktop_config_path()
274
- if _uninstall_from_config(desktop_path, name, "Claude Desktop"):
275
- removed_targets.append("Claude Desktop")
276
- except RuntimeError:
277
- pass
278
-
279
- # Claude Code
280
- if target in ("code", "all"):
281
- code_path = get_claude_code_config_path()
282
- if _uninstall_from_config(code_path, name, "Claude Code"):
283
- removed_targets.append("Claude Code")
284
-
285
- if removed_targets:
286
- if console:
287
- console.print(f"\n[bold green]Datatron MCP 服务已移除[/bold green]")
288
- console.print(f"从以下位置移除: {', '.join(removed_targets)}")
289
- console.print(f"\n[dim]请重启 Claude Desktop/Code 以使配置生效[/dim]")
290
- else:
291
- print(f"\nDatatron MCP 服务已移除")
292
- print(f"从以下位置移除: {', '.join(removed_targets)}")
293
- print(f"\n请重启 Claude Desktop/Code 以使配置生效")
294
- else:
295
- if console:
296
- console.print(f"[yellow]未找到名为 '{name}' 的 MCP 服务[/yellow]")
297
- else:
298
- print(f"未找到名为 '{name}' 的 MCP 服务")
299
-
300
- def status(self):
301
- """
302
- 查看 Datatron MCP 服务安装状态
303
-
304
- 示例:
305
- dt mcp status
306
- """
307
- # Claude Desktop
308
- try:
309
- desktop_path = get_claude_desktop_config_path()
310
- _show_config_status(desktop_path, "Claude Desktop")
311
- except RuntimeError:
312
- pass
313
-
314
- # Claude Code
315
- code_path = get_claude_code_config_path()
316
- _show_config_status(code_path, "Claude Code")
317
-
318
- # 检查 mcp 依赖是否安装
319
- if console:
320
- console.print(f"\n[bold]依赖状态:[/bold]")
321
- else:
322
- print(f"\n依赖状态:")
323
-
324
- try:
325
- import mcp
326
-
327
- if console:
328
- console.print(f" mcp: [green]已安装[/green]")
329
- else:
330
- print(f" mcp: 已安装")
331
- except ImportError:
332
- if console:
333
- console.print(f" mcp: [red]未安装[/red] (运行 'pip install dtflow[mcp]')")
334
- else:
335
- print(f" mcp: 未安装 (运行 'pip install dtflow[mcp]')")
336
-
337
- def test(self):
338
- """
339
- 测试 Datatron MCP 服务是否正常工作
340
-
341
- 示例:
342
- dt mcp test
343
- """
344
- if console:
345
- console.print("\n[bold]测试 Datatron MCP 服务...[/bold]\n")
346
- else:
347
- print("\n测试 Datatron MCP 服务...\n")
348
-
349
- # 检查依赖
350
- try:
351
- from dtflow.mcp import mcp
352
-
353
- if console:
354
- console.print("[green]OK[/green] MCP 模块导入成功")
355
- else:
356
- print("OK MCP 模块导入成功")
357
- except ImportError as e:
358
- if console:
359
- console.print(f"[red]FAIL[/red] MCP 模块导入失败: {e}")
360
- console.print("\n请安装 mcp 依赖: pip install datatron[mcp]")
361
- else:
362
- print(f"FAIL MCP 模块导入失败: {e}")
363
- print("\n请安装 mcp 依赖: pip install datatron[mcp]")
364
- return
365
-
366
- # 检查文档
367
- try:
368
- from dtflow.mcp.docs import DOCS, TOPICS
369
-
370
- if console:
371
- console.print(f"[green]OK[/green] 文档加载成功 ({len(TOPICS)} 个主题)")
372
- else:
373
- print(f"OK 文档加载成功 ({len(TOPICS)} 个主题)")
374
- except ImportError as e:
375
- if console:
376
- console.print(f"[red]FAIL[/red] 文档加载失败: {e}")
377
- else:
378
- print(f"FAIL 文档加载失败: {e}")
379
- return
380
-
381
- # 检查命令
382
- command = get_dt_mcp_command()
383
- if console:
384
- console.print(f"[green]OK[/green] MCP 命令: {' '.join(command)}")
385
- console.print("\n[bold green]所有测试通过[/bold green]")
386
- else:
387
- print(f"OK MCP 命令: {' '.join(command)}")
388
- print("\n所有测试通过")