MCPcopy
hub / github.com/msgspec/msgspec / schema_components

Function schema_components

src/msgspec/_json_schema.py:64–116  ·  view source on GitHub ↗

Generate JSON Schemas for one or more types. Any schemas for (potentially) shared components are extracted and returned in a separate ``components`` dict. Parameters ---------- types : Iterable[type] An iterable of one or more types to generate schemas for. schema_h

(
    types: Iterable[Any],
    *,
    schema_hook: Optional[Callable[[type], dict[str, Any]]] = None,
    ref_template: str = _REF_TEMPLATE,
)

Source from the content-addressed store, hash-verified

62
63
64def schema_components(
65 types: Iterable[Any],
66 *,
67 schema_hook: Optional[Callable[[type], dict[str, Any]]] = None,
68 ref_template: str = _REF_TEMPLATE,
69) -> tuple[tuple[dict[str, Any], ...], dict[str, Any]]:
70 """Generate JSON Schemas for one or more types.
71
72 Any schemas for (potentially) shared components are extracted and returned
73 in a separate ``components`` dict.
74
75 Parameters
76 ----------
77 types : Iterable[type]
78 An iterable of one or more types to generate schemas for.
79 schema_hook : callable, optional
80 An optional callback to use for generating JSON schemas of custom
81 types. Will be called with the custom type, and should return a dict
82 representation of the JSON schema for that type.
83 ref_template : str, optional
84 A template to use when generating ``"$ref"`` fields. This template is
85 formatted with the type name as ``template.format(name=name)``. This
86 can be useful if you intend to store the ``components`` mapping
87 somewhere other than a top-level ``"$defs"`` field. For example, you
88 might use ``ref_template="#/components/{name}"`` if generating an
89 OpenAPI schema.
90
91 Returns
92 -------
93 schemas : tuple[dict]
94 A tuple of JSON Schemas, one for each type in ``types``.
95 components : dict
96 A mapping of name to schema for any shared components used by
97 ``schemas``.
98
99 See Also
100 --------
101 schema
102 """
103 type_infos = mi.multi_type_info(types)
104
105 component_types = _collect_component_types(type_infos)
106
107 name_map = _build_name_map(component_types)
108
109 gen = _SchemaGenerator(name_map, schema_hook, ref_template)
110
111 schemas = tuple(gen.to_schema(t) for t in type_infos)
112
113 components = {
114 name_map[cls]: gen.to_schema(t, False) for cls, t in component_types.items()
115 }
116 return schemas, components
117
118
119def _collect_component_types(type_infos: Iterable[mi.Type]) -> dict[Any, mi.Type]:

Callers 1

schemaFunction · 0.85

Calls 4

_collect_component_typesFunction · 0.85
_build_name_mapFunction · 0.85
_SchemaGeneratorClass · 0.85
to_schemaMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…