mcp-wizard-generators 0.5.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.
Files changed (35) hide show
  1. mcp_wizard_generators/__init__.py +34 -0
  2. mcp_wizard_generators/__main__.py +5 -0
  3. mcp_wizard_generators/cli.py +191 -0
  4. mcp_wizard_generators/codegen.py +113 -0
  5. mcp_wizard_generators/findings.py +214 -0
  6. mcp_wizard_generators/models.py +261 -0
  7. mcp_wizard_generators/openapi.py +304 -0
  8. mcp_wizard_generators/package_name.py +70 -0
  9. mcp_wizard_generators/packaging/__init__.py +5 -0
  10. mcp_wizard_generators/packaging/ziputil.py +50 -0
  11. mcp_wizard_generators/paths.py +38 -0
  12. mcp_wizard_generators/pipeline.py +126 -0
  13. mcp_wizard_generators/plugins/__init__.py +1 -0
  14. mcp_wizard_generators/plugins/agentcore/__init__.py +5 -0
  15. mcp_wizard_generators/plugins/agentcore/plugin.py +274 -0
  16. mcp_wizard_generators/plugins/python_mcp/__init__.py +5 -0
  17. mcp_wizard_generators/plugins/python_mcp/annotations.py +173 -0
  18. mcp_wizard_generators/plugins/python_mcp/client_template.py +278 -0
  19. mcp_wizard_generators/plugins/python_mcp/lock/requirements.in +6 -0
  20. mcp_wizard_generators/plugins/python_mcp/lock/requirements.txt +609 -0
  21. mcp_wizard_generators/plugins/python_mcp/plugin.py +1122 -0
  22. mcp_wizard_generators/plugins/python_mcp/tests_template.py +582 -0
  23. mcp_wizard_generators/python_mcp.py +244 -0
  24. mcp_wizard_generators/registry.py +63 -0
  25. mcp_wizard_generators/rules/__init__.py +15 -0
  26. mcp_wizard_generators/rules/anthropic.py +43 -0
  27. mcp_wizard_generators/rules/base.py +37 -0
  28. mcp_wizard_generators/rules/cursor.py +44 -0
  29. mcp_wizard_generators/rules/hooks.py +26 -0
  30. mcp_wizard_generators/toolmap.py +84 -0
  31. mcp_wizard_generators-0.5.0.dist-info/METADATA +388 -0
  32. mcp_wizard_generators-0.5.0.dist-info/RECORD +35 -0
  33. mcp_wizard_generators-0.5.0.dist-info/WHEEL +4 -0
  34. mcp_wizard_generators-0.5.0.dist-info/entry_points.txt +2 -0
  35. mcp_wizard_generators-0.5.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,34 @@
