toolpreflight 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,429 @@
1
+ """Cross-provider LLM JSON-Schema compatibility checking and normalization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ from typing import Any
7
+
8
+ from toolpreflight.models import Finding, ProviderSummary, Severity, ToolSpec
9
+
10
+ SUPPORTED_PROVIDERS = ("openai_strict", "gemini", "anthropic", "local_gbnf")
11
+
12
+ _OPENAI_STRICT_UNSUPPORTED_KEYWORDS = {
13
+ "minimum",
14
+ "maximum",
15
+ "exclusiveMinimum",
16
+ "exclusiveMaximum",
17
+ "multipleOf",
18
+ "minLength",
19
+ "maxLength",
20
+ "pattern",
21
+ "format",
22
+ "minItems",
23
+ "maxItems",
24
+ "uniqueItems",
25
+ "default",
26
+ "oneOf",
27
+ "not",
28
+ "patternProperties",
29
+ "unevaluatedProperties",
30
+ "dependentRequired",
31
+ "dependentSchemas",
32
+ }
33
+
34
+ _GEMINI_UNSUPPORTED_KEYWORDS = {
35
+ "additionalProperties",
36
+ "patternProperties",
37
+ "const",
38
+ "not",
39
+ "dependentRequired",
40
+ "dependentSchemas",
41
+ "unevaluatedProperties",
42
+ }
43
+
44
+ _LOCAL_GBNF_UNSUPPORTED_KEYWORDS = {
45
+ "patternProperties",
46
+ "dependentRequired",
47
+ "dependentSchemas",
48
+ "unevaluatedProperties",
49
+ "not",
50
+ }
51
+
52
+
53
+ def check_compatibility(
54
+ tools: list[ToolSpec], providers: list[str]
55
+ ) -> tuple[list[Finding], list[ProviderSummary]]:
56
+ """Validate all tools against each requested LLM provider profile."""
57
+ all_findings: list[Finding] = []
58
+ summaries: list[ProviderSummary] = []
59
+
60
+ for provider in providers:
61
+ if provider not in SUPPORTED_PROVIDERS:
62
+ raise ValueError(
63
+ f"Unknown provider '{provider}'. Choose from: {', '.join(SUPPORTED_PROVIDERS)}"
64
+ )
65
+ provider_findings: list[Finding] = []
66
+ for tool in tools:
67
+ provider_findings.extend(
68
+ _check_tool_for_provider(tool, provider)
69
+ )
70
+ err_count = sum(
71
+ 1 for f in provider_findings if f.severity == Severity.ERROR
72
+ )
73
+ warn_count = sum(
74
+ 1 for f in provider_findings if f.severity == Severity.WARNING
75
+ )
76
+ summaries.append(
77
+ ProviderSummary(
78
+ provider=provider,
79
+ compatible=(err_count == 0),
80
+ error_count=err_count,
81
+ warning_count=warn_count,
82
+ )
83
+ )
84
+ all_findings.extend(provider_findings)
85
+
86
+ return all_findings, summaries
87
+
88
+
89
+ def _check_tool_for_provider(tool: ToolSpec, provider: str) -> list[Finding]:
90
+ schema = tool.input_schema
91
+ if not isinstance(schema, dict) or not schema:
92
+ return []
93
+ findings: list[Finding] = []
94
+ _walk_provider_node(
95
+ tool_name=tool.name or "<unnamed>",
96
+ node=schema,
97
+ path="$.inputSchema",
98
+ provider=provider,
99
+ findings=findings,
100
+ )
101
+ return findings
102
+
103
+
104
+ def _walk_provider_node(
105
+ *,
106
+ tool_name: str,
107
+ node: Any,
108
+ path: str,
109
+ provider: str,
110
+ findings: list[Finding],
111
+ ) -> None:
112
+ if not isinstance(node, dict):
113
+ return
114
+
115
+ if provider == "openai_strict":
116
+ _check_openai_strict_node(tool_name, node, path, findings)
117
+ elif provider == "gemini":
118
+ _check_gemini_node(tool_name, node, path, findings)
119
+ elif provider == "anthropic":
120
+ _check_anthropic_node(tool_name, node, path, findings)
121
+ elif provider == "local_gbnf":
122
+ _check_local_gbnf_node(tool_name, node, path, findings)
123
+
124
+ props = node.get("properties")
125
+ if isinstance(props, dict):
126
+ for prop_name, prop_schema in props.items():
127
+ _walk_provider_node(
128
+ tool_name=tool_name,
129
+ node=prop_schema,
130
+ path=f"{path}.properties.{prop_name}",
131
+ provider=provider,
132
+ findings=findings,
133
+ )
134
+
135
+ if isinstance(node.get("items"), dict):
136
+ _walk_provider_node(
137
+ tool_name=tool_name,
138
+ node=node["items"],
139
+ path=f"{path}.items",
140
+ provider=provider,
141
+ findings=findings,
142
+ )
143
+
144
+ for key in ("$defs", "definitions"):
145
+ defs = node.get(key)
146
+ if isinstance(defs, dict):
147
+ for def_name, def_schema in defs.items():
148
+ _walk_provider_node(
149
+ tool_name=tool_name,
150
+ node=def_schema,
151
+ path=f"{path}.{key}.{def_name}",
152
+ provider=provider,
153
+ findings=findings,
154
+ )
155
+
156
+ for combiner in ("anyOf", "oneOf", "allOf"):
157
+ variants = node.get(combiner)
158
+ if isinstance(variants, list):
159
+ for idx, variant in enumerate(variants):
160
+ _walk_provider_node(
161
+ tool_name=tool_name,
162
+ node=variant,
163
+ path=f"{path}.{combiner}[{idx}]",
164
+ provider=provider,
165
+ findings=findings,
166
+ )
167
+
168
+
169
+ def _check_openai_strict_node(
170
+ tool_name: str, node: dict[str, Any], path: str, findings: list[Finding]
171
+ ) -> None:
172
+ if node.get("type") == "object" or "properties" in node:
173
+ if node.get("additionalProperties") is not False:
174
+ findings.append(
175
+ Finding(
176
+ code="OAI001",
177
+ severity=Severity.ERROR,
178
+ tool_name=tool_name,
179
+ provider="openai_strict",
180
+ message="OpenAI strict mode requires 'additionalProperties: false' on every object.",
181
+ json_path=path,
182
+ hint="Set additionalProperties=false or run `toolpreflight fix --target openai_strict`.",
183
+ )
184
+ )
185
+ props = node.get("properties")
186
+ if isinstance(props, dict) and props:
187
+ req = set(node.get("required") or [])
188
+ missing = [k for k in props if k not in req]
189
+ if missing:
190
+ findings.append(
191
+ Finding(
192
+ code="OAI002",
193
+ severity=Severity.ERROR,
194
+ tool_name=tool_name,
195
+ provider="openai_strict",
196
+ message=(
197
+ "OpenAI strict mode requires all properties in 'required' "
198
+ f"(missing: {', '.join(missing)})."
199
+ ),
200
+ json_path=f"{path}.required",
201
+ hint="Include every property in 'required' (use nullable types for optional fields).",
202
+ )
203
+ )
204
+
205
+ for kw in sorted(_OPENAI_STRICT_UNSUPPORTED_KEYWORDS):
206
+ if kw in node:
207
+ sev = Severity.ERROR if kw in ("oneOf", "not", "patternProperties") else Severity.WARNING
208
+ findings.append(
209
+ Finding(
210
+ code="OAI003",
211
+ severity=sev,
212
+ tool_name=tool_name,
213
+ provider="openai_strict",
214
+ message=f"Keyword '{kw}' is unsupported or stripped in OpenAI strict schemas.",
215
+ json_path=f"{path}.{kw}",
216
+ hint="Move numeric/string constraints into the property description.",
217
+ )
218
+ )
219
+
220
+
221
+ def _check_gemini_node(
222
+ tool_name: str, node: dict[str, Any], path: str, findings: list[Finding]
223
+ ) -> None:
224
+ if "$ref" in node or "$defs" in node or "definitions" in node:
225
+ findings.append(
226
+ Finding(
227
+ code="GEM001",
228
+ severity=Severity.ERROR,
229
+ tool_name=tool_name,
230
+ provider="gemini",
231
+ message="Gemini schemas commonly reject '$ref' / '$defs' references.",
232
+ json_path=path,
233
+ hint="Inline referenced sub-schemas with `toolpreflight fix --target gemini`.",
234
+ )
235
+ )
236
+ for kw in sorted(_GEMINI_UNSUPPORTED_KEYWORDS):
237
+ if kw in node:
238
+ findings.append(
239
+ Finding(
240
+ code="GEM002",
241
+ severity=Severity.ERROR if kw in ("additionalProperties", "const", "not") else Severity.WARNING,
242
+ tool_name=tool_name,
243
+ provider="gemini",
244
+ message=f"Keyword '{kw}' is not supported by Gemini function declarations.",
245
+ json_path=f"{path}.{kw}",
246
+ hint=f"Remove '{kw}' (or convert 'const' to single-value 'enum').",
247
+ )
248
+ )
249
+
250
+
251
+ def _check_anthropic_node(
252
+ tool_name: str, node: dict[str, Any], path: str, findings: list[Finding]
253
+ ) -> None:
254
+ for kw in ("not", "dependentRequired", "dependentSchemas", "unevaluatedProperties"):
255
+ if kw in node:
256
+ findings.append(
257
+ Finding(
258
+ code="ANT001",
259
+ severity=Severity.WARNING,
260
+ tool_name=tool_name,
261
+ provider="anthropic",
262
+ message=f"Keyword '{kw}' may be rejected or ignored by Anthropic tool input_schema.",
263
+ json_path=f"{path}.{kw}",
264
+ hint="Simplify schema combinators to standard properties/required/anyOf.",
265
+ )
266
+ )
267
+
268
+
269
+ def _check_local_gbnf_node(
270
+ tool_name: str, node: dict[str, Any], path: str, findings: list[Finding]
271
+ ) -> None:
272
+ for kw in sorted(_LOCAL_GBNF_UNSUPPORTED_KEYWORDS):
273
+ if kw in node:
274
+ findings.append(
275
+ Finding(
276
+ code="LOC001",
277
+ severity=Severity.WARNING,
278
+ tool_name=tool_name,
279
+ provider="local_gbnf",
280
+ message=f"Keyword '{kw}' frequently fails in local grammar (GBNF/vLLM) compilers.",
281
+ json_path=f"{path}.{kw}",
282
+ hint="Keep local-model tool schemas flat with explicit types and enums.",
283
+ )
284
+ )
285
+
286
+
287
+ def normalize_schema(
288
+ schema: dict[str, Any],
289
+ *,
290
+ target: str = "openai_strict",
291
+ preserve_constraints: bool = True,
292
+ ) -> dict[str, Any]:
293
+ """Normalize a JSON Schema for a target LLM provider while preserving intent."""
294
+ if target not in SUPPORTED_PROVIDERS:
295
+ raise ValueError(
296
+ f"Unknown target '{target}'. Choose from: {', '.join(SUPPORTED_PROVIDERS)}"
297
+ )
298
+
299
+ cloned = copy.deepcopy(schema)
300
+ defs: dict[str, Any] = {}
301
+ for def_key in ("$defs", "definitions"):
302
+ if isinstance(cloned.get(def_key), dict):
303
+ defs.update(cloned.pop(def_key))
304
+
305
+ normalized = _normalize_node(
306
+ cloned,
307
+ defs=defs,
308
+ target=target,
309
+ preserve_constraints=preserve_constraints,
310
+ visited_refs=set(),
311
+ )
312
+ return normalized
313
+
314
+
315
+ def _normalize_node(
316
+ node: Any,
317
+ *,
318
+ defs: dict[str, Any],
319
+ target: str,
320
+ preserve_constraints: bool,
321
+ visited_refs: set[str],
322
+ ) -> Any:
323
+ if not isinstance(node, dict):
324
+ return node
325
+
326
+ # Inline $ref if pointing to local $defs/definitions
327
+ ref = node.get("$ref")
328
+ if isinstance(ref, str) and (ref.startswith("#/$defs/") or ref.startswith("#/definitions/")):
329
+ ref_name = ref.split("/")[-1]
330
+ if ref_name in defs and ref_name not in visited_refs:
331
+ merged = copy.deepcopy(defs[ref_name])
332
+ for k, v in node.items():
333
+ if k != "$ref":
334
+ merged.setdefault(k, v)
335
+ return _normalize_node(
336
+ merged,
337
+ defs=defs,
338
+ target=target,
339
+ preserve_constraints=preserve_constraints,
340
+ visited_refs=visited_refs | {ref_name},
341
+ )
342
+
343
+ if target == "gemini" and "const" in node:
344
+ const_val = node.pop("const")
345
+ node["enum"] = [const_val]
346
+
347
+ strip_set = (
348
+ _OPENAI_STRICT_UNSUPPORTED_KEYWORDS
349
+ if target == "openai_strict"
350
+ else _GEMINI_UNSUPPORTED_KEYWORDS
351
+ if target == "gemini"
352
+ else _LOCAL_GBNF_UNSUPPORTED_KEYWORDS
353
+ if target == "local_gbnf"
354
+ else {"not", "dependentRequired", "dependentSchemas", "unevaluatedProperties"}
355
+ )
356
+
357
+ preserved_notes: list[str] = []
358
+ for kw in list(node.keys()):
359
+ if kw in strip_set:
360
+ val = node.pop(kw)
361
+ if preserve_constraints and kw not in ("additionalProperties", "not"):
362
+ preserved_notes.append(f"{kw}={val}")
363
+
364
+ if preserved_notes:
365
+ existing_desc = str(node.get("description") or "").strip()
366
+ note_str = f"[constraints: {', '.join(preserved_notes)}]"
367
+ node["description"] = f"{existing_desc} {note_str}".strip()
368
+
369
+ if isinstance(node.get("properties"), dict):
370
+ node["properties"] = {
371
+ k: _normalize_node(
372
+ v,
373
+ defs=defs,
374
+ target=target,
375
+ preserve_constraints=preserve_constraints,
376
+ visited_refs=visited_refs,
377
+ )
378
+ for k, v in node["properties"].items()
379
+ }
380
+
381
+ if target == "openai_strict" and (node.get("type") == "object" or "properties" in node):
382
+ node["additionalProperties"] = False
383
+ props = node.get("properties")
384
+ if isinstance(props, dict):
385
+ existing_req = set(node.get("required") or [])
386
+ for prop_name, prop_val in props.items():
387
+ if prop_name not in existing_req and isinstance(prop_val, dict):
388
+ _make_nullable(prop_val)
389
+ node["required"] = list(props.keys())
390
+
391
+ if isinstance(node.get("items"), dict):
392
+ node["items"] = _normalize_node(
393
+ node["items"],
394
+ defs=defs,
395
+ target=target,
396
+ preserve_constraints=preserve_constraints,
397
+ visited_refs=visited_refs,
398
+ )
399
+
400
+ for combiner in ("anyOf", "oneOf", "allOf"):
401
+ if isinstance(node.get(combiner), list):
402
+ node[combiner] = [
403
+ _normalize_node(
404
+ item,
405
+ defs=defs,
406
+ target=target,
407
+ preserve_constraints=preserve_constraints,
408
+ visited_refs=visited_refs,
409
+ )
410
+ for item in node[combiner]
411
+ ]
412
+
413
+ return node
414
+
415
+
416
+ def _make_nullable(prop_schema: dict[str, Any]) -> None:
417
+ """Ensure optional properties accept null when promoted to required in OpenAI strict mode."""
418
+ if "anyOf" in prop_schema:
419
+ variants = prop_schema["anyOf"]
420
+ if isinstance(variants, list) and not any(
421
+ isinstance(v, dict) and v.get("type") == "null" for v in variants
422
+ ):
423
+ variants.append({"type": "null"})
424
+ return
425
+ prop_type = prop_schema.get("type")
426
+ if isinstance(prop_type, str) and prop_type != "null":
427
+ prop_schema["type"] = [prop_type, "null"]
428
+ elif isinstance(prop_type, list) and "null" not in prop_type:
429
+ prop_type.append("null")
@@ -0,0 +1,262 @@
1
+ """Load and normalize tool specifications from JSON manifests or Python files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ import inspect
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Annotated, Any, get_args, get_origin, get_type_hints
11
+
12
+ from toolpreflight.models import ToolSpec
13
+
14
+
15
+ def parse_tool_payload(payload: Any) -> list[ToolSpec]:
16
+ """Normalize MCP, OpenAI, Anthropic, or Gemini JSON structures into ToolSpecs."""
17
+ if isinstance(payload, dict):
18
+ if "result" in payload and isinstance(payload["result"], dict):
19
+ payload = payload["result"]
20
+ if "tools" in payload and isinstance(payload["tools"], list):
21
+ return [_parse_single_tool(item) for item in payload["tools"]]
22
+ if "functionDeclarations" in payload and isinstance(
23
+ payload["functionDeclarations"], list
24
+ ):
25
+ return [
26
+ _parse_gemini_declaration(item)
27
+ for item in payload["functionDeclarations"]
28
+ ]
29
+ # Single tool object
30
+ return [_parse_single_tool(payload)]
31
+
32
+ if isinstance(payload, list):
33
+ tools: list[ToolSpec] = []
34
+ for item in payload:
35
+ if isinstance(item, dict) and "functionDeclarations" in item:
36
+ for decl in item["functionDeclarations"]:
37
+ tools.append(_parse_gemini_declaration(decl))
38
+ else:
39
+ tools.append(_parse_single_tool(item))
40
+ return tools
41
+
42
+ raise ValueError(f"Unsupported tool manifest root type: {type(payload).__name__}")
43
+
44
+
45
+ def _parse_single_tool(raw: Any) -> ToolSpec:
46
+ if not isinstance(raw, dict):
47
+ raise ValueError(f"Tool entry must be an object, got {type(raw).__name__}")
48
+
49
+ # OpenAI tool wrapper: {"type": "function", "function": {...}}
50
+ if raw.get("type") == "function" and isinstance(raw.get("function"), dict):
51
+ fn = raw["function"]
52
+ return ToolSpec(
53
+ name=str(fn.get("name", "")),
54
+ description=str(fn.get("description") or ""),
55
+ input_schema=_ensure_dict(fn.get("parameters")),
56
+ source_format="openai",
57
+ )
58
+
59
+ # Anthropic tool object: {"name": ..., "description": ..., "input_schema": {...}}
60
+ if "input_schema" in raw and "inputSchema" not in raw:
61
+ return ToolSpec(
62
+ name=str(raw.get("name", "")),
63
+ description=str(raw.get("description") or ""),
64
+ input_schema=_ensure_dict(raw.get("input_schema")),
65
+ annotations=_ensure_dict(raw.get("annotations")),
66
+ source_format="anthropic",
67
+ )
68
+
69
+ # Gemini declaration shape if passed directly
70
+ if "parametersJsonSchema" in raw or (
71
+ "parameters" in raw and "inputSchema" not in raw
72
+ ):
73
+ return _parse_gemini_declaration(raw)
74
+
75
+ # Standard MCP tool shape
76
+ return ToolSpec(
77
+ name=str(raw.get("name", "")),
78
+ description=str(raw.get("description") or ""),
79
+ input_schema=_ensure_dict(raw.get("inputSchema")),
80
+ annotations=_ensure_dict(raw.get("annotations")),
81
+ source_format="mcp",
82
+ )
83
+
84
+
85
+ def _parse_gemini_declaration(raw: dict[str, Any]) -> ToolSpec:
86
+ schema = raw.get("parametersJsonSchema")
87
+ if schema is None:
88
+ schema = raw.get("parameters")
89
+ return ToolSpec(
90
+ name=str(raw.get("name", "")),
91
+ description=str(raw.get("description") or ""),
92
+ input_schema=_ensure_dict(schema),
93
+ source_format="gemini",
94
+ )
95
+
96
+
97
+ def _ensure_dict(value: Any) -> dict[str, Any]:
98
+ return value if isinstance(value, dict) else {}
99
+
100
+
101
+ def _python_type_to_schema(annotation: Any) -> dict[str, Any]:
102
+ """Convert common Python type annotations to JSON Schema without heavy deps."""
103
+ if annotation is inspect.Parameter.empty or annotation is Any:
104
+ return {}
105
+ if annotation is str:
106
+ return {"type": "string"}
107
+ if annotation is int:
108
+ return {"type": "integer"}
109
+ if annotation is float:
110
+ return {"type": "number"}
111
+ if annotation is bool:
112
+ return {"type": "boolean"}
113
+ if annotation is type(None):
114
+ return {"type": "null"}
115
+
116
+ # Pydantic BaseModel support if installed
117
+ if hasattr(annotation, "model_json_schema"):
118
+ return annotation.model_json_schema()
119
+
120
+ origin = get_origin(annotation)
121
+ args = get_args(annotation)
122
+
123
+ # Unwrap typing.Annotated[T, Field(...)] and preserve description/constraints
124
+ if origin is Annotated and args:
125
+ base_schema = _python_type_to_schema(args[0])
126
+ for meta in args[1:]:
127
+ _apply_field_metadata(base_schema, meta)
128
+ return base_schema
129
+
130
+ if origin in (list, tuple, set):
131
+ item_schema = _python_type_to_schema(args[0]) if args else {}
132
+ return {"type": "array", "items": item_schema} if item_schema else {"type": "array"}
133
+
134
+ if origin is dict:
135
+ return {"type": "object"}
136
+
137
+ if str(origin) in ("typing.Literal", "<class 'typing.Literal'>") or getattr(
138
+ origin, "__name__", ""
139
+ ) == "Literal":
140
+ return {"enum": list(args)}
141
+
142
+ # Union / Optional (typing.Union or types.UnionType on 3.10+)
143
+ if origin is not None and args:
144
+ return {"anyOf": [_python_type_to_schema(arg) for arg in args]}
145
+
146
+ return {}
147
+
148
+
149
+ def _apply_field_metadata(schema: dict[str, Any], meta: Any) -> None:
150
+ """Extract description and numeric/string constraints from Pydantic FieldInfo or metadata."""
151
+ desc = getattr(meta, "description", None)
152
+ if isinstance(desc, str) and desc.strip():
153
+ schema["description"] = desc.strip()
154
+
155
+ # Direct attributes (e.g. custom metadata) and Pydantic v2 `.metadata` list
156
+ sources = [meta, *list(getattr(meta, "metadata", []) or [])]
157
+ attr_map = {
158
+ "ge": "minimum",
159
+ "le": "maximum",
160
+ "gt": "exclusiveMinimum",
161
+ "lt": "exclusiveMaximum",
162
+ "min_length": "minLength",
163
+ "max_length": "maxLength",
164
+ "pattern": "pattern",
165
+ }
166
+ for src in sources:
167
+ for attr, json_kw in attr_map.items():
168
+ val = getattr(src, attr, None)
169
+ if val is not None:
170
+ schema[json_kw] = val
171
+
172
+
173
+ def _callable_to_tool_spec(name: str, fn: Any) -> ToolSpec:
174
+ sig = inspect.signature(fn)
175
+ try:
176
+ hints = get_type_hints(fn, include_extras=True)
177
+ except Exception:
178
+ hints = {}
179
+
180
+ properties: dict[str, Any] = {}
181
+ required: list[str] = []
182
+ for param_name, param in sig.parameters.items():
183
+ if param_name in ("self", "cls", "ctx", "context"):
184
+ continue
185
+ if param.kind in (
186
+ inspect.Parameter.VAR_POSITIONAL,
187
+ inspect.Parameter.VAR_KEYWORD,
188
+ ):
189
+ continue
190
+ ann = hints.get(param_name, param.annotation)
191
+ prop_schema = _python_type_to_schema(ann)
192
+ if param.default is not inspect.Parameter.empty:
193
+ if param.default is not None:
194
+ prop_schema["default"] = param.default
195
+ else:
196
+ required.append(param_name)
197
+ properties[param_name] = prop_schema
198
+
199
+ schema: dict[str, Any] = {
200
+ "type": "object",
201
+ "properties": properties,
202
+ }
203
+ if required:
204
+ schema["required"] = required
205
+
206
+ return ToolSpec(
207
+ name=name,
208
+ description=inspect.getdoc(fn) or "",
209
+ input_schema=schema,
210
+ source_format="python",
211
+ )
212
+
213
+
214
+ def load_tools_from_python_file(path: Path) -> list[ToolSpec]:
215
+ """Import a Python module and extract top-level functions or Pydantic models."""
216
+ module_name = f"_toolpreflight_user_{path.stem}"
217
+ spec = importlib.util.spec_from_file_location(module_name, path)
218
+ if spec is None or spec.loader is None:
219
+ raise ValueError(f"Could not load Python module from {path}")
220
+
221
+ module = importlib.util.module_from_spec(spec)
222
+ sys.modules[module_name] = module
223
+ try:
224
+ spec.loader.exec_module(module)
225
+ finally:
226
+ sys.modules.pop(module_name, None)
227
+
228
+ tools: list[ToolSpec] = []
229
+ for attr_name, obj in inspect.getmembers(module):
230
+ if attr_name.startswith("_"):
231
+ continue
232
+ if getattr(obj, "__module__", None) != module_name:
233
+ continue
234
+ if inspect.isfunction(obj):
235
+ tools.append(_callable_to_tool_spec(attr_name, obj))
236
+ elif inspect.isclass(obj) and hasattr(obj, "model_json_schema"):
237
+ tools.append(
238
+ ToolSpec(
239
+ name=attr_name,
240
+ description=inspect.getdoc(obj) or "",
241
+ input_schema=obj.model_json_schema(),
242
+ source_format="pydantic",
243
+ )
244
+ )
245
+ return tools
246
+
247
+
248
+ def load_tools(source: str) -> list[ToolSpec]:
249
+ """Load ToolSpecs from '-', a JSON file path, or a Python file path."""
250
+ if source == "-":
251
+ raw = sys.stdin.read()
252
+ return parse_tool_payload(json.loads(raw))
253
+
254
+ path = Path(source)
255
+ if not path.exists():
256
+ raise FileNotFoundError(f"Tool source not found: {source}")
257
+
258
+ if path.suffix.lower() == ".py":
259
+ return load_tools_from_python_file(path)
260
+
261
+ content = path.read_text(encoding="utf-8")
262
+ return parse_tool_payload(json.loads(content))