lucidlink-mcp-cloudflared 0.1.0__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.
Potentially problematic release.
This version of lucidlink-mcp-cloudflared might be problematic. Click here for more details.
- lucidlink_mcp_cloudflared/__init__.py +8 -0
- lucidlink_mcp_cloudflared/cli.py +524 -0
- lucidlink_mcp_cloudflared/cloudflared.py +124 -0
- lucidlink_mcp_cloudflared/gateway.py +328 -0
- lucidlink_mcp_cloudflared/oauth.py +403 -0
- lucidlink_mcp_cloudflared-0.1.0.dist-info/METADATA +120 -0
- lucidlink_mcp_cloudflared-0.1.0.dist-info/RECORD +11 -0
- lucidlink_mcp_cloudflared-0.1.0.dist-info/WHEEL +5 -0
- lucidlink_mcp_cloudflared-0.1.0.dist-info/entry_points.txt +2 -0
- lucidlink_mcp_cloudflared-0.1.0.dist-info/licenses/LICENSE +9 -0
- lucidlink_mcp_cloudflared-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Companion package: LucidLink MCP over a Cloudflare quick tunnel.
|
|
2
|
+
|
|
3
|
+
Wraps ``lucidlink-mcp --http`` with a Cloudflare quick tunnel so one command
|
|
4
|
+
produces a paste-ready public URL for claude.ai custom connectors, Claude
|
|
5
|
+
mobile, and Cowork. Kept deliberately OUT of the official ``lucidlink-mcp``
|
|
6
|
+
package: the official server never spawns a tunnel vendor's binary; this
|
|
7
|
+
wrapper is the explicitly-chosen convenience that does.
|
|
8
|
+
"""
|
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
"""The ``lucidlink-mcp-cloudflared`` command.
|
|
2
|
+
|
|
3
|
+
One command, one paste-ready URL: starts the LucidLink MCP server in HTTP
|
|
4
|
+
mode (read-only by default, secret path, loopback bind — all inherited from
|
|
5
|
+
``lucidlink_mcp.http_mode``), opens a Cloudflare quick tunnel to it, prints
|
|
6
|
+
the public URL for claude.ai Settings -> Connectors, self-tests the exact
|
|
7
|
+
edge-and-back path a remote client will use, and tears everything down
|
|
8
|
+
together on exit.
|
|
9
|
+
|
|
10
|
+
A secret path segment is ALWAYS present here — there is deliberately no
|
|
11
|
+
``--no-path-secret`` on a public quick-tunnel URL.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
import signal
|
|
22
|
+
import socket
|
|
23
|
+
import sys
|
|
24
|
+
import threading
|
|
25
|
+
import time
|
|
26
|
+
import urllib.error
|
|
27
|
+
import urllib.parse
|
|
28
|
+
import urllib.request
|
|
29
|
+
from typing import TYPE_CHECKING
|
|
30
|
+
|
|
31
|
+
import uvicorn
|
|
32
|
+
|
|
33
|
+
from lucidlink_mcp.auth import verify_token
|
|
34
|
+
from lucidlink_mcp.http_mode import (
|
|
35
|
+
HttpOptions,
|
|
36
|
+
apply_http_security_defaults,
|
|
37
|
+
ensure_token_configured,
|
|
38
|
+
generate_path_secret,
|
|
39
|
+
has_token_configured,
|
|
40
|
+
serve_http,
|
|
41
|
+
)
|
|
42
|
+
from lucidlink_mcp.setup_cli import read_token_interactive, write_mcp_config
|
|
43
|
+
from lucidlink_mcp_cloudflared import cloudflared
|
|
44
|
+
|
|
45
|
+
if TYPE_CHECKING:
|
|
46
|
+
import subprocess
|
|
47
|
+
|
|
48
|
+
_SECRET_RE = re.compile(r"^[A-Za-z0-9_-]{8,128}$")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_args(argv: list[str]) -> HttpOptions:
|
|
52
|
+
"""Parse CLI flags into the core package's ``HttpOptions``.
|
|
53
|
+
|
|
54
|
+
The tunnel hostname is appended to ``allowed_hosts`` later, once known.
|
|
55
|
+
"""
|
|
56
|
+
parser = argparse.ArgumentParser(
|
|
57
|
+
prog="lucidlink-mcp-cloudflared",
|
|
58
|
+
description=(
|
|
59
|
+
"Serve the LucidLink MCP to claude.ai / Claude mobile / Cowork "
|
|
60
|
+
"through a Cloudflare quick tunnel: one command, one paste-ready "
|
|
61
|
+
"URL. Read-only by default. Requires cloudflared on PATH "
|
|
62
|
+
"(never downloaded for you)."
|
|
63
|
+
),
|
|
64
|
+
epilog=(
|
|
65
|
+
"Quick tunnels are best-effort and get a NEW hostname on every "
|
|
66
|
+
"start. For a stable deployment use the official package "
|
|
67
|
+
"(lucidlink-mcp --http) behind your own pipe - see its "
|
|
68
|
+
"docs/REMOTE-HOSTING.md."
|
|
69
|
+
),
|
|
70
|
+
)
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--port",
|
|
73
|
+
type=int,
|
|
74
|
+
default=8000,
|
|
75
|
+
help="local port to serve on (default: 8000; loopback only)",
|
|
76
|
+
)
|
|
77
|
+
parser.add_argument(
|
|
78
|
+
"--write",
|
|
79
|
+
action="store_true",
|
|
80
|
+
help=(
|
|
81
|
+
"register mutating tools (read-only without this; an explicit "
|
|
82
|
+
"LUCIDLINK_MCP_READ_ONLY / config readOnly still wins)"
|
|
83
|
+
),
|
|
84
|
+
)
|
|
85
|
+
parser.add_argument(
|
|
86
|
+
"--path-secret",
|
|
87
|
+
metavar="SECRET",
|
|
88
|
+
help=(
|
|
89
|
+
"use this secret path segment instead of generating one "
|
|
90
|
+
"(8-128 chars of [A-Za-z0-9_-])"
|
|
91
|
+
),
|
|
92
|
+
)
|
|
93
|
+
ns = parser.parse_args(argv)
|
|
94
|
+
if not 1 <= ns.port <= 65535:
|
|
95
|
+
parser.error("--port must be between 1 and 65535")
|
|
96
|
+
if ns.path_secret is not None and not _SECRET_RE.fullmatch(ns.path_secret):
|
|
97
|
+
parser.error("--path-secret must be 8-128 characters of [A-Za-z0-9_-]")
|
|
98
|
+
secret = ns.path_secret or generate_path_secret()
|
|
99
|
+
return HttpOptions(
|
|
100
|
+
host="127.0.0.1",
|
|
101
|
+
port=ns.port,
|
|
102
|
+
write=ns.write,
|
|
103
|
+
mcp_path=f"/{secret}/mcp",
|
|
104
|
+
allowed_hosts=(),
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _self_test(
|
|
109
|
+
public_url: str,
|
|
110
|
+
*,
|
|
111
|
+
expected_status: int = 200,
|
|
112
|
+
ok_note: str = "paste it into claude.ai and it will work",
|
|
113
|
+
) -> None:
|
|
114
|
+
"""POST an MCP ``initialize`` to the public URL and report the result.
|
|
115
|
+
|
|
116
|
+
Runs on a daemon thread after the tunnel is up: it exercises the exact
|
|
117
|
+
path a remote client will use (out to the Cloudflare edge, back down the
|
|
118
|
+
tunnel, into the server), so a pass here means the pasted URL will work.
|
|
119
|
+
Team mode expects 401 — proof that the endpoint is live AND auth is
|
|
120
|
+
enforced.
|
|
121
|
+
"""
|
|
122
|
+
body = json.dumps(
|
|
123
|
+
{
|
|
124
|
+
"jsonrpc": "2.0",
|
|
125
|
+
"id": 1,
|
|
126
|
+
"method": "initialize",
|
|
127
|
+
"params": {
|
|
128
|
+
"protocolVersion": "2025-06-18",
|
|
129
|
+
"capabilities": {},
|
|
130
|
+
"clientInfo": {"name": "lucidlink-mcp-self-test", "version": "0"},
|
|
131
|
+
},
|
|
132
|
+
}
|
|
133
|
+
).encode("utf-8")
|
|
134
|
+
request = urllib.request.Request( # noqa: S310 — https URL we constructed ourselves
|
|
135
|
+
public_url,
|
|
136
|
+
data=body,
|
|
137
|
+
headers={
|
|
138
|
+
"Content-Type": "application/json",
|
|
139
|
+
"Accept": "application/json, text/event-stream",
|
|
140
|
+
},
|
|
141
|
+
)
|
|
142
|
+
# Fresh *.trycloudflare.com hostnames can take minutes to appear in DNS
|
|
143
|
+
# (and a too-early lookup can seed a negative cache entry in the local
|
|
144
|
+
# resolver), so probe DNS first and keep at it for a while.
|
|
145
|
+
hostname = urllib.parse.urlsplit(public_url).hostname or ""
|
|
146
|
+
start = time.monotonic()
|
|
147
|
+
deadline = start + 240.0
|
|
148
|
+
dns_ok = False
|
|
149
|
+
said_waiting = False
|
|
150
|
+
while time.monotonic() < deadline:
|
|
151
|
+
time.sleep(10.0)
|
|
152
|
+
if not dns_ok:
|
|
153
|
+
try:
|
|
154
|
+
socket.getaddrinfo(hostname, 443)
|
|
155
|
+
dns_ok = True
|
|
156
|
+
except OSError:
|
|
157
|
+
if not said_waiting and time.monotonic() - start > 60.0:
|
|
158
|
+
print(
|
|
159
|
+
" self-test: still waiting for the fresh tunnel "
|
|
160
|
+
"hostname to appear in DNS (normal, can take a "
|
|
161
|
+
"minute or two)...\n",
|
|
162
|
+
file=sys.stderr,
|
|
163
|
+
)
|
|
164
|
+
said_waiting = True
|
|
165
|
+
continue
|
|
166
|
+
try:
|
|
167
|
+
with urllib.request.urlopen(request, timeout=15) as resp: # noqa: S310 — our own https URL
|
|
168
|
+
status = resp.status
|
|
169
|
+
except urllib.error.HTTPError as exc: # 4xx/5xx still proves reachability
|
|
170
|
+
status = exc.code
|
|
171
|
+
except OSError:
|
|
172
|
+
continue
|
|
173
|
+
if status == expected_status:
|
|
174
|
+
print(f" self-test OK: {ok_note}.\n", file=sys.stderr)
|
|
175
|
+
return
|
|
176
|
+
if dns_ok:
|
|
177
|
+
print(
|
|
178
|
+
" self-test: the hostname resolves but the endpoint did not "
|
|
179
|
+
"answer within 4 minutes -\n"
|
|
180
|
+
" check the cloudflared log and your network.\n",
|
|
181
|
+
file=sys.stderr,
|
|
182
|
+
)
|
|
183
|
+
else:
|
|
184
|
+
print(
|
|
185
|
+
" self-test: the hostname never appeared in THIS machine's DNS "
|
|
186
|
+
"within 4 minutes.\n"
|
|
187
|
+
" The tunnel itself is connected, and Claude resolves DNS "
|
|
188
|
+
"elsewhere - it may well\n"
|
|
189
|
+
" work anyway; try opening the URL from a browser or your "
|
|
190
|
+
"phone.\n",
|
|
191
|
+
file=sys.stderr,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _start_self_test(
|
|
196
|
+
public_url: str,
|
|
197
|
+
*,
|
|
198
|
+
expected_status: int = 200,
|
|
199
|
+
ok_note: str = "paste it into claude.ai and it will work",
|
|
200
|
+
) -> None:
|
|
201
|
+
threading.Thread(
|
|
202
|
+
target=_self_test,
|
|
203
|
+
args=(public_url,),
|
|
204
|
+
kwargs={"expected_status": expected_status, "ok_note": ok_note},
|
|
205
|
+
daemon=True,
|
|
206
|
+
).start()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _install_tunnel_signal_cleanup(proc: subprocess.Popen[bytes]) -> None:
|
|
210
|
+
"""Chain SIGTERM/SIGINT handlers that stop cloudflared before exiting.
|
|
211
|
+
|
|
212
|
+
``build_server()`` installs handlers that hard-exit via ``os._exit``
|
|
213
|
+
without knowing about the tunnel child, which would orphan cloudflared.
|
|
214
|
+
We wrap whatever is installed: kill the tunnel (safe — Python-level
|
|
215
|
+
handlers don't run in true async-signal context, and the existing
|
|
216
|
+
handler already does subprocess cleanup), then defer to the previous
|
|
217
|
+
handler. uvicorn's own capture/restore of signal handlers composes with
|
|
218
|
+
this: on its graceful path ``main``'s ``finally`` does the cleanup.
|
|
219
|
+
"""
|
|
220
|
+
|
|
221
|
+
def _chain(signum: int, frame: object) -> None:
|
|
222
|
+
cloudflared.stop_tunnel(proc)
|
|
223
|
+
prev = _previous.get(signum)
|
|
224
|
+
if callable(prev):
|
|
225
|
+
prev(signum, frame)
|
|
226
|
+
os._exit(0)
|
|
227
|
+
|
|
228
|
+
_previous: dict[int, object] = {}
|
|
229
|
+
for sig in (signal.SIGTERM, signal.SIGINT):
|
|
230
|
+
try:
|
|
231
|
+
_previous[sig] = signal.getsignal(sig)
|
|
232
|
+
signal.signal(sig, _chain)
|
|
233
|
+
except ValueError: # non-main thread (tests importing elsewhere)
|
|
234
|
+
pass
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _interactive_token_setup() -> bool:
|
|
238
|
+
"""First-run onboarding: acquire, verify, and store a token inline.
|
|
239
|
+
|
|
240
|
+
Reuses the exact machinery of ``lucidlink-mcp-setup`` (hidden prompt
|
|
241
|
+
with shape check, WebService verification with warn-but-proceed, 0600
|
|
242
|
+
config write), so the token lands where every LucidLink MCP client
|
|
243
|
+
reads it from and future runs of anything just work. Returns False when
|
|
244
|
+
the user aborts.
|
|
245
|
+
"""
|
|
246
|
+
print(
|
|
247
|
+
"\n"
|
|
248
|
+
"No LucidLink token configured - one-time setup.\n"
|
|
249
|
+
"You need a service-account token (a workspace admin mints one in\n"
|
|
250
|
+
"the LucidLink admin app under Service Accounts):\n"
|
|
251
|
+
"https://support.lucidlink.com/hc/en-us/articles/40222074543757\n",
|
|
252
|
+
file=sys.stderr,
|
|
253
|
+
)
|
|
254
|
+
token = read_token_interactive()
|
|
255
|
+
if token is None:
|
|
256
|
+
return False
|
|
257
|
+
print("verifying token against LucidLink WebService...", file=sys.stderr)
|
|
258
|
+
result = verify_token(token)
|
|
259
|
+
if result.ok:
|
|
260
|
+
print(" token verified.", file=sys.stderr)
|
|
261
|
+
else:
|
|
262
|
+
print(
|
|
263
|
+
f" {result.message}\n"
|
|
264
|
+
" Proceeding anyway - the token may still be valid.",
|
|
265
|
+
file=sys.stderr,
|
|
266
|
+
)
|
|
267
|
+
path = write_mcp_config(token)
|
|
268
|
+
print(f" saved to {path} (mode 0600); future runs need no setup.\n", file=sys.stderr)
|
|
269
|
+
return True
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _team_serve(ns: argparse.Namespace) -> None:
|
|
273
|
+
"""Team gateway: one URL, per-member OAuth, per-member backends."""
|
|
274
|
+
from lucidlink_mcp_cloudflared.gateway import Gateway, build_team_app
|
|
275
|
+
from lucidlink_mcp_cloudflared.oauth import LucidLinkTeamAuthProvider, TeamState
|
|
276
|
+
|
|
277
|
+
logging.basicConfig(
|
|
278
|
+
level=logging.INFO,
|
|
279
|
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
280
|
+
stream=sys.stderr,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
state = TeamState()
|
|
284
|
+
gateway = Gateway(
|
|
285
|
+
idle_timeout=ns.idle_timeout,
|
|
286
|
+
max_backends=ns.max_backends,
|
|
287
|
+
write_all=ns.write,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
tunnel_proc = None
|
|
291
|
+
if ns.public_url:
|
|
292
|
+
public_base = str(ns.public_url).rstrip("/")
|
|
293
|
+
else:
|
|
294
|
+
try:
|
|
295
|
+
tunnel_proc, hostname = cloudflared.start_quick_tunnel(ns.port)
|
|
296
|
+
except cloudflared.TunnelError as exc:
|
|
297
|
+
print(f"\n{exc}\n", file=sys.stderr)
|
|
298
|
+
raise SystemExit(2) from None
|
|
299
|
+
public_base = f"https://{hostname}"
|
|
300
|
+
|
|
301
|
+
provider = LucidLinkTeamAuthProvider(state, public_base)
|
|
302
|
+
app = build_team_app(provider, gateway, public_base)
|
|
303
|
+
|
|
304
|
+
members = ", ".join(m.sa_name for m in state.members.values()) or "none yet"
|
|
305
|
+
if ns.write:
|
|
306
|
+
tools_line = " tools: READ-WRITE for every member (--write)"
|
|
307
|
+
else:
|
|
308
|
+
tools_line = " tools: read-only by default (team allow-write <name>)"
|
|
309
|
+
lines = [
|
|
310
|
+
"",
|
|
311
|
+
"lucidlink-mcp team gateway (one URL, per-member auth)",
|
|
312
|
+
"",
|
|
313
|
+
" connector URL - add ONCE as a claude.ai custom connector",
|
|
314
|
+
" (on Team/Enterprise plans a workspace Owner does this):",
|
|
315
|
+
f" {public_base}/mcp",
|
|
316
|
+
"",
|
|
317
|
+
" Each member then clicks Connect in Claude and pastes THEIR OWN",
|
|
318
|
+
" service-account token on the enrollment page. Tokens stay on",
|
|
319
|
+
" this box; Claude receives only revocable access tokens. Each",
|
|
320
|
+
" member gets their own backend process, identity, and audit trail.",
|
|
321
|
+
"",
|
|
322
|
+
f" members enrolled: {members}",
|
|
323
|
+
tools_line,
|
|
324
|
+
" admin commands: team list / team remove / team allow-write <name>",
|
|
325
|
+
]
|
|
326
|
+
if tunnel_proc is not None:
|
|
327
|
+
lines += [
|
|
328
|
+
"",
|
|
329
|
+
" Quick tunnel caveat: the hostname (and thus the connector URL)",
|
|
330
|
+
" changes on every restart - members must reconnect. For a real",
|
|
331
|
+
" deployment use --public-url behind a named tunnel or proxy.",
|
|
332
|
+
]
|
|
333
|
+
lines.append("")
|
|
334
|
+
print("\n".join(lines), file=sys.stderr)
|
|
335
|
+
|
|
336
|
+
if tunnel_proc is not None:
|
|
337
|
+
_install_tunnel_signal_cleanup(tunnel_proc)
|
|
338
|
+
_start_self_test(
|
|
339
|
+
f"{public_base}/mcp",
|
|
340
|
+
expected_status=401,
|
|
341
|
+
ok_note="the endpoint is live and auth is enforced - members can Connect",
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
config = uvicorn.Config(
|
|
345
|
+
app, host="127.0.0.1", port=ns.port, timeout_graceful_shutdown=3, log_level="info"
|
|
346
|
+
)
|
|
347
|
+
try:
|
|
348
|
+
uvicorn.Server(config).run()
|
|
349
|
+
finally:
|
|
350
|
+
gateway.shutdown() # lifespan also does this; double-terminate is harmless
|
|
351
|
+
if tunnel_proc is not None:
|
|
352
|
+
cloudflared.stop_tunnel(tunnel_proc)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def team_main(argv: list[str]) -> None:
|
|
356
|
+
"""The `team` subcommand: serve / list / remove."""
|
|
357
|
+
from lucidlink_mcp_cloudflared.oauth import TeamState
|
|
358
|
+
|
|
359
|
+
parser = argparse.ArgumentParser(
|
|
360
|
+
prog="lucidlink-mcp-cloudflared team",
|
|
361
|
+
description=(
|
|
362
|
+
"Team gateway: one connector URL for everyone, per-member auth "
|
|
363
|
+
"(each person enrolls with their own service-account token), one "
|
|
364
|
+
"isolated backend process per member."
|
|
365
|
+
),
|
|
366
|
+
)
|
|
367
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
368
|
+
p_serve = sub.add_parser("serve", help="run the gateway behind a quick tunnel")
|
|
369
|
+
p_serve.add_argument("--port", type=int, default=8000, help="local port (default 8000)")
|
|
370
|
+
p_serve.add_argument(
|
|
371
|
+
"--idle-timeout",
|
|
372
|
+
type=float,
|
|
373
|
+
default=900.0,
|
|
374
|
+
metavar="SECONDS",
|
|
375
|
+
help="reap a member's backend after this idle time (default 900)",
|
|
376
|
+
)
|
|
377
|
+
p_serve.add_argument(
|
|
378
|
+
"--max-backends", type=int, default=8, help="max live member backends (default 8)"
|
|
379
|
+
)
|
|
380
|
+
p_serve.add_argument(
|
|
381
|
+
"--public-url",
|
|
382
|
+
default=None,
|
|
383
|
+
metavar="URL",
|
|
384
|
+
help=(
|
|
385
|
+
"serve behind your own pipe (named tunnel, reverse proxy) at this "
|
|
386
|
+
"public base URL instead of starting a quick tunnel"
|
|
387
|
+
),
|
|
388
|
+
)
|
|
389
|
+
p_serve.add_argument(
|
|
390
|
+
"--write",
|
|
391
|
+
action="store_true",
|
|
392
|
+
help=(
|
|
393
|
+
"register mutating tools for EVERY member this session (demo "
|
|
394
|
+
"convenience; without it, writes are per-member via allow-write)"
|
|
395
|
+
),
|
|
396
|
+
)
|
|
397
|
+
sub.add_parser("list", help="show enrolled members")
|
|
398
|
+
p_remove = sub.add_parser(
|
|
399
|
+
"remove", help="revoke a member by SA name or id (kills their tokens too)"
|
|
400
|
+
)
|
|
401
|
+
p_remove.add_argument("member")
|
|
402
|
+
p_allow = sub.add_parser(
|
|
403
|
+
"allow-write",
|
|
404
|
+
help="register mutating tools for a member's backend (read-only is the default)",
|
|
405
|
+
)
|
|
406
|
+
p_allow.add_argument("member")
|
|
407
|
+
p_revoke = sub.add_parser("revoke-write", help="return a member's backend to read-only")
|
|
408
|
+
p_revoke.add_argument("member")
|
|
409
|
+
|
|
410
|
+
ns = parser.parse_args(argv)
|
|
411
|
+
if ns.cmd == "list":
|
|
412
|
+
state = TeamState()
|
|
413
|
+
if not state.members:
|
|
414
|
+
print("no members enrolled yet", file=sys.stderr)
|
|
415
|
+
return
|
|
416
|
+
for m in state.members.values():
|
|
417
|
+
mode = "read-write" if m.write else "read-only"
|
|
418
|
+
print(f"{m.sa_name} (sa_id={m.sa_id}, {mode})")
|
|
419
|
+
return
|
|
420
|
+
if ns.cmd == "remove":
|
|
421
|
+
state = TeamState()
|
|
422
|
+
removed = state.remove_member(ns.member)
|
|
423
|
+
if removed is None:
|
|
424
|
+
print(f"no unique member matching {ns.member!r}", file=sys.stderr)
|
|
425
|
+
raise SystemExit(1)
|
|
426
|
+
print(f"removed {removed.sa_name} (sa_id={removed.sa_id}); their tokens are revoked")
|
|
427
|
+
return
|
|
428
|
+
if ns.cmd in ("allow-write", "revoke-write"):
|
|
429
|
+
state = TeamState()
|
|
430
|
+
write = ns.cmd == "allow-write"
|
|
431
|
+
member = state.set_write(ns.member, write)
|
|
432
|
+
if member is None:
|
|
433
|
+
print(f"no unique member matching {ns.member!r}", file=sys.stderr)
|
|
434
|
+
raise SystemExit(1)
|
|
435
|
+
mode = "read-write" if write else "read-only"
|
|
436
|
+
print(
|
|
437
|
+
f"{member.sa_name} is now {mode}. Applies when their backend next\n"
|
|
438
|
+
"spawns (after idle reap, or restart the gateway); if the gateway\n"
|
|
439
|
+
"is running now, restart it so the change is picked up."
|
|
440
|
+
)
|
|
441
|
+
return
|
|
442
|
+
_team_serve(ns)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def main() -> None:
|
|
446
|
+
"""Tunnel + server, torn down together (blocking)."""
|
|
447
|
+
if len(sys.argv) > 1 and sys.argv[1] == "team":
|
|
448
|
+
team_main(sys.argv[2:])
|
|
449
|
+
return
|
|
450
|
+
opts = parse_args(sys.argv[1:])
|
|
451
|
+
if not has_token_configured():
|
|
452
|
+
if sys.stdin.isatty():
|
|
453
|
+
if not _interactive_token_setup():
|
|
454
|
+
raise SystemExit(2)
|
|
455
|
+
else:
|
|
456
|
+
ensure_token_configured() # non-interactive: instructions + exit 2
|
|
457
|
+
apply_http_security_defaults(opts) # before build_server() loads config
|
|
458
|
+
|
|
459
|
+
logging.basicConfig(
|
|
460
|
+
level=logging.INFO,
|
|
461
|
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
462
|
+
stream=sys.stderr,
|
|
463
|
+
)
|
|
464
|
+
log = logging.getLogger("lucidlink_mcp_cloudflared")
|
|
465
|
+
|
|
466
|
+
log.info("starting lucidlink-mcp (streamable-http) behind a quick tunnel")
|
|
467
|
+
from lucidlink_mcp.server import build_server
|
|
468
|
+
|
|
469
|
+
server, on_exit = build_server()
|
|
470
|
+
try:
|
|
471
|
+
proc, hostname = cloudflared.start_quick_tunnel(opts.port)
|
|
472
|
+
except cloudflared.TunnelError as exc:
|
|
473
|
+
print(f"\n{exc}\n", file=sys.stderr)
|
|
474
|
+
try:
|
|
475
|
+
on_exit()
|
|
476
|
+
except Exception: # noqa: BLE001, S110
|
|
477
|
+
pass
|
|
478
|
+
os._exit(2)
|
|
479
|
+
|
|
480
|
+
opts = HttpOptions(
|
|
481
|
+
host=opts.host,
|
|
482
|
+
port=opts.port,
|
|
483
|
+
write=opts.write,
|
|
484
|
+
mcp_path=opts.mcp_path,
|
|
485
|
+
allowed_hosts=(hostname,),
|
|
486
|
+
)
|
|
487
|
+
public_url = f"https://{hostname}{opts.mcp_path}"
|
|
488
|
+
print(
|
|
489
|
+
"\n"
|
|
490
|
+
"lucidlink-mcp over a Cloudflare quick tunnel\n"
|
|
491
|
+
"\n"
|
|
492
|
+
" public URL (paste into claude.ai Settings -> Connectors):\n"
|
|
493
|
+
f" {public_url}\n"
|
|
494
|
+
"\n"
|
|
495
|
+
" Quick tunnels are best-effort: a reconnect mints a NEW hostname\n"
|
|
496
|
+
" (re-paste in Claude). Ctrl+C kills server, tunnel, and URL\n"
|
|
497
|
+
" together. The full URL is a bearer credential - treat it like a\n"
|
|
498
|
+
" password.\n",
|
|
499
|
+
file=sys.stderr,
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
_install_tunnel_signal_cleanup(proc)
|
|
503
|
+
_start_self_test(public_url)
|
|
504
|
+
try:
|
|
505
|
+
serve_http(server, opts, pipe_hint=False)
|
|
506
|
+
finally:
|
|
507
|
+
# Same hard-exit discipline as lucidlink_mcp.__main__: the C++
|
|
508
|
+
# daemon's native teardown SIGSEGVs during interpreter finalization,
|
|
509
|
+
# so clean up best-effort and leave via os._exit.
|
|
510
|
+
cloudflared.stop_tunnel(proc)
|
|
511
|
+
try:
|
|
512
|
+
on_exit()
|
|
513
|
+
except Exception: # noqa: BLE001, S110
|
|
514
|
+
pass
|
|
515
|
+
try:
|
|
516
|
+
sys.stdout.flush()
|
|
517
|
+
sys.stderr.flush()
|
|
518
|
+
except Exception: # noqa: BLE001, S110
|
|
519
|
+
pass
|
|
520
|
+
os._exit(0)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
if __name__ == "__main__":
|
|
524
|
+
main()
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Cloudflare quick-tunnel process management.
|
|
2
|
+
|
|
3
|
+
Spawns ``cloudflared`` (which must already be on PATH — it is never
|
|
4
|
+
downloaded for you, matching the core package's supply-chain stance on the
|
|
5
|
+
Node shim) as a child process, discovers the public ``*.trycloudflare.com``
|
|
6
|
+
hostname via cloudflared's local metrics endpoint, and tears the tunnel down
|
|
7
|
+
with the server. Quick tunnels are outbound-only: no inbound ports, no
|
|
8
|
+
firewall configuration, and nothing persists after exit.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import shutil
|
|
16
|
+
import socket
|
|
17
|
+
import subprocess
|
|
18
|
+
import tempfile
|
|
19
|
+
import time
|
|
20
|
+
import urllib.request
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger("lucidlink_mcp_cloudflared")
|
|
23
|
+
|
|
24
|
+
_HOSTNAME_TIMEOUT_SECONDS = 30.0
|
|
25
|
+
_POLL_INTERVAL_SECONDS = 0.5
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TunnelError(RuntimeError):
|
|
29
|
+
"""Quick tunnel could not be started (message is user-actionable)."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_INSTALL_HINT = (
|
|
33
|
+
"cloudflared not found on PATH. Install it and re-run:\n"
|
|
34
|
+
" macOS: brew install cloudflared\n"
|
|
35
|
+
" Windows: winget install --id Cloudflare.cloudflared\n"
|
|
36
|
+
" Linux: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/\n"
|
|
37
|
+
"Or use the official package with your own pipe:\n"
|
|
38
|
+
" lucidlink-mcp --http + cloudflared tunnel --url http://127.0.0.1:<port>"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _free_port() -> int:
|
|
43
|
+
with socket.socket() as sock:
|
|
44
|
+
sock.bind(("127.0.0.1", 0))
|
|
45
|
+
return int(sock.getsockname()[1])
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _query_hostname(metrics_port: int) -> str | None:
|
|
49
|
+
"""Ask cloudflared's metrics endpoint for the quick-tunnel hostname."""
|
|
50
|
+
try:
|
|
51
|
+
with urllib.request.urlopen( # noqa: S310 — fixed localhost URL
|
|
52
|
+
f"http://127.0.0.1:{metrics_port}/quicktunnel", timeout=2
|
|
53
|
+
) as resp:
|
|
54
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
55
|
+
except (OSError, ValueError):
|
|
56
|
+
return None
|
|
57
|
+
hostname = str(data.get("hostname") or "")
|
|
58
|
+
return hostname or None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def start_quick_tunnel(local_port: int) -> tuple[subprocess.Popen[bytes], str]:
|
|
62
|
+
"""Spawn a quick tunnel to ``127.0.0.1:local_port``.
|
|
63
|
+
|
|
64
|
+
Returns ``(process, public_hostname)``. Raises :class:`TunnelError` with
|
|
65
|
+
an actionable message when cloudflared is missing, dies early, or never
|
|
66
|
+
reports a hostname (the message includes the cloudflared log path).
|
|
67
|
+
"""
|
|
68
|
+
exe = shutil.which("cloudflared")
|
|
69
|
+
if exe is None:
|
|
70
|
+
raise TunnelError(_INSTALL_HINT)
|
|
71
|
+
|
|
72
|
+
metrics_port = _free_port()
|
|
73
|
+
log_file = tempfile.NamedTemporaryFile( # noqa: SIM115 — fd handed to Popen; parent closes below
|
|
74
|
+
mode="wb", prefix="cloudflared-", suffix=".log", delete=False
|
|
75
|
+
)
|
|
76
|
+
cmd = [
|
|
77
|
+
exe,
|
|
78
|
+
"tunnel",
|
|
79
|
+
"--url",
|
|
80
|
+
f"http://127.0.0.1:{local_port}",
|
|
81
|
+
"--metrics",
|
|
82
|
+
f"127.0.0.1:{metrics_port}",
|
|
83
|
+
"--no-autoupdate",
|
|
84
|
+
"--protocol",
|
|
85
|
+
"http2", # TCP 443; more corporate-firewall-friendly than QUIC
|
|
86
|
+
]
|
|
87
|
+
proc = subprocess.Popen( # noqa: S603 — fixed args; exe resolved via shutil.which
|
|
88
|
+
cmd, stdout=log_file, stderr=subprocess.STDOUT
|
|
89
|
+
)
|
|
90
|
+
log_file.close() # child holds its own copy of the fd
|
|
91
|
+
|
|
92
|
+
deadline = time.monotonic() + _HOSTNAME_TIMEOUT_SECONDS
|
|
93
|
+
while time.monotonic() < deadline:
|
|
94
|
+
if proc.poll() is not None:
|
|
95
|
+
raise TunnelError(
|
|
96
|
+
f"cloudflared exited (rc={proc.returncode}) before the tunnel "
|
|
97
|
+
f"came up; its log: {log_file.name}"
|
|
98
|
+
)
|
|
99
|
+
hostname = _query_hostname(metrics_port)
|
|
100
|
+
if hostname:
|
|
101
|
+
log.info("quick tunnel up: %s (cloudflared log: %s)", hostname, log_file.name)
|
|
102
|
+
return proc, hostname
|
|
103
|
+
time.sleep(_POLL_INTERVAL_SECONDS)
|
|
104
|
+
|
|
105
|
+
stop_tunnel(proc)
|
|
106
|
+
raise TunnelError(
|
|
107
|
+
"cloudflared started but no tunnel hostname appeared within "
|
|
108
|
+
f"{_HOSTNAME_TIMEOUT_SECONDS:.0f}s. Some networks block tunnel "
|
|
109
|
+
"services (trycloudflare.com) — try another network or ask IT. "
|
|
110
|
+
f"cloudflared log: {log_file.name}"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def stop_tunnel(proc: subprocess.Popen[bytes]) -> None:
|
|
115
|
+
"""Terminate cloudflared, escalating to kill. Never raises."""
|
|
116
|
+
try:
|
|
117
|
+
proc.terminate()
|
|
118
|
+
try:
|
|
119
|
+
proc.wait(timeout=5)
|
|
120
|
+
except subprocess.TimeoutExpired:
|
|
121
|
+
proc.kill()
|
|
122
|
+
proc.wait(timeout=5)
|
|
123
|
+
except Exception: # noqa: BLE001, S110 — teardown is best-effort by contract
|
|
124
|
+
pass
|