palanit-core 0.1.0__tar.gz

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,204 @@
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.
203
+
204
+ Copyright 2026 Stanislav Miziyev (PALANIT)
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: palanit-core
3
+ Version: 0.1.0
4
+ Summary: A watchtower for AI agents — scan MCP servers and agent tool manifests for hidden risk.
5
+ Author-email: Stanislav Miziyev <stas.m@palanit.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://palanit.com
8
+ Project-URL: Documentation, https://palanit.com/docs
9
+ Project-URL: Repository, https://github.com/stasxr/palanit-core
10
+ Project-URL: Issues, https://github.com/stasxr/palanit-core/issues
11
+ Keywords: security,mcp,ai-agents,prompt-injection,scanner,llm,supply-chain
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Topic :: Security
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ <div align="center">
24
+
25
+ # Palanit Core
26
+
27
+ ### A watchtower for AI agents.
28
+
29
+ **Scan MCP servers and AI-agent tool manifests for hidden risk — before an attacker finds it.**
30
+
31
+ [Website](https://palanit.com) · [Docs](https://palanit.com/docs) · [Palanit OS (hosted)](https://palanit.com/products/os)
32
+
33
+ </div>
34
+
35
+ ---
36
+
37
+ Your AI agent trusts tools, MCP servers and skills it didn't write. A tool's
38
+ description is injected straight into the model's context — so a *poisoned*
39
+ description can quietly tell your agent to leak a key, call an attacker's
40
+ server, or run a shell command. **Palanit Core reads every tool the way your
41
+ agent will, and flags the ones that would betray it.**
42
+
43
+ - **Zero dependencies.** Pure Python standard library. Nothing to audit but the rules.
44
+ - **Fast & local.** Runs on your machine. Sends nothing anywhere.
45
+ - **CI-ready.** Exits `1` on `HIGH`+ findings, so a poisoned tool fails the build.
46
+ - **Open & honest.** Every rule is readable. Severities reflect real impact, not upsell.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install palanit-core
52
+ ```
53
+
54
+ ## Use
55
+
56
+ ```bash
57
+ # Scan an MCP config or tool manifest
58
+ palanit scan mcp.config.json
59
+
60
+ # See it in action on the bundled malicious sample
61
+ palanit scan --sample
62
+
63
+ # Machine-readable output, fail CI on HIGH or above
64
+ palanit scan mcp.config.json --json --fail-on HIGH
65
+ ```
66
+
67
+ Example (trimmed):
68
+
69
+ ```
70
+ CRITICAL Possible data exfiltration [PL-EXFIL-001]
71
+ Instructs the agent to send sensitive data to an external URL (collector.evil.example).
72
+ ↳ mcp.config.json#/mcpServers/invoicing/tools/0/description
73
+ fix: Remove external URLs and exfiltration verbs from tool text.
74
+
75
+ HIGH Hidden instructions in tool text [PL-POISON-001]
76
+ HIGH Invisible or deceptive Unicode [PL-UNICODE-001]
77
+ MEDIUM Unpinned package / runner [PL-SUPPLY-001]
78
+ ...
79
+ 9 finding(s) (1 critical · 5 high · 3 medium)
80
+ ```
81
+
82
+ ## What it detects
83
+
84
+ | Rule | Severity | What it catches |
85
+ |------|----------|-----------------|
86
+ | `PL-POISON-001` | HIGH | Hidden / injected instructions in tool & schema descriptions |
87
+ | `PL-EXFIL-001` | MED–CRIT | Tool text that steers the agent to send data to external URLs |
88
+ | `PL-SECRET-001` | HIGH | Hardcoded API keys, tokens and private keys |
89
+ | `PL-UNICODE-001` | MED–HIGH | Invisible / bidirectional Unicode used to hide instructions |
90
+ | `PL-SUPPLY-001` | MEDIUM | Unpinned / floating package versions (`@latest`, bare names) |
91
+ | `PL-SHELL-001` | MED–HIGH | Tools that launch a shell (`bash -c`, `cmd /c`, …) |
92
+ | `PL-TLS-001` | LOW–MED | Endpoints over `http://` / `ws://` without TLS |
93
+ | `PL-COLLIDE-001` | MEDIUM | Duplicate tool names that let one shadow another |
94
+ | `PL-ENV-001` | HIGH | Literal secrets in a server's `env` block |
95
+
96
+ Run `palanit rules` to list them. Inputs understood: Claude-style `mcpServers`
97
+ configs, `servers` configs, `tools` manifests, a bare list of tools, or a single
98
+ tool object. Unknown JSON still gets string-level checks.
99
+
100
+ ## Use it in CI
101
+
102
+ ```yaml
103
+ # .github/workflows/palanit.yml
104
+ name: palanit
105
+ on: [push, pull_request]
106
+ jobs:
107
+ scan:
108
+ runs-on: ubuntu-latest
109
+ steps:
110
+ - uses: actions/checkout@v4
111
+ - uses: actions/setup-python@v5
112
+ with: { python-version: "3.12" }
113
+ - run: pip install palanit-core
114
+ - run: palanit scan mcp.config.json --fail-on HIGH
115
+ ```
116
+
117
+ ## Responsible use
118
+
119
+ Palanit Core only reads files you give it — but the broader PALANIT suite
120
+ (botprobe) sends live test traffic. **Only scan or test systems you own or are
121
+ authorized to test.** A clean scan reduces risk; it does not prove safety.
122
+
123
+ ## Beyond the CLI
124
+
125
+ - **[Palanit OS](https://palanit.com/products/os)** — the same engine in your browser, plus continuous monitoring, change alerts and shareable reports.
126
+ - **[Palanit Bot Killer](https://palanit.com/products/bot-killer)** — block hostile AI crawlers and red-team your own chatbot with botprobe.
127
+
128
+ ## License
129
+
130
+ Apache-2.0 © Stanislav Miziyev. Contributions welcome — see [CONTRIBUTING](CONTRIBUTING.md).
@@ -0,0 +1,108 @@
1
+ <div align="center">
2
+
3
+ # Palanit Core
4
+
5
+ ### A watchtower for AI agents.
6
+
7
+ **Scan MCP servers and AI-agent tool manifests for hidden risk — before an attacker finds it.**
8
+
9
+ [Website](https://palanit.com) · [Docs](https://palanit.com/docs) · [Palanit OS (hosted)](https://palanit.com/products/os)
10
+
11
+ </div>
12
+
13
+ ---
14
+
15
+ Your AI agent trusts tools, MCP servers and skills it didn't write. A tool's
16
+ description is injected straight into the model's context — so a *poisoned*
17
+ description can quietly tell your agent to leak a key, call an attacker's
18
+ server, or run a shell command. **Palanit Core reads every tool the way your
19
+ agent will, and flags the ones that would betray it.**
20
+
21
+ - **Zero dependencies.** Pure Python standard library. Nothing to audit but the rules.
22
+ - **Fast & local.** Runs on your machine. Sends nothing anywhere.
23
+ - **CI-ready.** Exits `1` on `HIGH`+ findings, so a poisoned tool fails the build.
24
+ - **Open & honest.** Every rule is readable. Severities reflect real impact, not upsell.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install palanit-core
30
+ ```
31
+
32
+ ## Use
33
+
34
+ ```bash
35
+ # Scan an MCP config or tool manifest
36
+ palanit scan mcp.config.json
37
+
38
+ # See it in action on the bundled malicious sample
39
+ palanit scan --sample
40
+
41
+ # Machine-readable output, fail CI on HIGH or above
42
+ palanit scan mcp.config.json --json --fail-on HIGH
43
+ ```
44
+
45
+ Example (trimmed):
46
+
47
+ ```
48
+ CRITICAL Possible data exfiltration [PL-EXFIL-001]
49
+ Instructs the agent to send sensitive data to an external URL (collector.evil.example).
50
+ ↳ mcp.config.json#/mcpServers/invoicing/tools/0/description
51
+ fix: Remove external URLs and exfiltration verbs from tool text.
52
+
53
+ HIGH Hidden instructions in tool text [PL-POISON-001]
54
+ HIGH Invisible or deceptive Unicode [PL-UNICODE-001]
55
+ MEDIUM Unpinned package / runner [PL-SUPPLY-001]
56
+ ...
57
+ 9 finding(s) (1 critical · 5 high · 3 medium)
58
+ ```
59
+
60
+ ## What it detects
61
+
62
+ | Rule | Severity | What it catches |
63
+ |------|----------|-----------------|
64
+ | `PL-POISON-001` | HIGH | Hidden / injected instructions in tool & schema descriptions |
65
+ | `PL-EXFIL-001` | MED–CRIT | Tool text that steers the agent to send data to external URLs |
66
+ | `PL-SECRET-001` | HIGH | Hardcoded API keys, tokens and private keys |
67
+ | `PL-UNICODE-001` | MED–HIGH | Invisible / bidirectional Unicode used to hide instructions |
68
+ | `PL-SUPPLY-001` | MEDIUM | Unpinned / floating package versions (`@latest`, bare names) |
69
+ | `PL-SHELL-001` | MED–HIGH | Tools that launch a shell (`bash -c`, `cmd /c`, …) |
70
+ | `PL-TLS-001` | LOW–MED | Endpoints over `http://` / `ws://` without TLS |
71
+ | `PL-COLLIDE-001` | MEDIUM | Duplicate tool names that let one shadow another |
72
+ | `PL-ENV-001` | HIGH | Literal secrets in a server's `env` block |
73
+
74
+ Run `palanit rules` to list them. Inputs understood: Claude-style `mcpServers`
75
+ configs, `servers` configs, `tools` manifests, a bare list of tools, or a single
76
+ tool object. Unknown JSON still gets string-level checks.
77
+
78
+ ## Use it in CI
79
+
80
+ ```yaml
81
+ # .github/workflows/palanit.yml
82
+ name: palanit
83
+ on: [push, pull_request]
84
+ jobs:
85
+ scan:
86
+ runs-on: ubuntu-latest
87
+ steps:
88
+ - uses: actions/checkout@v4
89
+ - uses: actions/setup-python@v5
90
+ with: { python-version: "3.12" }
91
+ - run: pip install palanit-core
92
+ - run: palanit scan mcp.config.json --fail-on HIGH
93
+ ```
94
+
95
+ ## Responsible use
96
+
97
+ Palanit Core only reads files you give it — but the broader PALANIT suite
98
+ (botprobe) sends live test traffic. **Only scan or test systems you own or are
99
+ authorized to test.** A clean scan reduces risk; it does not prove safety.
100
+
101
+ ## Beyond the CLI
102
+
103
+ - **[Palanit OS](https://palanit.com/products/os)** — the same engine in your browser, plus continuous monitoring, change alerts and shareable reports.
104
+ - **[Palanit Bot Killer](https://palanit.com/products/bot-killer)** — block hostile AI crawlers and red-team your own chatbot with botprobe.
105
+
106
+ ## License
107
+
108
+ Apache-2.0 © Stanislav Miziyev. Contributions welcome — see [CONTRIBUTING](CONTRIBUTING.md).
@@ -0,0 +1,9 @@
1
+ """PALANIT Core — a watchtower for AI agents.
2
+
3
+ Open-source scanner for MCP servers and AI-agent tool manifests.
4
+ """
5
+ from .models import Severity, Finding, ScanResult
6
+ from .engine import scan_files, scan_data
7
+
8
+ __version__ = "0.1.0"
9
+ __all__ = ["Severity", "Finding", "ScanResult", "scan_files", "scan_data", "__version__"]
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,101 @@
1
+ """PALANIT Core command-line interface.
2
+
3
+ Usage:
4
+ palanit scan <file...> [--json] [--fail-on LEVEL] [--no-color]
5
+ palanit scan --sample
6
+ palanit rules
7
+ palanit version
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import os
13
+ import sys
14
+
15
+ from . import __version__
16
+ from .engine import scan_files
17
+ from .models import Severity
18
+ from .report import to_json, to_text
19
+ from . import rules as rules_mod
20
+
21
+ SAMPLE = os.path.join(os.path.dirname(__file__), "samples", "malicious.mcp.json")
22
+
23
+
24
+ def _cmd_scan(args: argparse.Namespace) -> int:
25
+ paths = list(args.files)
26
+ if args.sample:
27
+ paths.append(SAMPLE)
28
+ if not paths:
29
+ print("palanit: no files to scan. Pass a file, or --sample.", file=sys.stderr)
30
+ return 2
31
+
32
+ result = scan_files(paths)
33
+
34
+ if args.json:
35
+ print(to_json(result))
36
+ else:
37
+ print(to_text(result, no_color=args.no_color))
38
+
39
+ try:
40
+ threshold = Severity.parse(args.fail_on)
41
+ except ValueError:
42
+ print(f"palanit: invalid --fail-on value {args.fail_on!r}", file=sys.stderr)
43
+ return 2
44
+
45
+ top = result.max_severity()
46
+ if top is not None and top >= threshold:
47
+ return 1
48
+ return 0
49
+
50
+
51
+ def _cmd_rules(_args: argparse.Namespace) -> int:
52
+ for rule_id, title, _fn in sorted(rules_mod.all_rules()):
53
+ print(f"{rule_id:<16} {title}")
54
+ return 0
55
+
56
+
57
+ def _cmd_version(_args: argparse.Namespace) -> int:
58
+ print(f"palanit-core {__version__}")
59
+ return 0
60
+
61
+
62
+ def build_parser() -> argparse.ArgumentParser:
63
+ p = argparse.ArgumentParser(
64
+ prog="palanit",
65
+ description="PALANIT — scan MCP servers and AI-agent tool manifests for hidden risk.",
66
+ epilog="Only scan systems you own or are authorized to test.",
67
+ )
68
+ p.add_argument("-V", "--version", action="store_true", help="print version and exit")
69
+ sub = p.add_subparsers(dest="command")
70
+
71
+ s = sub.add_parser("scan", help="scan one or more JSON files")
72
+ s.add_argument("files", nargs="*", help="MCP config or tool manifest JSON file(s)")
73
+ s.add_argument("--json", action="store_true", help="machine-readable JSON output")
74
+ s.add_argument("--fail-on", default="HIGH", metavar="LEVEL",
75
+ help="exit 1 if any finding is at this severity or above "
76
+ "(INFO|LOW|MEDIUM|HIGH|CRITICAL; default HIGH)")
77
+ s.add_argument("--no-color", action="store_true", help="disable ANSI colors")
78
+ s.add_argument("--sample", action="store_true", help="also scan the bundled malicious sample")
79
+ s.set_defaults(func=_cmd_scan)
80
+
81
+ r = sub.add_parser("rules", help="list detection rules")
82
+ r.set_defaults(func=_cmd_rules)
83
+
84
+ v = sub.add_parser("version", help="print version")
85
+ v.set_defaults(func=_cmd_version)
86
+ return p
87
+
88
+
89
+ def main(argv: list[str] | None = None) -> int:
90
+ parser = build_parser()
91
+ args = parser.parse_args(argv)
92
+ if getattr(args, "version", False):
93
+ return _cmd_version(args)
94
+ if not getattr(args, "command", None):
95
+ parser.print_help()
96
+ return 2
97
+ return args.func(args)
98
+
99
+
100
+ if __name__ == "__main__":
101
+ raise SystemExit(main())
@@ -0,0 +1,49 @@
1
+ """Scan orchestration: load targets, run rules, collect findings."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+
7
+ from . import rules as rules_mod
8
+ from .loaders import load_json, normalize, walk_strings
9
+ from .models import ScanResult
10
+
11
+
12
+ def scan_data(raw, filename: str = "<data>") -> ScanResult:
13
+ """Scan an already-parsed JSON structure."""
14
+ result = ScanResult(targets=[filename])
15
+ norm = normalize(raw)
16
+ result.scanned_servers = len(norm.servers)
17
+ result.scanned_tools = len(norm.tools)
18
+ result.scanned_strings = len(walk_strings(raw))
19
+ ctx = rules_mod.Context(norm=norm, filename=filename)
20
+ for rule_id, _title, fn in rules_mod.all_rules():
21
+ try:
22
+ for finding in fn(ctx):
23
+ result.add(finding)
24
+ except Exception as exc: # a broken rule must never crash the scan
25
+ result.errors.append(f"rule {rule_id} failed: {exc}")
26
+ return result
27
+
28
+
29
+ def scan_files(paths: list[str]) -> ScanResult:
30
+ """Scan one or more JSON files, merging findings into one result."""
31
+ merged = ScanResult()
32
+ for path in paths:
33
+ name = os.path.basename(path)
34
+ merged.targets.append(path)
35
+ try:
36
+ raw = load_json(path)
37
+ except FileNotFoundError:
38
+ merged.errors.append(f"{name}: file not found")
39
+ continue
40
+ except json.JSONDecodeError as exc:
41
+ merged.errors.append(f"{name}: invalid JSON ({exc})")
42
+ continue
43
+ sub = scan_data(raw, filename=name)
44
+ merged.findings.extend(sub.findings)
45
+ merged.scanned_servers += sub.scanned_servers
46
+ merged.scanned_tools += sub.scanned_tools
47
+ merged.scanned_strings += sub.scanned_strings
48
+ merged.errors.extend(sub.errors)
49
+ return merged