entitybind 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.
- entitybind/__init__.py +8 -0
- entitybind/__main__.py +3 -0
- entitybind/cli.py +510 -0
- entitybind/commands_api.py +900 -0
- entitybind/commands_auth.py +393 -0
- entitybind/commands_mcp.py +236 -0
- entitybind/context.py +100 -0
- entitybind/credentials.py +349 -0
- entitybind/device.py +433 -0
- entitybind/errors.py +184 -0
- entitybind/files.py +78 -0
- entitybind/http.py +319 -0
- entitybind/mcpconfig.py +778 -0
- entitybind/products.py +126 -0
- entitybind/py.typed +0 -0
- entitybind/records.py +234 -0
- entitybind/runtime.py +163 -0
- entitybind/submissions.py +83 -0
- entitybind-0.1.0.dist-info/METADATA +251 -0
- entitybind-0.1.0.dist-info/RECORD +23 -0
- entitybind-0.1.0.dist-info/WHEEL +4 -0
- entitybind-0.1.0.dist-info/entry_points.txt +2 -0
- entitybind-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""login, logout and whoami."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from entitybind.context import Context
|
|
9
|
+
from entitybind.credentials import Credential, credentials_path
|
|
10
|
+
from entitybind.device import (
|
|
11
|
+
DeviceAuthorization,
|
|
12
|
+
PendingStore,
|
|
13
|
+
credential_from_grant,
|
|
14
|
+
poll_for_token,
|
|
15
|
+
revoke_key,
|
|
16
|
+
revoke_token,
|
|
17
|
+
start_device_authorization,
|
|
18
|
+
)
|
|
19
|
+
from entitybind.errors import (
|
|
20
|
+
EXIT_AUTH,
|
|
21
|
+
EXIT_OK,
|
|
22
|
+
ApiError,
|
|
23
|
+
AuthError,
|
|
24
|
+
CliError,
|
|
25
|
+
ConflictError,
|
|
26
|
+
NetworkError,
|
|
27
|
+
NotFoundError,
|
|
28
|
+
PendingError,
|
|
29
|
+
UsageError,
|
|
30
|
+
)
|
|
31
|
+
from entitybind.http import ApiClient
|
|
32
|
+
from entitybind.products import CORE, Product, is_safe_browser_url
|
|
33
|
+
|
|
34
|
+
DEFAULT_CORE_SCOPE = "resolve"
|
|
35
|
+
CORE_LOGIN_SCOPES = ("read", "resolve", "review", "admin")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def requested_scope(product: Product, raw: str | None) -> str | None:
|
|
39
|
+
"""Core takes one scope name. AML takes agent, partner or its own scope names."""
|
|
40
|
+
if product is CORE:
|
|
41
|
+
scope = raw or DEFAULT_CORE_SCOPE
|
|
42
|
+
if scope not in CORE_LOGIN_SCOPES:
|
|
43
|
+
raise UsageError(
|
|
44
|
+
f"argument --scope: invalid choice for {product.label}: {scope!r} "
|
|
45
|
+
f"(choose from {', '.join(CORE_LOGIN_SCOPES)})"
|
|
46
|
+
)
|
|
47
|
+
return scope
|
|
48
|
+
return " ".join((raw or "").replace(",", " ").split()) or None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _refuse_scope_change(product: Product, base_url: str, stored: Any, scope: str) -> None:
|
|
52
|
+
"""Core scopes are disjoint: replacing the stored key would break every other command."""
|
|
53
|
+
if product is CORE and isinstance(stored, str) and stored != scope:
|
|
54
|
+
admin = " and set it as ENTITYBIND_ADMIN_KEY for keys commands" if scope == "admin" else ""
|
|
55
|
+
raise ConflictError(
|
|
56
|
+
f"a {stored}-scope key for {product.label} at {base_url} is already stored; signing "
|
|
57
|
+
f"in with --scope {scope} would replace it and leave it active",
|
|
58
|
+
code="scope_change",
|
|
59
|
+
hint=f"to keep it, get the {scope} key without storing it: `entitybind login --scope "
|
|
60
|
+
f"{scope} --print-key --no-store`{admin}; to replace it, run "
|
|
61
|
+
"`entitybind logout --revoke` first",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _replaced_note(product: Product, key_id: Any) -> str:
|
|
66
|
+
which = f" ({key_id})" if isinstance(key_id, str) else ""
|
|
67
|
+
if product is CORE:
|
|
68
|
+
how = (
|
|
69
|
+
f"with `entitybind keys revoke {key_id}` and an admin key, or in the portal's key list"
|
|
70
|
+
if which
|
|
71
|
+
else "in the portal's key list"
|
|
72
|
+
)
|
|
73
|
+
else:
|
|
74
|
+
how = "by a workspace administrator in AML Onboard"
|
|
75
|
+
return (
|
|
76
|
+
f"note: this replaced the previously stored key{which}, which stays active until it "
|
|
77
|
+
f"expires or is revoked {how}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def default_key_name(platform: str, now: float) -> str:
|
|
82
|
+
"""A label for the key list that names the client and day, not the machine."""
|
|
83
|
+
day = time.strftime("%Y-%m-%d", time.gmtime(now))
|
|
84
|
+
return f"entitybind-cli {platform} {day}"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _unwrap(body: Any) -> Any:
|
|
88
|
+
"""AML wraps payloads as {"data": ..., "request_id": ...}."""
|
|
89
|
+
if isinstance(body, dict) and isinstance(body.get("data"), dict) and "request_id" in body:
|
|
90
|
+
return body["data"]
|
|
91
|
+
return body
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _announce(ctx: Context, product: Product, authorization: DeviceAuthorization) -> None:
|
|
95
|
+
if ctx.output.json_mode:
|
|
96
|
+
ctx.output.event({"event": "device_authorization", **authorization.public()})
|
|
97
|
+
return
|
|
98
|
+
minutes = max(1, round((authorization.expires_at - ctx.runtime.now()) / 60))
|
|
99
|
+
lines = [
|
|
100
|
+
f"To sign in to {product.label}, open:",
|
|
101
|
+
f" {authorization.verification_uri}",
|
|
102
|
+
f"and enter the code: {authorization.user_code}",
|
|
103
|
+
]
|
|
104
|
+
if authorization.verification_uri_complete:
|
|
105
|
+
lines.append(f"(direct link: {authorization.verification_uri_complete})")
|
|
106
|
+
lines.append(f"Waiting for approval (the code expires in about {minutes} min)...")
|
|
107
|
+
ctx.output.info("\n".join(lines))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _identity(client: ApiClient, product: Product) -> dict[str, Any]:
|
|
111
|
+
try:
|
|
112
|
+
response = client.get(product.api_path("/credential"))
|
|
113
|
+
except (ApiError, NetworkError):
|
|
114
|
+
return {}
|
|
115
|
+
body = _unwrap(response.body)
|
|
116
|
+
if isinstance(body, dict) and isinstance(body.get("credential"), dict):
|
|
117
|
+
body = body["credential"]
|
|
118
|
+
return body if isinstance(body, dict) else {}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _fill_from_identity(credential: Credential, identity: dict[str, Any]) -> None:
|
|
122
|
+
key_id = identity.get("key_id") or identity.get("id")
|
|
123
|
+
if credential.key_id is None and isinstance(key_id, str):
|
|
124
|
+
credential.key_id = key_id
|
|
125
|
+
tenant = identity.get("tenant_id") or identity.get("tenantId")
|
|
126
|
+
if credential.tenant_id is None and isinstance(tenant, str):
|
|
127
|
+
credential.tenant_id = tenant
|
|
128
|
+
scope = identity.get("scope")
|
|
129
|
+
scopes = identity.get("scopes")
|
|
130
|
+
if scope is None and isinstance(scopes, list) and all(isinstance(s, str) for s in scopes):
|
|
131
|
+
scope = " ".join(scopes)
|
|
132
|
+
if credential.scope is None and isinstance(scope, str):
|
|
133
|
+
credential.scope = scope
|
|
134
|
+
expires = identity.get("expires_at") or identity.get("expiresAt")
|
|
135
|
+
if credential.expires_at is None and isinstance(expires, str):
|
|
136
|
+
credential.expires_at = expires
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def cmd_login(ctx: Context) -> int:
|
|
140
|
+
args = ctx.args
|
|
141
|
+
product = ctx.product()
|
|
142
|
+
base_url = ctx.base_url(product)
|
|
143
|
+
pending = PendingStore(ctx.env)
|
|
144
|
+
now = ctx.runtime.now
|
|
145
|
+
timeout: float | None = 0.0 if args.no_wait else args.timeout
|
|
146
|
+
if timeout is not None and timeout < 0:
|
|
147
|
+
raise UsageError("--timeout must be zero or more seconds")
|
|
148
|
+
if args.no_store and not args.print_key:
|
|
149
|
+
raise UsageError(
|
|
150
|
+
"--no-store without --print-key would discard the new key",
|
|
151
|
+
hint="add --print-key to pipe the key into a secret manager",
|
|
152
|
+
)
|
|
153
|
+
scope = None if args.resume else requested_scope(product, args.scope)
|
|
154
|
+
previous: dict[str, Any] = {}
|
|
155
|
+
if not args.no_store:
|
|
156
|
+
# Fail before the person approves, not after: an unreadable store
|
|
157
|
+
# would otherwise lose the newly issued key.
|
|
158
|
+
ctx.store().read()
|
|
159
|
+
previous = ctx.store().metadata(product, base_url)
|
|
160
|
+
if scope is not None:
|
|
161
|
+
_refuse_scope_change(product, base_url, previous.get("scope"), scope)
|
|
162
|
+
with ctx.client(base_url) as client:
|
|
163
|
+
if args.resume:
|
|
164
|
+
authorization = pending.get(product, base_url)
|
|
165
|
+
if authorization is None:
|
|
166
|
+
raise UsageError(
|
|
167
|
+
f"no sign-in is waiting for approval for {product.label} at {base_url}",
|
|
168
|
+
code="no_pending_login",
|
|
169
|
+
hint="run `entitybind login` to start one",
|
|
170
|
+
)
|
|
171
|
+
if authorization.expires_at <= now():
|
|
172
|
+
pending.delete(product, base_url)
|
|
173
|
+
raise PendingError(
|
|
174
|
+
"the waiting sign-in expired before it was approved",
|
|
175
|
+
code="login_expired",
|
|
176
|
+
hint="run `entitybind login` to start again",
|
|
177
|
+
)
|
|
178
|
+
_announce(ctx, product, authorization)
|
|
179
|
+
else:
|
|
180
|
+
name = args.name or default_key_name(ctx.runtime.platform, now())
|
|
181
|
+
authorization = start_device_authorization(
|
|
182
|
+
client, product, base_url, scope=scope, name=name, now=now
|
|
183
|
+
)
|
|
184
|
+
pending.put(authorization)
|
|
185
|
+
_announce(ctx, product, authorization)
|
|
186
|
+
link = authorization.verification_uri_complete or authorization.verification_uri
|
|
187
|
+
if not args.no_browser and is_safe_browser_url(link):
|
|
188
|
+
ctx.runtime.open_browser(link)
|
|
189
|
+
deadline = (
|
|
190
|
+
authorization.expires_at
|
|
191
|
+
if timeout is None
|
|
192
|
+
else min(authorization.expires_at, now() + timeout)
|
|
193
|
+
)
|
|
194
|
+
try:
|
|
195
|
+
grant = poll_for_token(
|
|
196
|
+
client,
|
|
197
|
+
product,
|
|
198
|
+
authorization,
|
|
199
|
+
deadline=deadline,
|
|
200
|
+
sleep=ctx.runtime.sleep,
|
|
201
|
+
now=now,
|
|
202
|
+
poll_immediately=bool(args.resume),
|
|
203
|
+
)
|
|
204
|
+
except PendingError as error:
|
|
205
|
+
if error.code != "login_pending":
|
|
206
|
+
pending.delete(product, base_url)
|
|
207
|
+
raise
|
|
208
|
+
except AuthError:
|
|
209
|
+
pending.delete(product, base_url)
|
|
210
|
+
raise
|
|
211
|
+
pending.delete(product, base_url)
|
|
212
|
+
credential = credential_from_grant(product, base_url, grant, now=now())
|
|
213
|
+
with ctx.client(base_url, token=credential.api_key) as authed:
|
|
214
|
+
_fill_from_identity(credential, _identity(authed, product))
|
|
215
|
+
storage = "none"
|
|
216
|
+
if not args.no_store:
|
|
217
|
+
storage = ctx.store().save(credential).storage
|
|
218
|
+
result: dict[str, Any] = {
|
|
219
|
+
"status": "logged_in",
|
|
220
|
+
"product": product.name,
|
|
221
|
+
"base_url": base_url,
|
|
222
|
+
"storage": storage,
|
|
223
|
+
**{
|
|
224
|
+
key: value
|
|
225
|
+
for key, value in credential.public().items()
|
|
226
|
+
if key in ("scope", "key_id", "tenant_id", "expires_at", "token_type")
|
|
227
|
+
},
|
|
228
|
+
}
|
|
229
|
+
if storage == "file":
|
|
230
|
+
result["credentials_path"] = str(credentials_path(ctx.env))
|
|
231
|
+
if previous and storage != "none":
|
|
232
|
+
result["replaced_key_id"] = previous.get("key_id")
|
|
233
|
+
simulated_only = grant.metadata.get("simulated_checks_only")
|
|
234
|
+
if isinstance(simulated_only, bool):
|
|
235
|
+
result["simulated_checks_only"] = simulated_only
|
|
236
|
+
if args.print_key:
|
|
237
|
+
result["api_key"] = credential.api_key
|
|
238
|
+
if ctx.output.json_mode:
|
|
239
|
+
ctx.output.data(result)
|
|
240
|
+
return EXIT_OK
|
|
241
|
+
where = {
|
|
242
|
+
"keyring": "in the OS keyring",
|
|
243
|
+
"file": f"in {credentials_path(ctx.env)} (mode 600)",
|
|
244
|
+
"none": "nowhere (--no-store)",
|
|
245
|
+
}[storage]
|
|
246
|
+
scope_text = f" with scope {credential.scope}" if credential.scope else ""
|
|
247
|
+
ctx.output.info(f"Logged in to {product.label} at {base_url}{scope_text}. Key stored {where}.")
|
|
248
|
+
if simulated_only is True:
|
|
249
|
+
ctx.output.info("This sandbox uses synthetic providers only; no live checks are available.")
|
|
250
|
+
if "replaced_key_id" in result:
|
|
251
|
+
ctx.output.info(_replaced_note(product, result["replaced_key_id"]))
|
|
252
|
+
if args.print_key:
|
|
253
|
+
ctx.output.line(credential.api_key)
|
|
254
|
+
return EXIT_OK
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _revocation_hint(product: Product, key_id: str | None) -> str:
|
|
258
|
+
key = f"key {key_id}" if key_id else "the key"
|
|
259
|
+
if product is CORE:
|
|
260
|
+
how = (
|
|
261
|
+
f"`entitybind keys revoke {key_id}` with an admin key, or the portal's key list"
|
|
262
|
+
if key_id
|
|
263
|
+
else "the portal's key list"
|
|
264
|
+
)
|
|
265
|
+
return (
|
|
266
|
+
f"the stored credential was kept; revoke {key} with {how}, then run `entitybind logout`"
|
|
267
|
+
)
|
|
268
|
+
return (
|
|
269
|
+
f"the stored credential was kept; retry, or ask a workspace administrator to revoke {key} "
|
|
270
|
+
"in AML Onboard, then run `entitybind logout --product aml`"
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _revoke_stored(ctx: Context, product: Product, base_url: str) -> bool:
|
|
275
|
+
"""Revoke the stored key and confirm it, or raise and keep the local record.
|
|
276
|
+
|
|
277
|
+
Returns False when nothing is stored. The local record is the only handle
|
|
278
|
+
on a key that is still live, so it is never removed unconfirmed.
|
|
279
|
+
"""
|
|
280
|
+
store = ctx.store()
|
|
281
|
+
key_id = store.metadata(product, base_url).get("key_id")
|
|
282
|
+
kept = {"key_id": key_id, "local_credential_kept": True}
|
|
283
|
+
try:
|
|
284
|
+
stored = store.get(product, base_url)
|
|
285
|
+
except CliError as error:
|
|
286
|
+
raise CliError(
|
|
287
|
+
f"the stored key for {product.label} at {base_url} could not be read, so it was "
|
|
288
|
+
f"not revoked: {error.message}",
|
|
289
|
+
code="revocation_unconfirmed",
|
|
290
|
+
exit_code=error.exit_code,
|
|
291
|
+
hint="; ".join(
|
|
292
|
+
part for part in (error.hint, _revocation_hint(product, key_id)) if part
|
|
293
|
+
),
|
|
294
|
+
data=kept,
|
|
295
|
+
) from None
|
|
296
|
+
if stored is None:
|
|
297
|
+
return False
|
|
298
|
+
key_id = stored.key_id or key_id
|
|
299
|
+
with ctx.client(base_url, token=stored.api_key) as client:
|
|
300
|
+
outcome = revoke_key(client, product, stored.api_key)
|
|
301
|
+
if stored.refresh_token:
|
|
302
|
+
revoke_token(client, product, stored.refresh_token)
|
|
303
|
+
if not outcome.confirmed:
|
|
304
|
+
raise CliError(
|
|
305
|
+
f"the key for {product.label} at {base_url} was not revoked: {outcome.detail}",
|
|
306
|
+
code="revocation_unconfirmed",
|
|
307
|
+
exit_code=outcome.cause.exit_code if outcome.cause is not None else EXIT_AUTH,
|
|
308
|
+
hint=_revocation_hint(product, key_id),
|
|
309
|
+
data={**kept, "key_id": key_id},
|
|
310
|
+
)
|
|
311
|
+
return True
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def cmd_logout(ctx: Context) -> int:
|
|
315
|
+
args = ctx.args
|
|
316
|
+
store = ctx.store()
|
|
317
|
+
if args.all:
|
|
318
|
+
if args.revoke:
|
|
319
|
+
raise UsageError(
|
|
320
|
+
"--all cannot be combined with --revoke",
|
|
321
|
+
hint="revoke each credential with `entitybind logout --revoke` (add --product aml "
|
|
322
|
+
"for AML Onboard), then run `entitybind logout --all`",
|
|
323
|
+
)
|
|
324
|
+
removed = store.delete_all()
|
|
325
|
+
PendingStore(ctx.env).path.unlink(missing_ok=True)
|
|
326
|
+
if ctx.output.json_mode:
|
|
327
|
+
ctx.output.data({"status": "logged_out", "removed": removed})
|
|
328
|
+
else:
|
|
329
|
+
ctx.output.info(f"Removed {removed} stored credential(s).")
|
|
330
|
+
return EXIT_OK
|
|
331
|
+
product = ctx.product()
|
|
332
|
+
base_url = ctx.base_url(product)
|
|
333
|
+
revoked = bool(args.revoke) and _revoke_stored(ctx, product, base_url)
|
|
334
|
+
removed = store.delete(product, base_url)
|
|
335
|
+
PendingStore(ctx.env).delete(product, base_url)
|
|
336
|
+
still_set = bool(ctx.env.get(product.key_env, "").strip())
|
|
337
|
+
if ctx.output.json_mode:
|
|
338
|
+
ctx.output.data(
|
|
339
|
+
{
|
|
340
|
+
"status": "logged_out",
|
|
341
|
+
"product": product.name,
|
|
342
|
+
"base_url": base_url,
|
|
343
|
+
"removed": removed,
|
|
344
|
+
"revoked": True if revoked else None,
|
|
345
|
+
"environment_key_set": still_set,
|
|
346
|
+
}
|
|
347
|
+
)
|
|
348
|
+
return EXIT_OK
|
|
349
|
+
if revoked:
|
|
350
|
+
ctx.output.info("Revoked the key on the server: it no longer authenticates.")
|
|
351
|
+
if removed:
|
|
352
|
+
ctx.output.info(f"Removed the stored credential for {product.label} at {base_url}.")
|
|
353
|
+
else:
|
|
354
|
+
ctx.output.info(f"No stored credential for {product.label} at {base_url}.")
|
|
355
|
+
if still_set:
|
|
356
|
+
ctx.output.info(f"{product.key_env} is still set and will keep authenticating.")
|
|
357
|
+
return EXIT_OK
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def cmd_whoami(ctx: Context) -> int:
|
|
361
|
+
product = ctx.product()
|
|
362
|
+
client, resolved, base_url = ctx.authenticated(product)
|
|
363
|
+
with client:
|
|
364
|
+
try:
|
|
365
|
+
response = client.get(product.api_path("/credential"))
|
|
366
|
+
except ApiError as error:
|
|
367
|
+
if error.status == 404:
|
|
368
|
+
raise NotFoundError(
|
|
369
|
+
f"{base_url} does not report credential details "
|
|
370
|
+
f"(GET {product.api_path('/credential')})",
|
|
371
|
+
code="credential_endpoint_unavailable",
|
|
372
|
+
) from None
|
|
373
|
+
raise
|
|
374
|
+
local = {
|
|
375
|
+
"product": product.name,
|
|
376
|
+
"base_url": base_url,
|
|
377
|
+
"source": resolved.source,
|
|
378
|
+
}
|
|
379
|
+
if resolved.env_var:
|
|
380
|
+
local["env_var"] = resolved.env_var
|
|
381
|
+
if ctx.output.json_mode:
|
|
382
|
+
ctx.output.data({**local, "credential": response.body})
|
|
383
|
+
return EXIT_OK
|
|
384
|
+
ctx.output.line(f"product: {product.name} ({product.label})")
|
|
385
|
+
ctx.output.line(f"base_url: {base_url}")
|
|
386
|
+
source = resolved.source + (f" ({resolved.env_var})" if resolved.env_var else "")
|
|
387
|
+
ctx.output.line(f"source: {source}")
|
|
388
|
+
body = _unwrap(response.body)
|
|
389
|
+
if isinstance(body, dict) and isinstance(body.get("credential"), dict):
|
|
390
|
+
body = body["credential"]
|
|
391
|
+
if isinstance(body, dict):
|
|
392
|
+
ctx.output.fields({k: v for k, v in body.items() if k != "correlation_id"})
|
|
393
|
+
return EXIT_OK
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""`entitybind mcp add <client>`: print or merge an MCP client configuration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from entitybind.context import Context
|
|
11
|
+
from entitybind.credentials import resolve_credential
|
|
12
|
+
from entitybind.errors import (
|
|
13
|
+
EXIT_OK,
|
|
14
|
+
EXIT_SERVER,
|
|
15
|
+
AuthError,
|
|
16
|
+
CliError,
|
|
17
|
+
ConflictError,
|
|
18
|
+
NotFoundError,
|
|
19
|
+
UsageError,
|
|
20
|
+
)
|
|
21
|
+
from entitybind.files import POSIX, atomic_write, existing_mode
|
|
22
|
+
from entitybind.mcpconfig import (
|
|
23
|
+
CLIENT_LABELS,
|
|
24
|
+
DEFAULT_SCOPES,
|
|
25
|
+
McpTarget,
|
|
26
|
+
MergeResult,
|
|
27
|
+
build_target,
|
|
28
|
+
merge_json,
|
|
29
|
+
merge_toml,
|
|
30
|
+
refuse_inline_key_in_project,
|
|
31
|
+
shell_command,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
_REDACTED = "<redacted key>"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _redact(value: Any, secret: str | None) -> Any:
|
|
38
|
+
if secret is None:
|
|
39
|
+
return value
|
|
40
|
+
if isinstance(value, str):
|
|
41
|
+
return value.replace(secret, _REDACTED)
|
|
42
|
+
if isinstance(value, list):
|
|
43
|
+
return [_redact(item, secret) for item in value]
|
|
44
|
+
if isinstance(value, dict):
|
|
45
|
+
return {key: _redact(item, secret) for key, item in value.items()}
|
|
46
|
+
return value
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _write_merge(result: MergeResult, *, secret: bool, warn: Callable[[str], None]) -> None:
|
|
50
|
+
if not result.changed:
|
|
51
|
+
return
|
|
52
|
+
mode = existing_mode(result.path)
|
|
53
|
+
if mode is None:
|
|
54
|
+
mode = 0o600 if secret else 0o644
|
|
55
|
+
elif secret and POSIX and mode & 0o077:
|
|
56
|
+
warn(f"tightening {result.path} to mode 600 because it now contains a key")
|
|
57
|
+
mode = 0o600
|
|
58
|
+
atomic_write(result.path, result.content, mode=mode)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _require_inside_project(path: Path, directory: Path) -> None:
|
|
62
|
+
"""A project file must not lead outside the project through a symlink.
|
|
63
|
+
|
|
64
|
+
A cloned repository could ship `.mcp.json` (or `.vscode/`) as a link to a
|
|
65
|
+
file elsewhere; writing through it would edit that file instead.
|
|
66
|
+
"""
|
|
67
|
+
resolved = path.resolve()
|
|
68
|
+
try:
|
|
69
|
+
resolved.relative_to(directory.resolve())
|
|
70
|
+
except ValueError:
|
|
71
|
+
raise ConflictError(
|
|
72
|
+
f"{path} resolves to {resolved}, outside the project directory; refusing to write "
|
|
73
|
+
"through the link",
|
|
74
|
+
code="config_outside_project",
|
|
75
|
+
hint="remove the link, or add the entry to that file by hand",
|
|
76
|
+
) from None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _run_claude(ctx: Context, target: McpTarget, secret: str | None) -> bool:
|
|
80
|
+
argv = target.write_command or []
|
|
81
|
+
if ctx.runtime.which("claude") is None:
|
|
82
|
+
raise NotFoundError(
|
|
83
|
+
"the claude CLI is not on PATH, so the user-scope entry cannot be added for you",
|
|
84
|
+
code="client_cli_missing",
|
|
85
|
+
hint=f"run it yourself: {_redact(shell_command(argv), secret)}",
|
|
86
|
+
)
|
|
87
|
+
if ctx.args.force:
|
|
88
|
+
ctx.runtime.run_command(["claude", "mcp", "remove", "--scope", "user", target.server_name])
|
|
89
|
+
result = ctx.runtime.run_command(argv)
|
|
90
|
+
if result.returncode == 0:
|
|
91
|
+
return True
|
|
92
|
+
# Redact before truncating, so a key cut in half cannot slip through.
|
|
93
|
+
text = _redact(" ".join((result.stderr or result.stdout).split()), secret)[:300]
|
|
94
|
+
if "already exists" in text.lower():
|
|
95
|
+
raise ConflictError(
|
|
96
|
+
f"Claude Code already has a user-scope MCP server named {target.server_name!r}",
|
|
97
|
+
code="config_conflict",
|
|
98
|
+
hint="use --force to replace it, or --server-name to add another entry",
|
|
99
|
+
)
|
|
100
|
+
raise CliError(
|
|
101
|
+
f"`claude mcp add-json` failed: {text or f'exit {result.returncode}'}",
|
|
102
|
+
code="client_cli_failed",
|
|
103
|
+
exit_code=EXIT_SERVER,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def cmd_mcp_add(ctx: Context) -> int:
|
|
108
|
+
args = ctx.args
|
|
109
|
+
product = ctx.product()
|
|
110
|
+
base_url = ctx.base_url(product)
|
|
111
|
+
inline_key: str | None = None
|
|
112
|
+
if args.inline_key and args.auth != "key":
|
|
113
|
+
raise UsageError("--inline-key applies only to --auth key")
|
|
114
|
+
if args.inline_key:
|
|
115
|
+
refuse_inline_key_in_project(args.scope or DEFAULT_SCOPES[args.client])
|
|
116
|
+
resolved = resolve_credential(product, base_url, ctx.env, ctx.store())
|
|
117
|
+
if resolved is None:
|
|
118
|
+
raise AuthError(
|
|
119
|
+
"--inline-key needs a key to write",
|
|
120
|
+
hint=f"run `entitybind login` or set {product.key_env}",
|
|
121
|
+
)
|
|
122
|
+
inline_key = resolved.token
|
|
123
|
+
ctx.output.info(
|
|
124
|
+
"warning: --inline-key writes the raw key into the configuration file. "
|
|
125
|
+
f"Anyone who can read the file can use the key; prefer {product.key_env}."
|
|
126
|
+
)
|
|
127
|
+
directory = Path(args.dir).expanduser() if args.dir else ctx.runtime.cwd
|
|
128
|
+
target = build_target(
|
|
129
|
+
args.client,
|
|
130
|
+
product,
|
|
131
|
+
base_url=base_url,
|
|
132
|
+
auth=args.auth,
|
|
133
|
+
scope=args.scope,
|
|
134
|
+
server_name=args.server_name,
|
|
135
|
+
directory=directory,
|
|
136
|
+
env=ctx.env,
|
|
137
|
+
platform=ctx.runtime.platform,
|
|
138
|
+
inline_key=inline_key,
|
|
139
|
+
)
|
|
140
|
+
merge: MergeResult | None = None
|
|
141
|
+
written = False
|
|
142
|
+
if args.write and target.scope == "project" and target.path is not None:
|
|
143
|
+
_require_inside_project(target.path, directory)
|
|
144
|
+
if args.write:
|
|
145
|
+
if target.format == "command":
|
|
146
|
+
written = _run_claude(ctx, target, inline_key)
|
|
147
|
+
elif target.format == "toml" and target.path is not None and target.toml is not None:
|
|
148
|
+
merge = merge_toml(
|
|
149
|
+
target.path,
|
|
150
|
+
target.server_name,
|
|
151
|
+
target.toml,
|
|
152
|
+
target.toml_expected or {},
|
|
153
|
+
force=args.force,
|
|
154
|
+
)
|
|
155
|
+
elif target.path is not None and target.entry is not None and target.container:
|
|
156
|
+
merge = merge_json(
|
|
157
|
+
target.path,
|
|
158
|
+
target.container,
|
|
159
|
+
target.server_name,
|
|
160
|
+
target.entry,
|
|
161
|
+
managed=target.managed,
|
|
162
|
+
allow_env=target.allow_env,
|
|
163
|
+
force=args.force,
|
|
164
|
+
)
|
|
165
|
+
if merge is not None:
|
|
166
|
+
_write_merge(merge, secret=target.inline_secret, warn=ctx.output.info)
|
|
167
|
+
written = merge.changed
|
|
168
|
+
_report(ctx, target, merge, written, inline_key)
|
|
169
|
+
return EXIT_OK
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _report(
|
|
173
|
+
ctx: Context,
|
|
174
|
+
target: McpTarget,
|
|
175
|
+
merge: MergeResult | None,
|
|
176
|
+
written: bool,
|
|
177
|
+
secret: str | None,
|
|
178
|
+
) -> None:
|
|
179
|
+
label = CLIENT_LABELS[target.client]
|
|
180
|
+
command = shell_command(target.command) if target.command else None
|
|
181
|
+
if ctx.output.json_mode:
|
|
182
|
+
payload: dict[str, Any] = {
|
|
183
|
+
"client": target.client,
|
|
184
|
+
"product": target.product,
|
|
185
|
+
"auth": target.auth,
|
|
186
|
+
"scope": target.scope,
|
|
187
|
+
"server_name": target.server_name,
|
|
188
|
+
"url": target.url,
|
|
189
|
+
"format": target.format,
|
|
190
|
+
"path": str(target.path) if target.path else None,
|
|
191
|
+
"entry": target.entry,
|
|
192
|
+
"configuration": target.document(),
|
|
193
|
+
"toml": target.toml,
|
|
194
|
+
"command": command,
|
|
195
|
+
"env_var": target.env_var,
|
|
196
|
+
"written": written,
|
|
197
|
+
"changed": merge.changed if merge else written,
|
|
198
|
+
"created": merge.created if merge else False,
|
|
199
|
+
"notes": target.notes,
|
|
200
|
+
}
|
|
201
|
+
ctx.output.data(_redact(payload, secret))
|
|
202
|
+
return
|
|
203
|
+
if ctx.args.write:
|
|
204
|
+
if target.format == "command":
|
|
205
|
+
ctx.output.line(
|
|
206
|
+
f"Added {target.server_name!r} to Claude Code (user scope) -> {target.url}"
|
|
207
|
+
)
|
|
208
|
+
elif merge is not None and merge.changed:
|
|
209
|
+
verb = "Created" if merge.created else "Updated"
|
|
210
|
+
ctx.output.line(f"{verb} {target.path}: {target.server_name} -> {target.url}")
|
|
211
|
+
else:
|
|
212
|
+
ctx.output.line(f"{target.path} already has this entry; nothing changed.")
|
|
213
|
+
else:
|
|
214
|
+
where = f" in {target.path}" if target.path else ""
|
|
215
|
+
ctx.output.line(f"{label} ({target.scope} scope){where}:")
|
|
216
|
+
if target.toml is not None:
|
|
217
|
+
ctx.output.line(_redact(target.toml, secret).rstrip("\n"))
|
|
218
|
+
else:
|
|
219
|
+
document = target.document()
|
|
220
|
+
if document is not None:
|
|
221
|
+
ctx.output.line(json.dumps(_redact(document, secret), indent=2))
|
|
222
|
+
if command and target.format == "command":
|
|
223
|
+
ctx.output.line("")
|
|
224
|
+
ctx.output.line("Run:")
|
|
225
|
+
ctx.output.line(f" {_redact(command, secret)}")
|
|
226
|
+
elif command:
|
|
227
|
+
ctx.output.line("")
|
|
228
|
+
ctx.output.line("Or run:")
|
|
229
|
+
ctx.output.line(f" {_redact(command, secret)}")
|
|
230
|
+
ctx.output.line("")
|
|
231
|
+
if target.format == "command":
|
|
232
|
+
ctx.output.line("Run again with --write to run this command for you.")
|
|
233
|
+
else:
|
|
234
|
+
ctx.output.line("Run again with --write to merge it into the file for you.")
|
|
235
|
+
for note in target.notes:
|
|
236
|
+
ctx.output.info(f"note: {note}")
|