linc-cli-kit 0.1.1__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,201 @@
1
+ Metadata-Version: 2.5
2
+ Name: linc-cli-kit
3
+ Version: 0.1.1
4
+ Summary: Reflect a FastMCP tool registry into Click commands under one agent-grade output contract
5
+ Project-URL: Homepage, https://github.com/LincForge/cli-kit
6
+ Project-URL: Issues, https://github.com/LincForge/cli-kit/issues
7
+ Author: LINC Innovations
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Requires-Python: >=3.12
12
+ Requires-Dist: click>=8.1
13
+ Requires-Dist: mcp<2,>=1.26
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=8.0; extra == 'dev'
16
+ Requires-Dist: ruff>=0.9; extra == 'dev'
17
+ Requires-Dist: structlog>=24.0; extra == 'dev'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # linc-cli-kit
21
+
22
+ Turn a [FastMCP](https://github.com/modelcontextprotocol/python-sdk) tool registry into a Click
23
+ CLI with one agent-grade output contract: JSON on stdout, a structured error envelope on stderr,
24
+ exit codes `0`/`1`/`2`, and a `schema --json` dump of the whole command tree. An importable
25
+ conformance suite proves the CLI still matches the MCP tools. An agent that has learned one CLI
26
+ built this way has learned them all.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install linc-cli-kit # or: uv add linc-cli-kit
32
+ ```
33
+
34
+ Python 3.12+. Runtime dependencies: `click` and `mcp`.
35
+
36
+ ## Example
37
+
38
+ Save as `hello_cli.py`:
39
+
40
+ ```python
41
+ import click
42
+ from mcp.server.fastmcp import FastMCP
43
+
44
+ from linc_cli_kit import LocalTransport, install_globals, mount_tools
45
+
46
+ server = FastMCP("hello")
47
+
48
+
49
+ @server.tool()
50
+ def hello_greet(name: str, times: int = 1) -> dict:
51
+ """Greet someone. Example: hello greet --name Ada --times 2"""
52
+ return {"greeting": " ".join([f"Hello, {name}!"] * times)}
53
+
54
+
55
+ @click.group()
56
+ def main() -> None:
57
+ """hello: JSON on stdout by default, --human for text."""
58
+
59
+
60
+ install_globals(main)
61
+ mount_tools(main, server, prefix="hello_", transport=LocalTransport())
62
+
63
+ if __name__ == "__main__":
64
+ main()
65
+ ```
66
+
67
+ ```console
68
+ $ python hello_cli.py greet --name Ada --times 2
69
+ {"greeting": "Hello, Ada! Hello, Ada!"}
70
+
71
+ $ python hello_cli.py greet; echo "exit=$?"
72
+ {"error": {"code": "USAGE_ERROR", "message": "Missing option '--name'.", "hint": "", "category": "validation", "retryable": false, "details": {}}}
73
+ exit=2
74
+
75
+ $ python hello_cli.py schema --json # the whole command tree, for an agent to read once
76
+ ```
77
+
78
+ The error envelope goes to stderr and stdout stays empty, so `python hello_cli.py greet | jq`
79
+ never parses half a document.
80
+
81
+ ## Wiring a real tool
82
+
83
+ ```python
84
+ # src/<tool>/cli/main.py: a real tool with an optional local daemon
85
+ import sys
86
+ import click
87
+ from linc_cli_kit import (
88
+ HttpDaemonTransport, LocalTransport, configure_structlog_stderr,
89
+ install_globals, mount_tools,
90
+ )
91
+
92
+ configure_structlog_stderr() # MUST be above your package imports — see below
93
+
94
+ from <tool>.mcp._core import server # noqa: E402
95
+ from <tool>.core.controller import Controller # noqa: E402
96
+
97
+
98
+ @click.group()
99
+ def main() -> None:
100
+ """<tool> — JSON on stdout by default; --human for text, --stream for JSON Lines."""
101
+
102
+
103
+ install_globals(main) # adds the global flags; mount_tools refuses to run without it
104
+ main.add_command(my_hand_written_command) # hand-written commands win on name collision
105
+
106
+ mount_tools(
107
+ main, server, prefix="<tool>_",
108
+ transport=HttpDaemonTransport(
109
+ "<tool>", "http://127.0.0.1:8111",
110
+ fallback=LocalTransport(before=ensure_initialized),
111
+ daemon_only=frozenset({"<tool>_diff"}), # tools that need the daemon's in-memory state
112
+ ),
113
+ skip={"<tool>_internal": "why this tool has no CLI surface"},
114
+ renderers={"state": render_state}, # --human text per command
115
+ )
116
+ ```
117
+
118
+ **Why `configure_structlog_stderr()` goes above the imports:** modules bind their logger at
119
+ import time, so a later call leaves already-bound loggers writing to stdout — which corrupts
120
+ the JSON payload and breaks `<tool> <cmd> | jq`. Same reason `install_globals` calls
121
+ `configure_stderr_logging()` for stdlib logging.
122
+
123
+ **Transports.** `LocalTransport(fn_for=..., before=...)` calls the tool function in-process
124
+ (`before` runs one-time init; `fn_for` swaps in a different callable per spec).
125
+ `HttpDaemonTransport(tool, default_url, fallback=..., daemon_only=..., timeout=...)` posts to
126
+ `{base}/tools/{name}`. It resolves the base from `LINC_<TOOL>_DAEMON`, then
127
+ `$LINC_HOME/<tool>/daemon.port` (`LINC_HOME` defaults to `~/.linc`), then `default_url`, and
128
+ falls back to `fallback` when the daemon is down. It never falls back on a **timeout**: the
129
+ daemon is still executing the tool, so a retry would run it twice.
130
+ [nerve](https://github.com/LincForge/nerve) is the worked example.
131
+
132
+ ## Conformance test
133
+
134
+ ```python
135
+ from linc_cli_kit import assert_cli_parity
136
+ from <tool>.cli.main import main, _registry_server
137
+
138
+
139
+ def test_cli_parity() -> None:
140
+ report = assert_cli_parity(
141
+ main, _registry_server(), prefix="<tool>_",
142
+ skip={"<tool>_internal": "why this tool has no CLI surface"},
143
+ samples={"<tool>_screenshot": {"device": "emulator-5554"}},
144
+ )
145
+ assert report.tools >= 40
146
+ ```
147
+
148
+ Rules the suite enforces, so read them before adding a command:
149
+
150
+ - **Every hand-written override needs a `samples[<tool_name>]` entry.** Without one the suite
151
+ fails closed rather than silently skipping the override's JSON contract.
152
+ - **Overrides must route through the group transport** (`ctx.find_root().command.linc_transport`),
153
+ not call the tool function directly, so the suite's stubbed error payloads reach them and the
154
+ exit-code contract is actually exercised. An override that never calls the transport (it
155
+ hard-codes or locally computes its output) fails, with or without a sample.
156
+ - Generated commands are checked for option parity, `--help`, the payload handed to the
157
+ transport, and execution consistency against a direct `LocalTransport` call.
158
+ - **A sampled generated command runs once through the real transport with the process stdout
159
+ captured** at the file-descriptor level. A tool that prints, or a structlog logger bound to
160
+ stdout at import, or a child process inheriting fd 1, fails the suite: in a real CLI process
161
+ those bytes would land in the JSON payload.
162
+ - Reserved option names — `json`, `human`, `stream`, `output`, `timeout`, `log_level`, `help`,
163
+ `yes` — are remapped to `--arg-<name>` on generated commands.
164
+
165
+ ## Output contract
166
+
167
+ | | |
168
+ |---|---|
169
+ | Default | bare JSON on stdout, one document, no ANSI — strict JSON (no `NaN`/`Infinity`) |
170
+ | Encoding | dataclass → object · pydantic → `model_dump(mode="json")` · set → sorted list · bytes → base64 string · datetime/date/time → ISO 8601 · other → `str()`. A non-finite float is a `NON_JSON_VALUE` error (exit `1`), never invalid JSON. `linc_cli_kit.to_json` / `json_default` expose the same encoder |
171
+ | Modes | `--json` (default), `--human`, `--stream` (JSON Lines), or `LINC_OUTPUT=json\|human\|jsonl` |
172
+ | Failure | **empty stdout**, one `{"error": {code, message, hint, category, retryable, details}}` line on stderr — always the **last** line (see below) |
173
+ | Exit codes | `0` success · `1` tool/internal error · `2` usage/validation error |
174
+ | Discovery | `<tool> schema --json` dumps the whole command tree — no `--help` crawl |
175
+ | Artifacts | `-o/--output PATH` writes binary content and returns a `{type, path, bytes, sha256}` reference |
176
+ | Other globals | `--timeout SECONDS`, `--log-level LEVEL`; logs and heartbeats are stderr-only |
177
+ | Signals | SIGTERM → exit `143`, SIGINT → exit `130` with an `INTERRUPTED` envelope; both unwind the stack (`finally` / context managers run). SIGTERM is not optional: a watchdog hard-exits after `LINC_SIGNAL_GRACE` seconds (default 10; `inf` = never) if the unwind stalls, and a second SIGTERM (more than 0.5s after the first) hard-exits at once. SIGINT keeps Python's semantics — every Ctrl-C raises `KeyboardInterrupt` |
178
+
179
+ **Parsing stderr.** stderr may carry more than the envelope. A long call writes one
180
+ heartbeat line every 10s (`{"event": "heartbeat", "label": ..., "elapsed_s": ...}`, or
181
+ `[label] Ns elapsed` under `--human`), and stdlib/structlog logging goes to stderr too. So do
182
+ not `json.loads` the whole stream. The envelope is the **last line**: read
183
+ `stderr.strip().splitlines()[-1]`, or call `linc_cli_kit.parse_error_envelope(stderr)`. It
184
+ returns the last line that is an `{"error": {...}}` object, or `None`.
185
+
186
+ A hand-written command or group callback that raises is wrapped the same way as a generated
187
+ command: envelope, exit `1` (or the `ToolError`'s own `exit_code`), and no traceback.
188
+
189
+ ## How this repo works
190
+
191
+ This is a release mirror of a private LINC repository. The code is built by LINC's AI software
192
+ factory under human review, and each release lands here as one commit. Issues are welcome; see
193
+ [CONTRIBUTING.md](CONTRIBUTING.md). To report a security problem, see [SECURITY.md](SECURITY.md).
194
+
195
+ ## License
196
+
197
+ Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
198
+
199
+ ---
200
+
201
+ Built by [LINC Innovations](https://lincinnovations.com/audit?utm_source=github&utm_medium=readme&utm_campaign=cli-kit). We diagnose flaky device test suites.
@@ -0,0 +1,14 @@
1
+ linc_cli_kit/__init__.py,sha256=BqqKI0LrQpt09C-ihbgBIiZTYR0CspNGWoqqBtMiGhw,1973
2
+ linc_cli_kit/errors.py,sha256=dpMiW_5Oo_-flBDae_JAUIHCQimV5wlmpRdbOMCyr6A,4260
3
+ linc_cli_kit/logging.py,sha256=ToVvK19v2p8F1RGOBNkml-Z8C7zIsmhDNdXQhO8AYSY,1268
4
+ linc_cli_kit/mount.py,sha256=5krpSjAF4wT_xJ_xPjMvKBT3nqHk8tfmf4xLmWsygIc,11503
5
+ linc_cli_kit/output.py,sha256=pWsf73Jq2dlpO6N8w-W6IRGKtK9CIt9LEXfFMLok7MU,15905
6
+ linc_cli_kit/registry.py,sha256=gi1frzA_0YfwyBvLaFpx_u238o96GkkPP9IRTrx-kwM,1593
7
+ linc_cli_kit/schema.py,sha256=ztN9PCuy30GQY4arpxj6ebVkFJBhRsIZjU-M_uqOLCw,5221
8
+ linc_cli_kit/testing.py,sha256=D1jKtJ2oEBTlCmn-xDHhZpeK5dkk3OkxiaVdSNLE4Io,20390
9
+ linc_cli_kit/transport.py,sha256=qa9t8JfGQv8D0l980-nLSmS--ukLbFvwV2WjMgMUVSU,5255
10
+ linc_cli_kit-0.1.1.dist-info/METADATA,sha256=eqldDUatYTEn5xrFceWzePZM5Etp0SodLqeWboXlk08,9027
11
+ linc_cli_kit-0.1.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
12
+ linc_cli_kit-0.1.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ linc_cli_kit-0.1.1.dist-info/licenses/NOTICE,sha256=EWyv194tD9JyCjMTsUlz1IaaQyaVlykhb7Os3x_JqdI,49
14
+ linc_cli_kit-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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
+ LINC CLI Kit
2
+ Copyright 2026 LINC Innovations LLC