1
+ """MCP Wizard generators — IR → MCP tool map → file tree (no HTTP servers)."""
2
+
3
+ from mcp_wizard_generators.findings import Finding, operation_findings
4
+ from mcp_wizard_generators.models import (
5
+ FileEntry,
6
+ FileTree,
7
+ GenerateContext,
8
+ IntermediateRep,
9
+ ToolMap,
10
+ ToolMapping,
11
+ )
12
+ from mcp_wizard_generators.package_name import validate_package_name
13
+ from mcp_wizard_generators.pipeline import generate
14
+ from mcp_wizard_generators.python_mcp import generate_python_mcp, generate_python_mcp_result
15
+ from mcp_wizard_generators.registry import GeneratorRegistry, get_default_registry
16
+
17
+ __all__ = [
18
+ "FileEntry",
19
+ "FileTree",
20
+ "Finding",
21
+ "GenerateContext",
22
+ "GeneratorRegistry",
23
+ "IntermediateRep",
24
+ "ToolMap",
25
+ "ToolMapping",
26
+ "generate",
27
+ "generate_python_mcp",
28
+ "generate_python_mcp_result",
29
+ "get_default_registry",
30
+ "operation_findings",
31
+ "validate_package_name",
32
+ ]
33
+
34
+ __version__ = "0.5.0"
@@ -0,0 +1,5 @@
1
+ """python -m mcp_wizard_generators"""
2
+
3
+ from mcp_wizard_generators.cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,191 @@
1
+ """CLI entry for mcp-wizard-api workers and local golden runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from mcp_wizard_generators.models import (
11
+ AUTH_MODES,
12
+ AgentRulesBundle,
13
+ IntermediateRep,
14
+ SecurityConfig,
15
+ )
16
+ from mcp_wizard_generators.packaging import pack_file_tree_to_zip
17
+ from mcp_wizard_generators.paths import resolve_user_path
18
+ from mcp_wizard_generators.pipeline import generate
19
+ from mcp_wizard_generators.python_mcp import generate_python_mcp
20
+ from mcp_wizard_generators.registry import get_default_registry
21
+
22
+
23
+ def _path_type(value: str) -> Path:
24
+ """Argparse type: expand ``~`` on macOS / Windows / Linux."""
25
+ return resolve_user_path(value)
26
+
27
+
28
+ def _load_json(path: Path) -> dict:
29
+ return json.loads(path.read_text(encoding="utf-8"))
30
+
31
+
32
+ def build_parser() -> argparse.ArgumentParser:
33
+ p = argparse.ArgumentParser(
34
+ prog="mcp-wizard-gen",
35
+ description="Generate an MCP project tree from an IR JSON snapshot (no server).",
36
+ )
37
+ sub = p.add_subparsers(dest="command", required=True)
38
+
39
+ list_p = sub.add_parser("list-targets", help="List registered generator plugins")
40
+ list_p.set_defaults(func=cmd_list_targets)
41
+
42
+ gen = sub.add_parser("generate", help="IR JSON → file tree and/or zip")
43
+ gen.add_argument("--ir", required=True, type=_path_type, help="Path to IntermediateRep JSON")
44
+ gen.add_argument("--target", default="local", help="Generator target (default: local)")
45
+ gen.add_argument("--language", default="python")
46
+ gen.add_argument(
47
+ "--select",
48
+ action="append",
49
+ default=None,
50
+ help="Operation id to include (repeatable; default = all)",
51
+ )
52
+ gen.add_argument("--package-name", default="generated_mcp")
53
+ gen.add_argument("--out-dir", type=_path_type, help="Write file tree to this directory")
54
+ gen.add_argument("--zip", type=_path_type, help="Write zip archive to this path")
55
+ gen.add_argument("--manifest", type=_path_type, help="Write generation manifest JSON")
56
+ gen.add_argument("--auth-mode", default="none", choices=sorted(AUTH_MODES))
57
+ gen.add_argument(
58
+ "--security",
59
+ type=_path_type,
60
+ help="Experience API SecurityConfig JSON (authMode, apiKey, oauth); overrides --auth-mode",
61
+ )
62
+ gen.add_argument(
63
+ "--rules-dir", type=_path_type, help="Optional directory of Agent Rules originals"
64
+ )
65
+ gen.add_argument(
66
+ "--rules-family",
67
+ default="unknown",
68
+ choices=["cursor", "anthropic", "mixed", "unknown"],
69
+ )
70
+ gen.set_defaults(func=cmd_generate)
71
+
72
+ py = sub.add_parser(
73
+ "generate-python",
74
+ help="Convenience: local Python MCP (FastMCP/MCPServer) → out-dir and/or zip",
75
+ )
76
+ py.add_argument(
77
+ "--ir",
78
+ type=_path_type,
79
+ help="Path to IntermediateRep JSON (or simple {title,servers,operations} JSON)",
80
+ )
81
+ py.add_argument(
82
+ "--operations",
83
+ type=_path_type,
84
+ help="Optional JSON file: list of operation ids or operation objects",
85
+ )
86
+ py.add_argument(
87
+ "--select",
88
+ action="append",
89
+ default=None,
90
+ help="Operation id to include (repeatable; alternative to --operations)",
91
+ )
92
+ py.add_argument("--package-name", default="generated_mcp")
93
+ py.add_argument("--out-dir", type=_path_type, help="Write file tree to this directory")
94
+ py.add_argument("--zip", type=_path_type, help="Write zip archive to this path")
95
+ py.add_argument("--auth-mode", default="none", choices=sorted(AUTH_MODES))
96
+ py.add_argument(
97
+ "--security",
98
+ type=_path_type,
99
+ help="Experience API SecurityConfig JSON (authMode, apiKey, oauth); overrides --auth-mode",
100
+ )
101
+ py.set_defaults(func=cmd_generate_python)
102
+ return p
103
+
104
+
105
+ def cmd_list_targets(_: argparse.Namespace) -> int:
106
+ for item in get_default_registry().list_targets():
107
+ print(f"{item['key']}/{item['language']}\t{item['display_name']}")
108
+ return 0
109
+
110
+
111
+ def _load_rules(args: argparse.Namespace) -> AgentRulesBundle:
112
+ if not args.rules_dir:
113
+ return AgentRulesBundle()
114
+ root = Path(args.rules_dir)
115
+ originals: dict[str, str] = {}
116
+ for path in root.rglob("*"):
117
+ if path.is_file():
118
+ originals[str(path.relative_to(root))] = path.read_text(encoding="utf-8")
119
+ return AgentRulesBundle(format_family=args.rules_family, originals=originals)
120
+
121
+
122
+ def _security(args: argparse.Namespace) -> SecurityConfig:
123
+ try:
124
+ if args.security:
125
+ return SecurityConfig.from_wizard(_load_json(args.security))
126
+ return SecurityConfig(auth_mode=args.auth_mode)
127
+ except ValueError as exc:
128
+ raise SystemExit(f"invalid security config: {exc}") from exc
129
+
130
+
131
+ def cmd_generate(args: argparse.Namespace) -> int:
132
+ ir = IntermediateRep.from_dict(_load_json(args.ir))
133
+ result = generate(
134
+ ir,
135
+ target=args.target,
136
+ language=args.language,
137
+ selected_operation_ids=args.select,
138
+ security=_security(args),
139
+ agent_rules=_load_rules(args),
140
+ package_name=args.package_name,
141
+ fail_on_rules_errors=False if args.target == "local" else True,
142
+ )
143
+ if args.out_dir:
144
+ result.tree.write_to(args.out_dir)
145
+ if args.zip:
146
+ pack_file_tree_to_zip(result.tree, args.zip)
147
+ if args.manifest:
148
+ args.manifest.parent.mkdir(parents=True, exist_ok=True)
149
+ args.manifest.write_text(json.dumps(result.manifest, indent=2) + "\n", encoding="utf-8")
150
+ if not args.out_dir and not args.zip and not args.manifest:
151
+ print(json.dumps(result.manifest, indent=2))
152
+ return 0
153
+
154
+
155
+ def cmd_generate_python(args: argparse.Namespace) -> int:
156
+ if not args.ir and not args.operations:
157
+ raise SystemExit("generate-python requires --ir and/or --operations")
158
+ if not args.out_dir and not args.zip:
159
+ raise SystemExit("generate-python requires --out-dir and/or --zip")
160
+
161
+ spec = _load_json(args.ir) if args.ir else {}
162
+ operations: list | None = args.select
163
+ if args.operations:
164
+ loaded = json.loads(Path(args.operations).read_text(encoding="utf-8"))
165
+ if isinstance(loaded, dict) and "operations" in loaded and not args.ir:
166
+ spec = loaded
167
+ operations = args.select
168
+ else:
169
+ operations = loaded
170
+
171
+ path = generate_python_mcp(
172
+ spec,
173
+ operations,
174
+ out_dir=args.out_dir,
175
+ zip_path=args.zip,
176
+ package_name=args.package_name,
177
+ security=_security(args),
178
+ )
179
+ # Pathlib str() is OS-native; fine for humans and shell copy-paste.
180
+ print(path)
181
+ return 0
182
+
183
+
184
+ def main(argv: list[str] | None = None) -> int:
185
+ parser = build_parser()
186
+ args = parser.parse_args(argv)
187
+ return int(args.func(args))
188
+
189
+
190
+ if __name__ == "__main__":
191
+ sys.exit(main())
@@ -0,0 +1,113 @@
1
+ """Safe emission of untrusted spec values into generated source and config files.
2
+
3
+ OpenAPI documents are user-supplied. Never paste a spec value into generated code
4
+ with plain string formatting; route it through one of these helpers instead.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import keyword
11
+ import math
12
+ import re
13
+ from collections.abc import Iterable
14
+ from typing import Any
15
+
16
+ HTTP_METHODS = frozenset({"get", "post", "put", "patch", "delete", "head", "options", "trace"})
17
+
18
+
19
+ def py_str(value: str) -> str:
20
+ """A Python string literal for ``value`` (JSON string syntax is valid Python)."""
21
+ return json.dumps(str(value))
22
+
23
+
24
+ def docstring_text(value: str) -> str:
25
+ """Text safe to place between triple double quotes.
26
+
27
+ Escapes backslashes and every double quote (so ``\"\"\"`` and a trailing quote
28
+ cannot close the docstring), and escapes non-printable characters such as NUL.
29
+ """
30
+ out: list[str] = []
31
+ for ch in str(value).replace("\r\n", "\n"):
32
+ if ch == "\\":
33
+ out.append("\\\\")
34
+ elif ch == '"':
35
+ out.append('\\"')
36
+ elif ch in "\n\t" or ch.isprintable():
37
+ out.append(ch)
38
+ elif ord(ch) <= 0xFF:
39
+ out.append(f"\\x{ord(ch):02x}")
40
+ elif ord(ch) <= 0xFFFF:
41
+ out.append(f"\\u{ord(ch):04x}")
42
+ else:
43
+ out.append(f"\\U{ord(ch):08x}")
44
+ return "".join(out)
45
+
46
+
47
+ def toml_str(value: str) -> str:
48
+ """A TOML basic string for ``value``."""
49
+ # ensure_ascii=False avoids surrogate-pair escapes, which TOML rejects;
50
+ # JSON already escapes C0 controls, TOML also requires DEL to be escaped.
51
+ return json.dumps(str(value), ensure_ascii=False).replace("\x7f", "\\u007f")
52
+
53
+
54
+ _CONTROL_RUN = re.compile(r"[\x00-\x1f\x7f-\x9f

]+")
55
+
56
+
57
+ def one_line(value: str) -> str:
58
+ """Collapse line breaks and control characters to single spaces (Markdown, .env)."""
59
+ return _CONTROL_RUN.sub(" ", str(value)).strip()
60
+
61
+
62
+ def env_value(value: str) -> str:
63
+ """A value that cannot start a new line in a dotenv file."""
64
+ return one_line(value)
65
+
66
+
67
+ def py_ident(name: str, taken: set[str], reserved: Iterable[str] = ()) -> str:
68
+ """Map ``name`` to a unique, safe Python identifier and record it in ``taken``.
69
+
70
+ Non-identifier characters become ``_``; a leading digit gets a ``p_`` prefix;
71
+ keywords and ``reserved`` names get a trailing ``_``; collisions get more ``_``.
72
+ """
73
+ ident = re.sub(r"\W", "_", str(name), flags=re.ASCII) or "param"
74
+ if ident[0].isdigit():
75
+ ident = f"p_{ident}"
76
+ reserved_set = set(reserved)
77
+ if keyword.iskeyword(ident) or ident in reserved_set:
78
+ ident = f"{ident}_"
79
+ while ident in taken or keyword.iskeyword(ident) or ident in reserved_set:
80
+ ident = f"{ident}_"
81
+ taken.add(ident)
82
+ return ident
83
+
84
+
85
+ def py_literal(obj: Any, indent: int = 2, _level: int = 0) -> str:
86
+ """A Python literal for JSON-like data, laid out like ``json.dumps(indent=2)``.
87
+
88
+ Unlike JSON text it uses ``True`` / ``False`` / ``None``, so it is valid Python
89
+ (``ast.literal_eval``-safe). Non-finite floats and unknown types become strings.
90
+ """
91
+ pad = " " * (indent * (_level + 1))
92
+ end = " " * (indent * _level)
93
+ if obj is None or isinstance(obj, bool):
94
+ return repr(obj)
95
+ if isinstance(obj, int):
96
+ return repr(int(obj))
97
+ if isinstance(obj, float):
98
+ return repr(obj) if math.isfinite(obj) else py_str(repr(obj))
99
+ if isinstance(obj, str):
100
+ return py_str(obj)
101
+ if isinstance(obj, dict):
102
+ if not obj:
103
+ return "{}"
104
+ items = [
105
+ f"{pad}{py_str(str(k))}: {py_literal(v, indent, _level + 1)}" for k, v in obj.items()
106
+ ]
107
+ return "{\n" + ",\n".join(items) + "\n" + end + "}"
108
+ if isinstance(obj, list | tuple):
109
+ if not obj:
110
+ return "[]"
111
+ items = [f"{pad}{py_literal(v, indent, _level + 1)}" for v in obj]
112
+ return "[\n" + ",\n".join(items) + "\n" + end + "]"
113
+ return py_str(str(obj))
@@ -0,0 +1,214 @@
1
+ """Secret-exposure findings for OpenAPI operations (design ADR-023).
2
+
3
+ One check, shared by the Experience API (operation list: warning labels and
4
+ which operations start unticked) and the generators (manifest, SECURITY-NOTES.md,
5
+ tool descriptions), so the wizard and the zip always agree.
6
+
7
+ A parameter is *sensitive* when its name or its schema says it carries a secret.
8
+ Where it travels sets the severity: a URL (query or path) ends up in proxy, server
9
+ and client logs, browser history and error messages, so that is **medium**.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from dataclasses import asdict, dataclass
16
+ from typing import Any
17
+
18
+ from mcp_wizard_generators.openapi import IN_KEY, openapi_to_ir
19
+
20
+ # Tokens that name a secret on their own (after splitting on case and punctuation).
21
+ _SECRET_TOKENS = frozenset(
22
+ {
23
+ "password",
24
+ "passwd",
25
+ "pwd",
26
+ "passphrase",
27
+ "secret",
28
+ "token",
29
+ "credential",
30
+ "credentials",
31
+ "authorization",
32
+ "ssn",
33
+ # Run-together spellings.
34
+ "apikey",
35
+ "accesskey",
36
+ "privatekey",
37
+ "clientsecret",
38
+ "sessionid",
39
+ "accesstoken",
40
+ "refreshtoken",
41
+ "authtoken",
42
+ }
43
+ )
44
+ # Adjacent token pairs that name a secret ("api key", "session id").
45
+ _SECRET_PAIRS = frozenset(
46
+ {
47
+ ("api", "key"),
48
+ ("access", "key"),
49
+ ("private", "key"),
50
+ ("secret", "key"),
51
+ ("session", "id"),
52
+ }
53
+ )
54
+ # "token" next to one of these is pagination or metadata, not a credential.
55
+ _TOKEN_EXEMPT = frozenset(
56
+ {
57
+ "page",
58
+ "next",
59
+ "prev",
60
+ "previous",
61
+ "continuation",
62
+ "cursor",
63
+ "sync",
64
+ "pagination",
65
+ "type",
66
+ "url",
67
+ "uri",
68
+ "endpoint",
69
+ "count",
70
+ "expires",
71
+ "expiry",
72
+ "expiration",
73
+ "id",
74
+ }
75
+ )
76
+
77
+ URL_REMEDIATION = (
78
+ "Leave this operation unticked unless you need it. If you keep it, run the server only "
79
+ "where request URLs are not logged, and ask the API provider for a login that takes "
80
+ "credentials in a header or request body."
81
+ )
82
+
83
+ # location -> (code, severity, message template, remediation, short form for tool descriptions)
84
+ _RULES: dict[str, tuple[str, str, str, str, str]] = {
85
+ "query": (
86
+ "secret_in_query",
87
+ "medium",
88
+ "Sends {p} in the URL query string, where proxies, servers and logs can record it.",
89
+ URL_REMEDIATION,
90
+ "sends {p} in the URL query string",
91
+ ),
92
+ "path": (
93
+ "secret_in_path",
94
+ "medium",
95
+ "Puts {p} in the URL path, where proxies, servers and logs can record it.",
96
+ URL_REMEDIATION,
97
+ "puts {p} in the URL path",
98
+ ),
99
+ "cookie": (
100
+ "secret_in_cookie",
101
+ "low",
102
+ "Sends {p} in a cookie. Cookies are rarely logged, but proxies and browsers can keep them.",
103
+ "Keep this operation only if you trust every proxy between the server and the API.",
104
+ "sends {p} in a cookie",
105
+ ),
106
+ "header": (
107
+ "secret_in_header",
108
+ "info",
109
+ "Sends {p} in a request header, the usual place for a credential.",
110
+ "No action needed.",
111
+ "sends {p} in a header",
112
+ ),
113
+ "body": (
114
+ "secret_in_body",
115
+ "info",
116
+ "Sends {p} in the request body, which is not part of the URL.",
117
+ "No action needed.",
118
+ "sends {p} in the request body",
119
+ ),
120
+ }
121
+
122
+ BLOCKING_SEVERITIES = frozenset({"medium", "high"})
123
+
124
+
125
+ @dataclass(frozen=True)
126
+ class Finding:
127
+ """One finding, shaped like the Experience API ``OperationFinding``."""
128
+
129
+ code: str
130
+ severity: str
131
+ parameter: str | None
132
+ location: str | None
133
+ message: str
134
+ remediation: str
135
+
136
+ def to_dict(self) -> dict[str, Any]:
137
+ return asdict(self)
138
+
139
+ @property
140
+ def short(self) -> str:
141
+ """Lower-case clause for a tool description ("sends password in ...")."""
142
+ rule = _RULES.get(self.location or "")
143
+ return rule[4].format(p=self.parameter) if rule else self.message
144
+
145
+
146
+ def _tokens(name: str) -> list[str]:
147
+ spaced = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", name)
148
+ spaced = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", spaced) # "APIKey" -> "API Key"
149
+ return [t.lower() for t in re.split(r"[^A-Za-z0-9]+", spaced) if t]
150
+
151
+
152
+ def is_sensitive(name: str, schema: dict[str, Any] | None = None) -> bool:
153
+ """True when a parameter named ``name`` with ``schema`` likely carries a secret."""
154
+ schema = schema if isinstance(schema, dict) else {}
155
+ if schema.get("format") == "password" or schema.get("writeOnly") is True:
156
+ return True
157
+ tokens = _tokens(name)
158
+ hits = {t for t in tokens if t in _SECRET_TOKENS}
159
+ if hits == {"token"} and any(t in _TOKEN_EXEMPT for t in tokens):
160
+ hits = set()
161
+ if hits:
162
+ return True
163
+ return any(pair in _SECRET_PAIRS for pair in zip(tokens, tokens[1:], strict=False))
164
+
165
+
166
+ def analyze_operation(input_schema: dict[str, Any]) -> list[Finding]:
167
+ """Findings for one operation's IR input schema, in parameter order (info included)."""
168
+ props = input_schema.get("properties") if isinstance(input_schema, dict) else None
169
+ if not isinstance(props, dict):
170
+ return []
171
+ findings: list[Finding] = []
172
+ for name, prop in props.items():
173
+ if not isinstance(name, str) or not isinstance(prop, dict):
174
+ continue
175
+ rule = _RULES.get(str(prop.get(IN_KEY)))
176
+ if rule is None or not is_sensitive(name, prop):
177
+ continue
178
+ code, severity, message, remediation, _ = rule
179
+ findings.append(
180
+ Finding(code, severity, name, str(prop[IN_KEY]), message.format(p=name), remediation)
181
+ )
182
+ return findings
183
+
184
+
185
+ def is_blocking(findings: list[Finding]) -> bool:
186
+ """True when any finding is medium or higher: the operation starts unticked."""
187
+ return any(f.severity in BLOCKING_SEVERITIES for f in findings)
188
+
189
+
190
+ def visible(findings: list[Finding]) -> list[Finding]:
191
+ """Findings worth showing a person (info-level ones are only for redaction)."""
192
+ return [f for f in findings if f.severity != "info"]
193
+
194
+
195
+ def operation_findings(
196
+ spec: dict[str, Any], *, include_info: bool = False
197
+ ) -> dict[str, list[dict[str, Any]]]:
198
+ """Findings per operation id (the API catalog ids), for an OpenAPI/Swagger document.
199
+
200
+ Operations without findings are omitted. Never raises on a malformed document;
201
+ the API validates documents before it gets here.
202
+ """
203
+ try:
204
+ ir = openapi_to_ir(spec if isinstance(spec, dict) else {})
205
+ except (TypeError, ValueError, AttributeError, KeyError):
206
+ return {}
207
+ out: dict[str, list[dict[str, Any]]] = {}
208
+ for op in ir.operations:
209
+ found = analyze_operation(op.input_schema)
210
+ if not include_info:
211
+ found = visible(found)
212
+ if found:
213
+ out[op.id] = [f.to_dict() for f in found]
214
+ return out