-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
503 lines (400 loc) · 17 KB
/
Copy pathcli.py
File metadata and controls
503 lines (400 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#!/usr/bin/env python3
"""
clawconnect — Connector management CLI for OpenClaw agents
Cowork-style connector experience for the terminal.
"""
import sys
import json
import os
from pathlib import Path
try:
import click
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from rich import box
except ImportError:
print("Missing dependencies. Run: pip install click rich requests")
sys.exit(1)
console = Console()
# ============================================================
# ASCII ART — Dangerous Pac-Man
# ============================================================
PACMAN_ART = r"""
[bold yellow]
████████████████████████████████████████
██ ██
██ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ██
██ ░░ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ░░ ██
██ ░░ ██▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀██ ░░ ██
██ ░░ ██ ╔══╗ ╔╗ ██ ░░ ██
██ ░░ ██ ║██║ ╠╣ CLAWCON ██ ░░ ██
██ ░░ ██ ╚══╝ ╚╝ NECT ██ ░░ ██
██ ░░ ██▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄██ ░░ ██
██ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ██
██ ██
████████████████████████████████████████
[/bold yellow]
[bold red]
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░ ▄████▄ ██████ ██████ ░░
░░ ██ ██ ██ ██ ██ ██ ░░
░░ ██ ██ ██ ██ ██ ██ ░░
░░ ▀████▀ ██████ ██████ ░░
░░ ░░░░░░░░░░░░░░░░░░░░ ░░
░░ ░░░ CONSUME. ░░░░░ ░░
░░░ ░░ CONNECT. ░░░░ ░░░
░░░░░ CONTROL. ░░░░░░░░
[/bold red]
[dim] Cowork-style connectors for OpenClaw agents[/dim]
[dim] github.com/terence-ma/clawconnect[/dim]
"""
PACMAN_SMALL = "[bold yellow]⬤[/bold yellow][bold red]꩜[/bold red]"
def print_banner():
console.print(PACMAN_ART)
# ============================================================
# CONFIG
# ============================================================
CONFIG_DIR = Path.home() / ".clawconnect"
CONNECTORS_DIR = CONFIG_DIR / "connectors"
TOKENS_FILE = CONFIG_DIR / "tokens.json"
SETTINGS_FILE = CONFIG_DIR / "settings.json"
def ensure_config():
CONFIG_DIR.mkdir(exist_ok=True)
CONNECTORS_DIR.mkdir(exist_ok=True)
if not TOKENS_FILE.exists():
TOKENS_FILE.write_text(json.dumps({}))
if not SETTINGS_FILE.exists():
SETTINGS_FILE.write_text(json.dumps({
"openclaw_gateway": "ws://127.0.0.1:18789",
"openclaw_token": "",
"telegram_bot_token": "",
"mcp_port": 18800
}))
def load_settings():
ensure_config()
return json.loads(SETTINGS_FILE.read_text())
def save_settings(settings):
SETTINGS_FILE.write_text(json.dumps(settings, indent=2))
def load_tokens():
ensure_config()
return json.loads(TOKENS_FILE.read_text())
def save_tokens(tokens):
TOKENS_FILE.write_text(json.dumps(tokens, indent=2))
# ============================================================
# CLI ROOT
# ============================================================
@click.group()
@click.version_option("1.0.0", prog_name="clawconnect")
def cli():
"""
\b
clawconnect — Cowork-style connectors for OpenClaw agents.
Manage, authenticate, and bridge connectors across OpenClaw and Cowork.
"""
ensure_config()
# ============================================================
# INIT
# ============================================================
@cli.command()
def init():
"""Interactive setup — configure OpenClaw gateway and Telegram."""
print_banner()
console.print(Panel(
"[bold]Welcome to clawconnect setup[/bold]\n"
"This will configure your OpenClaw gateway connection\n"
"and optional Telegram companion bot.",
border_style="yellow"
))
settings = load_settings()
console.print("\n[bold cyan]OpenClaw Gateway[/bold cyan]")
gw = click.prompt(
"Gateway URL",
default=settings.get("openclaw_gateway", "ws://127.0.0.1:18789")
)
token = click.prompt(
"Gateway token",
default=settings.get("openclaw_token", ""),
hide_input=True
)
console.print("\n[bold cyan]Telegram Companion (optional)[/bold cyan]")
tg = click.prompt(
"Telegram bot token (leave blank to skip)",
default=settings.get("telegram_bot_token", ""),
hide_input=True
)
console.print("\n[bold cyan]MCP Bridge[/bold cyan]")
port = click.prompt(
"MCP server port",
default=settings.get("mcp_port", 18800),
type=int
)
settings.update({
"openclaw_gateway": gw,
"openclaw_token": token,
"telegram_bot_token": tg,
"mcp_port": port
})
save_settings(settings)
console.print(Panel(
"[bold green]✓ Setup complete[/bold green]\n"
f"Config saved to: {SETTINGS_FILE}\n\n"
"Next steps:\n"
" [cyan]clawconnect connectors list[/cyan] — see available connectors\n"
" [cyan]clawconnect connect gmail[/cyan] — authenticate Gmail\n"
" [cyan]clawconnect bridge start[/cyan] — start MCP bridge server\n"
" [cyan]clawconnect telegram start[/cyan] — start Telegram companion",
border_style="green"
))
# ============================================================
# CONNECTORS
# ============================================================
@cli.group()
def connectors():
"""Manage available connectors."""
pass
@connectors.command("list")
@click.option("--connected", is_flag=True, help="Show only connected connectors")
def connectors_list(connected):
"""List all available connectors."""
from clawconnect.connectors.registry import CONNECTOR_REGISTRY
tokens = load_tokens()
table = Table(
title=f"{PACMAN_SMALL} [bold]Available Connectors[/bold]",
box=box.ROUNDED,
border_style="yellow",
show_header=True,
header_style="bold cyan"
)
table.add_column("Connector", style="bold white", width=20)
table.add_column("Category", style="dim", width=15)
table.add_column("Auth", width=10)
table.add_column("Status", width=12)
table.add_column("Description", width=40)
for name, info in CONNECTOR_REGISTRY.items():
is_connected = name in tokens
if connected and not is_connected:
continue
status = "[bold green]● Connected[/bold green]" if is_connected else "[dim]○ Not connected[/dim]"
auth_type = info.get("auth", "oauth2")
table.add_row(
name,
info.get("category", "general"),
auth_type,
status,
info.get("description", "")
)
console.print(table)
console.print(
f"\n[dim]Connect a service: [cyan]clawconnect connect <name>[/cyan][/dim]"
)
@connectors.command("info")
@click.argument("name")
def connectors_info(name):
"""Show detailed info about a connector."""
from clawconnect.connectors.registry import CONNECTOR_REGISTRY
if name not in CONNECTOR_REGISTRY:
console.print(f"[red]Unknown connector: {name}[/red]")
console.print(f"Run [cyan]clawconnect connectors list[/cyan] to see available connectors.")
return
info = CONNECTOR_REGISTRY[name]
tokens = load_tokens()
is_connected = name in tokens
status_line = "[bold green]● Connected[/bold green]" if is_connected else "[dim]○ Not connected[/dim]"
panel_content = (
f"[bold]{info.get('display_name', name)}[/bold] {status_line}\n\n"
f"{info.get('description', '')}\n\n"
f"[bold cyan]Auth type:[/bold cyan] {info.get('auth', 'oauth2')}\n"
f"[bold cyan]Category:[/bold cyan] {info.get('category', 'general')}\n\n"
f"[bold cyan]Available actions:[/bold cyan]\n"
)
for action in info.get("actions", []):
panel_content += f" • {action['name']}: {action.get('description', '')}\n"
panel_content += f"\n[dim]Connect: [cyan]clawconnect connect {name}[/cyan][/dim]"
console.print(Panel(panel_content, title=f"[bold yellow]{name}[/bold yellow]", border_style="yellow"))
# ============================================================
# CONNECT / DISCONNECT
# ============================================================
@cli.command()
@click.argument("connector_name")
@click.option("--api-key", help="Use API key instead of OAuth")
def connect(connector_name, api_key):
"""Authenticate a connector."""
from clawconnect.connectors.registry import CONNECTOR_REGISTRY
from clawconnect.connectors.oauth import run_oauth_flow
if connector_name not in CONNECTOR_REGISTRY:
console.print(f"[red]Unknown connector: {connector_name}[/red]")
return
info = CONNECTOR_REGISTRY[connector_name]
tokens = load_tokens()
console.print(Panel(
f"[bold]Connecting {info.get('display_name', connector_name)}[/bold]\n"
f"{info.get('description', '')}",
border_style="cyan"
))
auth_type = info.get("auth", "oauth2")
if api_key or auth_type == "api_key":
if not api_key:
api_key = click.prompt(f"Enter API key for {connector_name}", hide_input=True)
tokens[connector_name] = {"type": "api_key", "key": api_key}
save_tokens(tokens)
console.print(f"[bold green]✓ {connector_name} connected via API key[/bold green]")
elif auth_type == "oauth2":
console.print(f"\n[cyan]Starting OAuth flow for {connector_name}...[/cyan]")
console.print("[dim]A browser window will open. Complete authentication there.[/dim]\n")
try:
token_data = run_oauth_flow(connector_name, info)
tokens[connector_name] = token_data
save_tokens(tokens)
console.print(f"[bold green]✓ {connector_name} connected successfully[/bold green]")
except Exception as e:
console.print(f"[red]OAuth flow failed: {e}[/red]")
console.print("[dim]You can also use: clawconnect connect {connector_name} --api-key YOUR_KEY[/dim]")
else:
console.print(f"[red]Unknown auth type: {auth_type}[/red]")
@cli.command()
@click.argument("connector_name")
def disconnect(connector_name):
"""Remove a connector's credentials."""
tokens = load_tokens()
if connector_name not in tokens:
console.print(f"[yellow]{connector_name} is not connected.[/yellow]")
return
if click.confirm(f"Disconnect {connector_name}? This will remove stored credentials."):
del tokens[connector_name]
save_tokens(tokens)
console.print(f"[green]✓ {connector_name} disconnected[/green]")
# ============================================================
# BRIDGE — MCP server
# ============================================================
@cli.group()
def bridge():
"""MCP bridge server — makes connectors available to OpenClaw and Cowork."""
pass
@bridge.command("start")
@click.option("--port", default=None, type=int, help="Port to listen on")
@click.option("--daemon", is_flag=True, help="Run in background")
def bridge_start(port, daemon):
"""Start the MCP bridge server."""
settings = load_settings()
port = port or settings.get("mcp_port", 18800)
console.print(Panel(
f"[bold green]Starting MCP bridge server[/bold green]\n\n"
f"Port: [cyan]{port}[/cyan]\n"
f"MCP URL: [cyan]http://127.0.0.1:{port}/mcp[/cyan]\n\n"
f"Add to OpenClaw openclaw.json:\n"
f'[dim]{{"mcp": {{"servers": {{"clawconnect": {{"url": "http://127.0.0.1:{port}/mcp"}}}}}}}}[/dim]\n\n'
f"Add to Cowork as custom connector:\n"
f"[dim]URL: http://127.0.0.1:{port}/mcp[/dim]",
border_style="green"
))
from clawconnect.bridge.server import run_mcp_server
run_mcp_server(port=port, daemon=daemon)
@bridge.command("status")
def bridge_status():
"""Check if the MCP bridge is running."""
settings = load_settings()
port = settings.get("mcp_port", 18800)
try:
import requests
r = requests.get(f"http://127.0.0.1:{port}/health", timeout=2)
if r.status_code == 200:
console.print(f"[bold green]● Bridge running[/bold green] on port {port}")
else:
console.print(f"[red]● Bridge unhealthy[/red] — status {r.status_code}")
except Exception:
console.print(f"[dim]○ Bridge not running[/dim] (port {port})")
console.print(f"Start with: [cyan]clawconnect bridge start[/cyan]")
# ============================================================
# TELEGRAM
# ============================================================
@cli.group()
def telegram():
"""Telegram companion bot — connector management via chat."""
pass
@telegram.command("start")
def telegram_start():
"""Start the Telegram companion bot."""
settings = load_settings()
token = settings.get("telegram_bot_token", "")
if not token:
console.print("[red]No Telegram bot token configured.[/red]")
console.print("Run [cyan]clawconnect init[/cyan] to set up your bot token.")
return
console.print(Panel(
"[bold green]Starting Telegram companion bot[/bold green]\n\n"
"Your agents can now request connector operations via Telegram.\n"
"Users will be prompted to authorise each action.\n\n"
"[dim]Press Ctrl+C to stop[/dim]",
border_style="green"
))
from clawconnect.telegram.bot import run_bot
run_bot(token)
# ============================================================
# RUN — Execute a connector action directly
# ============================================================
@cli.command()
@click.argument("connector_name")
@click.argument("action")
@click.option("--params", default="{}", help="JSON params for the action")
@click.option("--agent", default=None, help="Agent ID making the request")
def run(connector_name, action, params, agent):
"""Execute a connector action directly from CLI."""
from clawconnect.connectors.registry import CONNECTOR_REGISTRY
from clawconnect.connectors.executor import execute_action
tokens = load_tokens()
if connector_name not in tokens:
console.print(f"[red]{connector_name} is not connected.[/red]")
console.print(f"Connect first: [cyan]clawconnect connect {connector_name}[/cyan]")
return
if connector_name not in CONNECTOR_REGISTRY:
console.print(f"[red]Unknown connector: {connector_name}[/red]")
return
try:
params_dict = json.loads(params)
except json.JSONDecodeError:
console.print(f"[red]Invalid JSON params: {params}[/red]")
return
console.print(f"[dim]Running {connector_name}.{action}...[/dim]")
try:
result = execute_action(
connector_name=connector_name,
action=action,
params=params_dict,
token_data=tokens[connector_name],
connector_info=CONNECTOR_REGISTRY[connector_name]
)
console.print(Panel(
json.dumps(result, indent=2),
title=f"[bold green]✓ {connector_name}.{action}[/bold green]",
border_style="green"
))
except Exception as e:
console.print(f"[red]Action failed: {e}[/red]")
# ============================================================
# STATUS
# ============================================================
@cli.command()
def status():
"""Show overall clawconnect status."""
print_banner()
settings = load_settings()
tokens = load_tokens()
table = Table(box=box.SIMPLE, show_header=False, padding=(0, 2))
table.add_column("Key", style="bold cyan")
table.add_column("Value")
gw = settings.get("openclaw_gateway", "not set")
tg = "configured" if settings.get("telegram_bot_token") else "not configured"
port = settings.get("mcp_port", 18800)
table.add_row("OpenClaw gateway", gw)
table.add_row("Telegram bot", tg)
table.add_row("MCP bridge port", str(port))
table.add_row("Connected services", str(len(tokens)))
if tokens:
table.add_row("", "")
for name in tokens:
table.add_row(f" ● {name}", "[green]connected[/green]")
console.print(Panel(table, title=f"{PACMAN_SMALL} [bold]clawconnect status[/bold]", border_style="yellow"))
if __name__ == "__main__":
cli()