knuckles-mcp 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.
@@ -0,0 +1,3 @@
1
+ """MCP server exposing Knuckles tenant setup to coding agents."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,7 @@
1
+ """Allow ``python -m knuckles_mcp``."""
2
+
3
+ import sys
4
+
5
+ from knuckles_mcp.server import main
6
+
7
+ sys.exit(main())
knuckles_mcp/py.typed ADDED
File without changes
knuckles_mcp/server.py ADDED
@@ -0,0 +1,539 @@
1
+ """The ``knuckles-mcp`` stdio server (Decision #027).
2
+
3
+ Every tool wraps a :mod:`knuckles_cli.ops` function. The server finds
4
+ its Knuckles deployment the same way the CLI does: ``KNUCKLES_URL`` and
5
+ ``KNUCKLES_ADMIN_TOKEN`` in its environment, else the profile stored by
6
+ ``knuckles login`` (``KNUCKLES_PROFILE``, default ``default``).
7
+
8
+ Secrets never pass through tool arguments or results. Tenant secrets
9
+ go straight into an ``.env`` file; provider secrets are read from files
10
+ on this machine or from the server's own environment; rows come back
11
+ redacted.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import os
18
+ import sys
19
+ from contextlib import contextmanager
20
+ from importlib import resources
21
+ from pathlib import Path
22
+ from typing import TYPE_CHECKING, Any, Literal
23
+
24
+ from knuckles_cli import ops
25
+ from knuckles_cli.api import KnucklesAPI
26
+ from knuckles_cli.config import config_path, resolve_profile
27
+ from knuckles_cli.errors import INVALID_INPUT, CliError
28
+ from knuckles_cli.providers import parse_google_client_secret
29
+ from mcp.server.mcpserver import MCPServer
30
+ from mcp.server.mcpserver.exceptions import ToolError
31
+ from mcp.types import ToolAnnotations
32
+
33
+ from knuckles_mcp import __version__
34
+
35
+ if TYPE_CHECKING:
36
+ from collections.abc import Iterator, Mapping
37
+
38
+ INSTRUCTIONS = """\
39
+ Tools for setting up sign-in with a Knuckles identity server: create a
40
+ tenant (app client) for an app, configure its sign-in methods, and
41
+ check the result with knuckles_doctor.
42
+
43
+ Secrets never go in tool arguments. Tenant credentials are written to
44
+ the .env file you name. Provider secrets are read from files on this
45
+ machine: Google's client_secret_*.json, Apple's AuthKey_<KEYID>.p8, or
46
+ a file holding the Resend API key. Ask the user for those file paths;
47
+ never ask them to paste a secret into the chat. Prefer absolute paths.
48
+
49
+ Run knuckles_doctor after any change. Changing a passkey rp_id that
50
+ users already registered passkeys under signs all of them out, so
51
+ never pass force_rp_id unless the user explicitly asks.
52
+ """
53
+
54
+ READ_ONLY = ToolAnnotations(read_only_hint=True, open_world_hint=True)
55
+ WRITES = ToolAnnotations(
56
+ read_only_hint=False, destructive_hint=False, open_world_hint=True
57
+ )
58
+ DESTRUCTIVE = ToolAnnotations(
59
+ read_only_hint=False, destructive_hint=True, open_world_hint=True
60
+ )
61
+
62
+ ProviderGroup = Literal["email", "google", "apple", "passkey"]
63
+
64
+
65
+ @contextmanager
66
+ def _tool_errors() -> Iterator[None]:
67
+ """Turn CLI and file errors into MCP tool errors.
68
+
69
+ Yields:
70
+ Nothing; wraps the body of a tool.
71
+
72
+ Raises:
73
+ ToolError: ``CODE: message`` for a :class:`CliError`, or
74
+ ``INVALID_INPUT`` for an unreadable file.
75
+ """
76
+ try:
77
+ yield
78
+ except CliError as exc:
79
+ raise ToolError(f"{exc.code}: {exc.message}") from exc
80
+ except OSError as exc:
81
+ raise ToolError(f"{INVALID_INPUT}: {exc}") from exc
82
+
83
+
84
+ def _path(value: str) -> Path:
85
+ """Resolve a path argument against the server's working directory.
86
+
87
+ Args:
88
+ value: Path as the agent gave it; ``~`` is expanded.
89
+
90
+ Returns:
91
+ An absolute path.
92
+ """
93
+ path = Path(value).expanduser()
94
+ return path if path.is_absolute() else Path.cwd() / path
95
+
96
+
97
+ def _read_secret(
98
+ file: str | None, *, env_var: str, label: str, env: Mapping[str, str]
99
+ ) -> str:
100
+ """Read a secret from a file, else from the server's environment.
101
+
102
+ Args:
103
+ file: Path to a file holding the secret, or ``None``.
104
+ env_var: Server environment variable to fall back to.
105
+ label: Human name of the secret for errors.
106
+ env: The server's environment.
107
+
108
+ Returns:
109
+ The secret, whitespace-trimmed.
110
+
111
+ Raises:
112
+ CliError: ``INVALID_INPUT`` if neither source has a value.
113
+ """
114
+ if file:
115
+ value = _path(file).read_text()
116
+ elif env.get(env_var):
117
+ value = env[env_var]
118
+ else:
119
+ raise CliError(
120
+ INVALID_INPUT,
121
+ f"No {label}. Ask the user for the path of a file holding it, or "
122
+ f"set {env_var} in this MCP server's environment.",
123
+ )
124
+ value = value.strip()
125
+ if not value:
126
+ raise CliError(INVALID_INPUT, f"The {label} is empty.")
127
+ return value
128
+
129
+
130
+ def _next_steps(client_id: str, origin: str | None) -> list[str]:
131
+ """Describe the tool calls that finish setting up a new tenant.
132
+
133
+ Args:
134
+ client_id: The new tenant id.
135
+ origin: Its primary origin, if any.
136
+
137
+ Returns:
138
+ One line per remaining step.
139
+ """
140
+ return [
141
+ f"knuckles_configure_email(client_id={client_id!r}, from_email=..., "
142
+ "api_key_file=...) for magic links",
143
+ f"knuckles_configure_google(client_id={client_id!r}, "
144
+ "client_secret_json=...) for Google",
145
+ f"knuckles_configure_apple(client_id={client_id!r}, services_id=..., "
146
+ "team_id=..., p8_file=...) for Apple",
147
+ f"knuckles_configure_passkey(client_id={client_id!r}, "
148
+ f"origin={origin or '...'!r}) for passkeys",
149
+ f"knuckles_doctor(client_id={client_id!r})",
150
+ "Install the SDK in the app: pip install knuckles-client "
151
+ "(or npm install @knuckles/client)",
152
+ ]
153
+
154
+
155
+ def build_server(env: Mapping[str, str] | None = None) -> MCPServer[Any]:
156
+ """Create the MCP server with every Knuckles tool registered.
157
+
158
+ Args:
159
+ env: Environment to read configuration and fallback secrets
160
+ from; defaults to the process environment, read per call.
161
+
162
+ Returns:
163
+ A server ready to ``run()``.
164
+ """
165
+ environ: Mapping[str, str] = os.environ if env is None else env
166
+ server: MCPServer[Any] = MCPServer(
167
+ name="knuckles",
168
+ title="Knuckles",
169
+ instructions=INSTRUCTIONS,
170
+ version=__version__,
171
+ )
172
+
173
+ def api() -> KnucklesAPI:
174
+ """Build an admin API client from the effective profile.
175
+
176
+ Returns:
177
+ A client for the configured server.
178
+ """
179
+ profile = resolve_profile(
180
+ path=config_path(environ),
181
+ name=environ.get("KNUCKLES_PROFILE") or "default",
182
+ env=environ,
183
+ )
184
+ return KnucklesAPI(profile.url, admin_token=profile.admin_token)
185
+
186
+ @server.tool(annotations=READ_ONLY)
187
+ def knuckles_doctor(client_id: str | None = None) -> dict[str, Any]:
188
+ """Check the Knuckles server and its tenants' sign-in configuration.
189
+
190
+ Args:
191
+ client_id: Check only this tenant; omit to check every tenant.
192
+
193
+ Returns:
194
+ Each check (name, status ok/warn/fail, detail) and a tally.
195
+ """
196
+ with _tool_errors():
197
+ return ops.doctor(api(), client_id).to_dict()
198
+
199
+ @server.tool(annotations=READ_ONLY)
200
+ def knuckles_list_apps() -> dict[str, Any]:
201
+ """List every tenant (app client) on the Knuckles server.
202
+
203
+ Returns:
204
+ ``{"apps": [...]}`` with redacted rows.
205
+ """
206
+ with _tool_errors():
207
+ return {"apps": api().list_apps()}
208
+
209
+ @server.tool(annotations=READ_ONLY)
210
+ def knuckles_show_app(client_id: str) -> dict[str, Any]:
211
+ """Show one tenant's configuration (secrets appear as booleans).
212
+
213
+ Args:
214
+ client_id: The tenant id.
215
+
216
+ Returns:
217
+ The redacted row.
218
+ """
219
+ with _tool_errors():
220
+ return api().get_app(client_id)
221
+
222
+ @server.tool(annotations=WRITES)
223
+ def knuckles_create_app(
224
+ client_id: str,
225
+ name: str,
226
+ origins: list[str],
227
+ env_file: str,
228
+ overwrite: bool = False,
229
+ ) -> dict[str, Any]:
230
+ """Create a tenant and write its credentials into the app's .env file.
231
+
232
+ Writes KNUCKLES_URL, KNUCKLES_CLIENT_ID and KNUCKLES_CLIENT_SECRET.
233
+ The client secret is shown only once and goes only to that file.
234
+
235
+ Args:
236
+ client_id: New tenant id, e.g. ``my-site``.
237
+ name: Human-readable app name.
238
+ origins: Browser origins the app runs on, including local dev,
239
+ e.g. ``["https://my-site.com", "http://localhost:3000"]``.
240
+ env_file: Path of the consuming app's .env file.
241
+ overwrite: Replace differing KNUCKLES_* values already there.
242
+
243
+ Returns:
244
+ The created row, the .env path, and the remaining setup steps.
245
+ """
246
+ with _tool_errors():
247
+ created = ops.create_app(
248
+ api(),
249
+ client_id=client_id,
250
+ name=name,
251
+ origins=origins,
252
+ env_file=_path(env_file),
253
+ force=overwrite,
254
+ )
255
+ created.pop("client_secret", None)
256
+ primary = created["allowed_origins"][0] if created["allowed_origins"] else None
257
+ created["next_steps"] = _next_steps(client_id, primary)
258
+ return created
259
+
260
+ @server.tool(annotations=WRITES)
261
+ def knuckles_set_origins(client_id: str, origins: list[str]) -> dict[str, Any]:
262
+ """Replace a tenant's allowed browser origins.
263
+
264
+ Args:
265
+ client_id: The tenant id.
266
+ origins: The complete new list of origins.
267
+
268
+ Returns:
269
+ The updated row.
270
+ """
271
+ with _tool_errors():
272
+ return ops.set_origins(api(), client_id, origins)
273
+
274
+ @server.tool(annotations=DESTRUCTIVE)
275
+ def knuckles_rotate_secret(
276
+ client_id: str, env_file: str, overwrite: bool = False
277
+ ) -> dict[str, Any]:
278
+ """Mint a new client secret and write it into the app's .env file.
279
+
280
+ The old secret stops working immediately, so every deployment of
281
+ the app needs the new value.
282
+
283
+ Args:
284
+ client_id: The tenant id.
285
+ env_file: Path of the consuming app's .env file.
286
+ overwrite: Required to replace a KNUCKLES_CLIENT_SECRET already
287
+ in the file.
288
+
289
+ Returns:
290
+ The tenant id and the .env path.
291
+ """
292
+ with _tool_errors():
293
+ data = ops.rotate_secret(
294
+ api(), client_id, env_file=_path(env_file), force=overwrite
295
+ )
296
+ data.pop("client_secret", None)
297
+ return data
298
+
299
+ @server.tool(annotations=WRITES)
300
+ def knuckles_configure_email(
301
+ client_id: str,
302
+ from_email: str,
303
+ api_key_file: str | None = None,
304
+ verify_domain: bool = True,
305
+ ) -> dict[str, Any]:
306
+ """Turn on magic-link email for a tenant, sent through Resend.
307
+
308
+ The sending domain must already show Verified in Resend.
309
+
310
+ Args:
311
+ client_id: The tenant id.
312
+ from_email: From address, e.g. ``My App <signin@mail.my-app.com>``.
313
+ api_key_file: Path of a file holding the Resend API key. If
314
+ omitted, the server's KNUCKLES_RESEND_API_KEY is used.
315
+ verify_domain: Check with Resend that the domain is verified.
316
+
317
+ Returns:
318
+ The updated row and any warnings.
319
+ """
320
+ with _tool_errors():
321
+ key = _read_secret(
322
+ api_key_file,
323
+ env_var="KNUCKLES_RESEND_API_KEY",
324
+ label="Resend API key",
325
+ env=environ,
326
+ )
327
+ return ops.configure_email(
328
+ api(),
329
+ client_id,
330
+ from_email=from_email,
331
+ api_key=key,
332
+ verify=verify_domain,
333
+ ).to_dict()
334
+
335
+ @server.tool(annotations=WRITES)
336
+ def knuckles_configure_google(
337
+ client_id: str,
338
+ client_secret_json: str | None = None,
339
+ google_client_id: str | None = None,
340
+ client_secret_file: str | None = None,
341
+ ) -> dict[str, Any]:
342
+ """Turn on Sign in with Google for a tenant.
343
+
344
+ Preferred: the client_secret_*.json that Google Cloud Console
345
+ downloads for a "Web application" OAuth client. Otherwise give the
346
+ Google client id plus a file holding its secret.
347
+
348
+ Args:
349
+ client_id: The tenant id.
350
+ client_secret_json: Path of Google's downloaded JSON file.
351
+ google_client_id: Google OAuth client id, for manual entry.
352
+ client_secret_file: With google_client_id, path of a file
353
+ holding the client secret. If omitted, the server's
354
+ KNUCKLES_GOOGLE_CLIENT_SECRET is used.
355
+
356
+ Returns:
357
+ The updated row and a warning per redirect URI whose origin
358
+ the tenant does not allow.
359
+ """
360
+ with _tool_errors():
361
+ redirect_origins: list[str] = []
362
+ if client_secret_json:
363
+ creds = parse_google_client_secret(
364
+ _path(client_secret_json).read_text()
365
+ )
366
+ google_id, secret = creds.client_id, creds.client_secret
367
+ redirect_origins = creds.redirect_origins
368
+ elif google_client_id:
369
+ google_id = google_client_id
370
+ secret = _read_secret(
371
+ client_secret_file,
372
+ env_var="KNUCKLES_GOOGLE_CLIENT_SECRET",
373
+ label="Google client secret",
374
+ env=environ,
375
+ )
376
+ else:
377
+ raise CliError(
378
+ INVALID_INPUT,
379
+ "Give client_secret_json (preferred) or google_client_id.",
380
+ )
381
+ return ops.configure_google(
382
+ api(),
383
+ client_id,
384
+ client_id=google_id,
385
+ client_secret=secret,
386
+ redirect_origins=redirect_origins,
387
+ ).to_dict()
388
+
389
+ @server.tool(annotations=WRITES)
390
+ def knuckles_configure_apple(
391
+ client_id: str,
392
+ services_id: str,
393
+ team_id: str,
394
+ p8_file: str,
395
+ key_id: str | None = None,
396
+ ) -> dict[str, Any]:
397
+ """Turn on Sign in with Apple for a tenant.
398
+
399
+ Args:
400
+ client_id: The tenant id.
401
+ services_id: The Apple Services ID for the website.
402
+ team_id: The 10-character Apple Developer team id.
403
+ p8_file: Path of the downloaded ``AuthKey_<KEYID>.p8`` key file.
404
+ key_id: The key id, only if the file was renamed.
405
+
406
+ Returns:
407
+ The updated row.
408
+ """
409
+ with _tool_errors():
410
+ return ops.configure_apple(
411
+ api(),
412
+ client_id,
413
+ services_id=services_id,
414
+ team_id=team_id,
415
+ p8_path=_path(p8_file),
416
+ key_id=key_id,
417
+ ).to_dict()
418
+
419
+ @server.tool(annotations=WRITES)
420
+ def knuckles_configure_passkey(
421
+ client_id: str,
422
+ origin: str,
423
+ rp_id: str | None = None,
424
+ rp_name: str | None = None,
425
+ force_rp_id: bool = False,
426
+ ) -> dict[str, Any]:
427
+ """Turn on passkeys for a tenant by setting its WebAuthn relying party.
428
+
429
+ Args:
430
+ client_id: The tenant id.
431
+ origin: The production origin passkeys are used on.
432
+ rp_id: Relying-party id; defaults to the origin's host. A parent
433
+ domain works too, to share passkeys across subdomains.
434
+ rp_name: Name shown in the passkey prompt; defaults to the
435
+ tenant's app name.
436
+ force_rp_id: Allow changing an rp_id existing passkeys use,
437
+ which invalidates every one of them. Only on explicit
438
+ user request.
439
+
440
+ Returns:
441
+ The updated row.
442
+ """
443
+ with _tool_errors():
444
+ return ops.configure_passkey(
445
+ api(),
446
+ client_id,
447
+ origin=origin,
448
+ rp_id=rp_id,
449
+ rp_name=rp_name,
450
+ force_rp_id=force_rp_id,
451
+ ).to_dict()
452
+
453
+ @server.tool(annotations=DESTRUCTIVE)
454
+ def knuckles_clear_provider(
455
+ client_id: str, group: ProviderGroup, force_rp_id: bool = False
456
+ ) -> dict[str, Any]:
457
+ """Remove one sign-in method's configuration from a tenant.
458
+
459
+ With the operator env fallback off, this turns the method off.
460
+
461
+ Args:
462
+ client_id: The tenant id.
463
+ group: ``email``, ``google``, ``apple`` or ``passkey``.
464
+ force_rp_id: Required to clear a passkey rp_id that registered
465
+ passkeys depend on.
466
+
467
+ Returns:
468
+ The updated row.
469
+ """
470
+ with _tool_errors():
471
+ row = ops.clear_provider(api(), client_id, group, force_rp_id=force_rp_id)
472
+ return {"app": row}
473
+
474
+ return server
475
+
476
+
477
+ def install_skill(dest: Path, *, force: bool = False) -> Path:
478
+ """Copy the bundled ``knuckles-setup`` Claude Code skill into ``dest``.
479
+
480
+ Args:
481
+ dest: Skills directory, e.g. ``~/.claude/skills``.
482
+ force: Replace a local copy that differs from the bundled one.
483
+
484
+ Returns:
485
+ Path of the installed ``SKILL.md``.
486
+
487
+ Raises:
488
+ CliError: ``INVALID_INPUT`` if a different copy exists and
489
+ ``force`` is not set.
490
+ """
491
+ bundled = resources.files("knuckles_mcp").joinpath("skill/SKILL.md").read_text()
492
+ target = dest / "knuckles-setup" / "SKILL.md"
493
+ if target.exists() and target.read_text() != bundled and not force:
494
+ raise CliError(
495
+ INVALID_INPUT,
496
+ f"{target} exists and differs from the bundled skill; "
497
+ "pass --force to replace it.",
498
+ )
499
+ target.parent.mkdir(parents=True, exist_ok=True)
500
+ target.write_text(bundled)
501
+ return target
502
+
503
+
504
+ def main(argv: list[str] | None = None) -> int:
505
+ """Entry point of the ``knuckles-mcp`` console script.
506
+
507
+ With no arguments it serves MCP over stdio, which is how MCP
508
+ clients launch it. ``install-skill`` copies the bundled skill.
509
+
510
+ Args:
511
+ argv: Arguments after the program name; defaults to ``sys.argv``.
512
+
513
+ Returns:
514
+ Process exit status.
515
+ """
516
+ parser = argparse.ArgumentParser(
517
+ prog="knuckles-mcp", description="Knuckles MCP server (stdio)."
518
+ )
519
+ parser.add_argument("--version", action="version", version=__version__)
520
+ sub = parser.add_subparsers(dest="command")
521
+ skill = sub.add_parser("install-skill", help="Install the Claude Code skill.")
522
+ skill.add_argument(
523
+ "--dest",
524
+ default=str(Path.home() / ".claude" / "skills"),
525
+ help="Skills directory (default: ~/.claude/skills).",
526
+ )
527
+ skill.add_argument("--force", action="store_true", help="Replace local edits.")
528
+ args = parser.parse_args(argv)
529
+
530
+ if args.command == "install-skill":
531
+ try:
532
+ path = install_skill(Path(args.dest).expanduser(), force=args.force)
533
+ except CliError as exc:
534
+ print(f"error: {exc.message}", file=sys.stderr)
535
+ return 1
536
+ print(f"Installed the knuckles-setup skill at {path}")
537
+ return 0
538
+ build_server().run()
539
+ return 0
@@ -0,0 +1,162 @@
1
+ ---
2
+ name: knuckles-setup
3
+ description: Add sign-in (Google, Apple, email magic link, passkeys) to an app using a Knuckles identity server, end to end — create the tenant, configure each sign-in method, wire the SDK into the app, and verify with doctor. Use when the user asks to add login, sign-in, auth, or Knuckles to an app, or to set up or fix a Knuckles tenant. Needs the knuckles MCP server (knuckles-mcp).
4
+ ---
5
+
6
+ # Set up Knuckles sign-in for an app
7
+
8
+ Knuckles is a self-hosted identity server. An app (a "tenant", or app
9
+ client) sends people to it to sign in and gets back an RS256 access
10
+ token plus a rotating refresh token. The app verifies access tokens
11
+ locally against Knuckles' JWKS, so there's no per-request call.
12
+
13
+ You drive setup through the `knuckles_*` MCP tools. If they aren't
14
+ available, tell the user to install the server (see "Install" below)
15
+ and stop.
16
+
17
+ ## Rules
18
+
19
+ - **Never handle a secret in the conversation.** Don't ask the user to
20
+ paste a client secret, API key, or private key, and never put one in
21
+ a tool argument, a shell command, or a file you write by hand. The
22
+ tools take *file paths* for secrets and write tenant credentials to
23
+ `.env` themselves. If the user pastes a secret anyway, don't repeat
24
+ it; suggest they rotate it.
25
+ - **The client secret is server-side only.** It belongs in the app's
26
+ backend environment, never in a browser bundle or a `NEXT_PUBLIC_*` /
27
+ `VITE_*` variable.
28
+ - **Check before you change.** Call `knuckles_list_apps` before
29
+ creating a tenant, and `knuckles_show_app` before reconfiguring one.
30
+ - **Passkey rp_id is permanent in practice.** Changing it signs out
31
+ every registered passkey. Never pass `force_rp_id` unless the user
32
+ explicitly asks after you've explained that.
33
+ - **Finish with `knuckles_doctor`.** Fix every `fail`; explain every
34
+ `warn`.
35
+
36
+ ## Steps
37
+
38
+ ### 1. Look at the app and the server
39
+
40
+ 1. Work out the app's stack (Python: Flask / FastAPI / Django;
41
+ TypeScript: Next.js / Express / Hono), where its backend `.env`
42
+ lives, and every origin it runs on (production URL plus local dev,
43
+ e.g. `http://localhost:3000`).
44
+ 2. Call `knuckles_doctor` with no arguments. If it fails with
45
+ `NOT_LOGGED_IN` or `ADMIN_API_DISABLED`, see "Troubleshooting".
46
+ 3. Call `knuckles_list_apps`. If a tenant for this app already exists,
47
+ reuse it rather than creating a duplicate.
48
+
49
+ ### 2. Create the tenant
50
+
51
+ Confirm the tenant id, display name, and origins with the user, then
52
+ call `knuckles_create_app` with the absolute path of the app's backend
53
+ `.env`. It writes `KNUCKLES_URL`, `KNUCKLES_CLIENT_ID`, and
54
+ `KNUCKLES_CLIENT_SECRET` there. Make sure that `.env` is gitignored.
55
+
56
+ If it fails with `ENV_FILE_CONFLICT`, the file already holds different
57
+ Knuckles values. Ask the user before retrying with `overwrite: true`.
58
+
59
+ ### 3. Turn on sign-in methods
60
+
61
+ Ask which methods the user wants. Each needs something only the user
62
+ can get from a provider console; tell them exactly what to fetch, then
63
+ ask for the **file path**.
64
+
65
+ **Email magic links (Resend)**
66
+ - The user adds their sending domain at resend.com/domains and waits
67
+ for **Verified**, then saves an API key to a file (e.g.
68
+ `~/.config/knuckles/resend.key`).
69
+ - Call `knuckles_configure_email` with `from_email` (e.g.
70
+ `"My App <signin@mail.my-app.com>"`) and `api_key_file`.
71
+ - `EMAIL_DOMAIN_UNVERIFIED` means the DNS records aren't verified yet.
72
+
73
+ **Sign in with Google**
74
+ - In Google Cloud Console → APIs & Services → Credentials, the user
75
+ creates an OAuth client of type **Web application**, adds the app's
76
+ callback URL (e.g. `https://my-app.com/auth/google/callback`, plus
77
+ the localhost one) as an authorized redirect URI, and clicks
78
+ **Download JSON**.
79
+ - Call `knuckles_configure_google` with `client_secret_json`.
80
+ - A warning about a redirect origin means that origin isn't allowed on
81
+ the tenant; add it with `knuckles_set_origins` (pass the full list).
82
+
83
+ **Sign in with Apple**
84
+ - In the Apple Developer portal the user needs: the **team id**; a
85
+ **Services ID** for the website with Sign in with Apple enabled and
86
+ the app's domain and return URL registered; and a **key** with Sign
87
+ in with Apple enabled, downloaded once as `AuthKey_<KEYID>.p8`.
88
+ - Call `knuckles_configure_apple` with `services_id`, `team_id`, and
89
+ `p8_file`. The key id is read from the filename.
90
+
91
+ **Passkeys**
92
+ - Call `knuckles_configure_passkey` with the production `origin`. The
93
+ rp_id defaults to its host. To share passkeys across subdomains, use
94
+ the parent domain as `rp_id`. Passkeys only work on HTTPS and on
95
+ `localhost`.
96
+
97
+ ### 4. Wire the app
98
+
99
+ Install the SDK in the backend:
100
+ - Python: `pip install knuckles-client`
101
+ - TypeScript: `@knuckles/client` isn't on npm yet; vendor it from
102
+ `packages/knuckles-client-ts` in the Knuckles repo, or call the HTTP
103
+ API directly.
104
+
105
+ Build one client from the three env vars:
106
+
107
+ ```python
108
+ from knuckles_client import KnucklesClient
109
+
110
+ knuckles = KnucklesClient(
111
+ base_url=os.environ["KNUCKLES_URL"],
112
+ client_id=os.environ["KNUCKLES_CLIENT_ID"],
113
+ client_secret=os.environ["KNUCKLES_CLIENT_SECRET"],
114
+ )
115
+ ```
116
+
117
+ Then add, following the app's existing conventions:
118
+ 1. **Ceremony routes** on the backend for each enabled method. They
119
+ call `knuckles.<method>.start(...)` and `.complete(...)` (or
120
+ `magic_link.start` / `magic_link.verify`; `passkey.sign_in_begin` /
121
+ `sign_in_complete`), and return the token pair. Callback URLs must
122
+ be on an allowed origin and match what's registered with
123
+ Google/Apple.
124
+ 2. **Auth middleware** that reads `Authorization: Bearer <token>`,
125
+ calls `knuckles.verify_access_token(token)`, and uses `claims["sub"]`
126
+ as the user id. Treat `KnucklesTokenExpiredError` as "refresh and
127
+ retry", any other `KnucklesTokenError` as 401.
128
+ 3. **Refresh**: `knuckles.refresh(refresh_token)` returns a new pair.
129
+ **Always store the new refresh token**; the old one is consumed.
130
+ 4. **Logout**: `knuckles.logout(refresh_token)`.
131
+
132
+ Key the app's own user records by `sub`, not email (email can change).
133
+ The SDK READMEs have middleware recipes for Flask, FastAPI, Django,
134
+ Express, Hono, and Next.js.
135
+
136
+ ### 5. Verify
137
+
138
+ 1. Call `knuckles_doctor` with the tenant's `client_id`.
139
+ 2. Start the app and try one sign-in per enabled method, or ask the
140
+ user to.
141
+ 3. Summarize what's configured, what's still a warning, and where the
142
+ credentials were written.
143
+
144
+ ## Troubleshooting
145
+
146
+ | Error | Meaning | Fix |
147
+ |---|---|---|
148
+ | `NOT_LOGGED_IN` | The MCP server doesn't know which Knuckles to use. | The user runs `knuckles login --url https://<their-knuckles>` once (the `knuckles` CLI installs alongside `knuckles-mcp`), or sets `KNUCKLES_URL` and `KNUCKLES_ADMIN_TOKEN` in the MCP server's environment. |
149
+ | `ADMIN_API_DISABLED` | The server has no `KNUCKLES_ADMIN_TOKEN` set. | The operator sets it on the Knuckles deployment and redeploys. |
150
+ | `HTTP_ERROR` 401 on admin calls | Wrong admin token. | Re-run `knuckles login`. |
151
+ | `APP_CLIENT_NOT_FOUND` | Typo in `client_id`. | `knuckles_list_apps`. |
152
+ | `ENV_FILE_CONFLICT` | `.env` already has other Knuckles values. | Confirm with the user, then `overwrite: true`. |
153
+ | `EMAIL_DOMAIN_UNVERIFIED` | Resend hasn't verified the domain. | Finish DNS at resend.com/domains, then retry. |
154
+
155
+ ## Install
156
+
157
+ ```bash
158
+ uvx --from knuckles-cli knuckles login --url https://auth.example.com # once; prompts for the admin token
159
+ claude mcp add knuckles -- uvx knuckles-mcp
160
+ uvx knuckles-mcp install-skill # copies this skill to ~/.claude/skills
161
+ # or: pip install knuckles-mcp, then the same commands without `uvx`
162
+ ```
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.4
2
+ Name: knuckles-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server that lets coding agents set up Knuckles sign-in
5
+ Author-email: Garrett Sooter <garrett.sooter@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/gsooter/knuckles
8
+ Project-URL: Documentation, https://gsooter.github.io/knuckles/mcp
9
+ Project-URL: Source, https://github.com/gsooter/knuckles/tree/main/packages/knuckles-mcp
10
+ Project-URL: Issues, https://github.com/gsooter/knuckles/issues
11
+ Keywords: authentication,identity,mcp,knuckles,oauth,passkey
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Security
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: knuckles-cli<0.3,>=0.2
26
+ Requires-Dist: mcp<3,>=2.3
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest<9,>=8.0; extra == "dev"
29
+ Requires-Dist: pytest-cov<6,>=5.0; extra == "dev"
30
+ Requires-Dist: responses<1,>=0.25; extra == "dev"
31
+ Requires-Dist: cryptography<46,>=42.0; extra == "dev"
32
+ Requires-Dist: mypy<2,>=1.9; extra == "dev"
33
+ Requires-Dist: ruff==0.15.11; extra == "dev"
34
+ Requires-Dist: black<25,>=24.0; extra == "dev"
35
+ Requires-Dist: types-requests<3,>=2.31; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # knuckles-mcp
39
+
40
+ An [MCP](https://modelcontextprotocol.io) server that lets a coding
41
+ agent (Claude Code, Cursor, any MCP client) set up sign-in with your
42
+ [Knuckles](https://github.com/gsooter/knuckles) server: create a tenant
43
+ for an app, turn on Google, Apple, email magic links and passkeys, and
44
+ check the result, all from a conversation.
45
+
46
+ It ships with a Claude Code skill, `knuckles-setup`, that walks the
47
+ agent through the whole job, including wiring the SDK into the app.
48
+
49
+ ```bash
50
+ uvx --from knuckles-cli knuckles login --url https://auth.example.com # once; prompts for the admin token
51
+ claude mcp add knuckles -- uvx knuckles-mcp
52
+ uvx knuckles-mcp install-skill # optional: the setup skill
53
+ ```
54
+
55
+ Then ask your agent: *"Add Knuckles sign-in with Google and passkeys to
56
+ this app."*
57
+
58
+ No uv? `pip install knuckles-mcp` gives you both commands; drop the
59
+ `uvx` prefixes.
60
+
61
+ Your Knuckles server needs `KNUCKLES_ADMIN_TOKEN` set (Decision #021).
62
+
63
+ ## How it finds your server
64
+
65
+ The same way the `knuckles` CLI does (it's installed alongside):
66
+
67
+ 1. `KNUCKLES_URL` and `KNUCKLES_ADMIN_TOKEN` in the server's
68
+ environment, e.g. `claude mcp add knuckles -e KNUCKLES_URL=... -- uvx knuckles-mcp`.
69
+ 2. Otherwise the profile saved by `knuckles login`
70
+ (`KNUCKLES_PROFILE` picks one; default `default`).
71
+
72
+ ## Secrets stay out of the conversation
73
+
74
+ No tool takes a secret as an argument or returns one, so nothing
75
+ sensitive ends up in the agent's transcript or tool logs:
76
+
77
+ - `knuckles_create_app` and `knuckles_rotate_secret` write the client
78
+ secret straight into the `.env` file you name. They won't run
79
+ without one.
80
+ - Provider secrets are read from files on your machine: Google's
81
+ `client_secret_*.json`, Apple's `AuthKey_<KEYID>.p8`, or a file
82
+ holding your Resend API key. You can also set
83
+ `KNUCKLES_RESEND_API_KEY` / `KNUCKLES_GOOGLE_CLIENT_SECRET` in the
84
+ server's environment.
85
+ - Tenant rows come back redacted: secrets show as `*_configured`
86
+ booleans.
87
+
88
+ ## Tools
89
+
90
+ | Tool | What it does |
91
+ |---|---|
92
+ | `knuckles_doctor` | Checks the server (health, issuer, JWKS, HTTPS) and each tenant's config. Read-only. |
93
+ | `knuckles_list_apps` / `knuckles_show_app` | List tenants or show one. Read-only. |
94
+ | `knuckles_create_app` | Creates a tenant and writes `KNUCKLES_URL` / `KNUCKLES_CLIENT_ID` / `KNUCKLES_CLIENT_SECRET` into an `.env`. |
95
+ | `knuckles_set_origins` | Replaces a tenant's allowed origins. |
96
+ | `knuckles_rotate_secret` | Mints a new client secret into the `.env`; the old one stops working. |
97
+ | `knuckles_configure_email` | Resend magic-link email. Checks that the domain is verified first. |
98
+ | `knuckles_configure_google` | Google sign-in from the console's downloaded JSON. Warns about redirect URIs on disallowed origins. |
99
+ | `knuckles_configure_apple` | Sign in with Apple from the `.p8` key. Reads the key id from the filename. |
100
+ | `knuckles_configure_passkey` | WebAuthn relying party. Refuses to change an rp_id in use unless forced. |
101
+ | `knuckles_clear_provider` | Removes one sign-in method's config from a tenant. |
102
+
103
+ Errors carry the same codes as the CLI and the API
104
+ (`NOT_LOGGED_IN`, `ADMIN_API_DISABLED`, `APP_CLIENT_NOT_FOUND`,
105
+ `ENV_FILE_CONFLICT`, `EMAIL_DOMAIN_UNVERIFIED`, ...).
106
+
107
+ ## Other clients
108
+
109
+ Any MCP client that launches stdio servers works. For example, in a
110
+ JSON config:
111
+
112
+ ```json
113
+ {
114
+ "mcpServers": {
115
+ "knuckles": { "command": "uvx", "args": ["knuckles-mcp"] }
116
+ }
117
+ }
118
+ ```
119
+
120
+ ## Development
121
+
122
+ ```bash
123
+ pip install -e ../knuckles-cli -e ".[dev]"
124
+ pytest --cov=knuckles_mcp
125
+ ```
126
+
127
+ See Decision #027 in the repo's `DECISIONS.md` for the design.
128
+
129
+ ## Releasing
130
+
131
+ Bump the version in `pyproject.toml` and `__init__.py`, add a
132
+ CHANGELOG entry, merge, then push a tag:
133
+
134
+ ```bash
135
+ git tag knuckles-mcp-vX.Y.Z && git push origin knuckles-mcp-vX.Y.Z
136
+ ```
137
+
138
+ `.github/workflows/release-mcp.yml` tests, builds and publishes to PyPI
139
+ via Trusted Publishing.
140
+
141
+ knuckles-mcp depends on knuckles-cli, so tag the matching knuckles-cli release first.
@@ -0,0 +1,11 @@
1
+ knuckles_mcp/__init__.py,sha256=lMjK-2hQjpF3nrDDY7ivIOmCAA_Z6LB7PyZ57QULRkE,89
2
+ knuckles_mcp/__main__.py,sha256=TuAGYADRaN70GckwKFejfGmMWfex5JnI_qmm3Z6-2l8,108
3
+ knuckles_mcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ knuckles_mcp/server.py,sha256=Vcif7tiQngzGezocsQydAYnKwTcZBzN8avKMmX6aa1o,18605
5
+ knuckles_mcp/skill/SKILL.md,sha256=_W8y7iT0Attwomz6woW87D5oe_yBq0N-pDrEYkQCiMs,7551
6
+ knuckles_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=G3I3YS3f75NFZsGp3VGqf8HXBIW_0IuBLgIf0ItkQoQ,1071
7
+ knuckles_mcp-0.1.0.dist-info/METADATA,sha256=8q0S3v-d-Ob06ghsCgIPKAaTNFUAQ0G1l2NN_5ER6yk,5538
8
+ knuckles_mcp-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ knuckles_mcp-0.1.0.dist-info/entry_points.txt,sha256=9KMJTuv9N4lDNoCFRN-wtP1LifFmSJaqFv3BF8Ec3rs,58
10
+ knuckles_mcp-0.1.0.dist-info/top_level.txt,sha256=fM-L1sMHvkyU_nJskX8W01wpHLnQ3tU8ZJ3dok1L3Wg,13
11
+ knuckles_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ knuckles-mcp = knuckles_mcp.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Garrett Sooter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ knuckles_mcp