incur-cli 0.10.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.
- incur/__init__.py +62 -0
- incur/_cli.py +2139 -0
- incur/_command.py +426 -0
- incur/_completions.py +170 -0
- incur/_errors.py +234 -0
- incur/_filter.py +173 -0
- incur/_formatter.py +112 -0
- incur/_gateway.py +173 -0
- incur/_help.py +260 -0
- incur/_http.py +389 -0
- incur/_js.py +467 -0
- incur/_jsonschema.py +320 -0
- incur/_mcp.py +872 -0
- incur/_mcpsource.py +226 -0
- incur/_model.py +348 -0
- incur/_openapi.py +640 -0
- incur/_parser.py +347 -0
- incur/_pm.py +49 -0
- incur/_schema.py +555 -0
- incur/_serve_http.py +236 -0
- incur/_skill.py +355 -0
- incur/_sync.py +403 -0
- incur/_syncmcp.py +188 -0
- incur/_tokens.py +130 -0
- incur/_toon.py +202 -0
- incur/_tree.py +273 -0
- incur/_update.py +373 -0
- incur/_yaml.py +651 -0
- incur/py.typed +0 -0
- incur_cli-0.10.0.dist-info/METADATA +376 -0
- incur_cli-0.10.0.dist-info/RECORD +32 -0
- incur_cli-0.10.0.dist-info/WHEEL +4 -0
incur/_mcpsource.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Remote MCP servers as command groups: a streamable-HTTP client and generated commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import uuid
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from . import _js
|
|
11
|
+
from ._command import Command, Context, ToolMeta
|
|
12
|
+
from ._errors import Error
|
|
13
|
+
from ._http import FetchHandler, Headers, Request, call, normalize_url, parse_json
|
|
14
|
+
from ._http import fetch as default_fetch
|
|
15
|
+
from ._js import Json
|
|
16
|
+
from ._jsonschema import coerce, convert, describe, optional
|
|
17
|
+
from ._schema import Field, Type, object_type
|
|
18
|
+
from ._tree import Entry
|
|
19
|
+
|
|
20
|
+
PROTOCOL_VERSION = "2025-06-18"
|
|
21
|
+
_CATALOG = frozenset({"search_tools", "get_tool_details", "call_read_tool", "call_write_tool"})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Source:
|
|
25
|
+
"""A remote MCP server reached over streamable HTTP, with its session state."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, url: str, fetch: FetchHandler | None, headers: Mapping[str, str]) -> None:
|
|
28
|
+
self.url = normalize_url(url)
|
|
29
|
+
self.fetch: FetchHandler = fetch or default_fetch
|
|
30
|
+
self.headers = dict(headers)
|
|
31
|
+
self.session: str | None = None
|
|
32
|
+
self.initialized = False
|
|
33
|
+
self.progressive = False
|
|
34
|
+
|
|
35
|
+
async def request(self, method: str, params: Json = None) -> dict[str, Json]:
|
|
36
|
+
"""Sends a JSON-RPC request or notification and returns its result.
|
|
37
|
+
|
|
38
|
+
Raises:
|
|
39
|
+
RuntimeError: When the server answers with an HTTP or JSON-RPC error.
|
|
40
|
+
"""
|
|
41
|
+
notification = method.startswith("notifications/")
|
|
42
|
+
id_ = None if notification else str(uuid.uuid4())
|
|
43
|
+
headers = Headers(self.headers)
|
|
44
|
+
headers.set("content-type", "application/json")
|
|
45
|
+
headers.set("accept", "application/json, text/event-stream")
|
|
46
|
+
if self.session:
|
|
47
|
+
headers.set("mcp-session-id", self.session)
|
|
48
|
+
if self.initialized:
|
|
49
|
+
headers.set("mcp-protocol-version", PROTOCOL_VERSION)
|
|
50
|
+
message: dict[str, Json] = {"jsonrpc": "2.0"}
|
|
51
|
+
if id_ is not None:
|
|
52
|
+
message["id"] = id_
|
|
53
|
+
message["method"] = method
|
|
54
|
+
if params is not None:
|
|
55
|
+
message["params"] = params
|
|
56
|
+
body = _js.stringify(message)
|
|
57
|
+
response = await call(
|
|
58
|
+
self.fetch, Request(self.url, method="POST", headers=headers, body=body)
|
|
59
|
+
)
|
|
60
|
+
session = response.headers.get("mcp-session-id")
|
|
61
|
+
if session:
|
|
62
|
+
self.session = session
|
|
63
|
+
if not response.ok:
|
|
64
|
+
raise RuntimeError(f"MCP HTTP {response.status}")
|
|
65
|
+
if notification and response.status == 202:
|
|
66
|
+
return {}
|
|
67
|
+
text = await response.text()
|
|
68
|
+
if not text:
|
|
69
|
+
return {}
|
|
70
|
+
if "text/event-stream" in (response.headers.get("content-type") or ""):
|
|
71
|
+
reply = _sse(text, id_)
|
|
72
|
+
else:
|
|
73
|
+
reply = _js.as_object(parse_json(text))
|
|
74
|
+
error = reply.get("error")
|
|
75
|
+
if isinstance(error, dict):
|
|
76
|
+
message_text = error.get("message")
|
|
77
|
+
raise RuntimeError(
|
|
78
|
+
message_text if isinstance(message_text, str) else "MCP request failed"
|
|
79
|
+
)
|
|
80
|
+
result = reply.get("result")
|
|
81
|
+
return result if isinstance(result, dict) else {}
|
|
82
|
+
|
|
83
|
+
async def call(self, name: str, arguments: dict[str, Json]) -> Json:
|
|
84
|
+
"""Calls a tool of the server's catalog, failing on tool errors."""
|
|
85
|
+
result = await self.request("tools/call", {"name": name, "arguments": arguments})
|
|
86
|
+
if result.get("isError"):
|
|
87
|
+
raise RuntimeError(_text(result) or f"MCP tool failed: {name}")
|
|
88
|
+
return _value(result)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _sse(text: str, id_: str | None) -> dict[str, Json]:
|
|
92
|
+
"""Finds the JSON-RPC message answering `id_` in a server-sent event stream."""
|
|
93
|
+
for event in re.split(r"\r?\n\r?\n", text):
|
|
94
|
+
lines = [
|
|
95
|
+
line[5:].lstrip() for line in re.split(r"\r?\n", event) if line.startswith("data:")
|
|
96
|
+
]
|
|
97
|
+
data = "\n".join(lines)
|
|
98
|
+
if not data:
|
|
99
|
+
continue
|
|
100
|
+
message = _js.as_object(parse_json(data))
|
|
101
|
+
if id_ is None or message.get("id") == id_:
|
|
102
|
+
return message
|
|
103
|
+
raise RuntimeError("MCP SSE response did not include the matching JSON-RPC message")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _text(result: dict[str, Json]) -> str:
|
|
107
|
+
content = result.get("content")
|
|
108
|
+
items = content if isinstance(content, list) else []
|
|
109
|
+
texts = [
|
|
110
|
+
item.get("text") for item in items if isinstance(item, dict) and item.get("type") == "text"
|
|
111
|
+
]
|
|
112
|
+
return "\n".join(t for t in texts if isinstance(t, str) and t)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _value(result: dict[str, Json]) -> Json:
|
|
116
|
+
"""The value of a tool result: structured content, or its text parsed as JSON."""
|
|
117
|
+
if "structuredContent" in result:
|
|
118
|
+
return result["structuredContent"]
|
|
119
|
+
content = result.get("content")
|
|
120
|
+
items = content if isinstance(content, list) else []
|
|
121
|
+
texts: list[Json] = [
|
|
122
|
+
item["text"]
|
|
123
|
+
for item in items
|
|
124
|
+
if isinstance(item, dict)
|
|
125
|
+
and item.get("type") == "text"
|
|
126
|
+
and isinstance(item.get("text"), str)
|
|
127
|
+
]
|
|
128
|
+
if len(texts) == 1:
|
|
129
|
+
text = str(texts[0])
|
|
130
|
+
return _js.parse_json(text) if _js.json_parse_error(text) is None else text
|
|
131
|
+
return texts
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def _tools(source: Source) -> list[dict[str, Json]]:
|
|
135
|
+
"""Initializes the server and lists its tools, paging through a progressive catalog."""
|
|
136
|
+
await source.request(
|
|
137
|
+
"initialize",
|
|
138
|
+
{
|
|
139
|
+
"protocolVersion": PROTOCOL_VERSION,
|
|
140
|
+
"capabilities": {},
|
|
141
|
+
"clientInfo": {"name": "incur", "version": "1.0.0"},
|
|
142
|
+
},
|
|
143
|
+
)
|
|
144
|
+
source.initialized = True
|
|
145
|
+
await source.request("notifications/initialized")
|
|
146
|
+
listed = source.request("tools/list")
|
|
147
|
+
tools = [t for t in _js.as_list((await listed).get("tools") or []) if isinstance(t, dict)]
|
|
148
|
+
names = frozenset(name for t in tools if isinstance(name := t.get("name"), str))
|
|
149
|
+
if len(tools) != 4 or names != _CATALOG:
|
|
150
|
+
return tools
|
|
151
|
+
source.progressive = True
|
|
152
|
+
found: list[dict[str, Json]] = []
|
|
153
|
+
offset: int | None = 0
|
|
154
|
+
while offset is not None:
|
|
155
|
+
search = _js.as_object(
|
|
156
|
+
await source.call("search_tools", {"query": "", "limit": 20, "offset": offset})
|
|
157
|
+
)
|
|
158
|
+
for match in _js.as_list(search.get("tools") or []):
|
|
159
|
+
name = match.get("name") if isinstance(match, dict) else None
|
|
160
|
+
if not name:
|
|
161
|
+
continue
|
|
162
|
+
tool = await source.call("get_tool_details", {"name": name})
|
|
163
|
+
if isinstance(tool, dict) and tool.get("name"):
|
|
164
|
+
found.append(tool)
|
|
165
|
+
nxt = search.get("nextOffset")
|
|
166
|
+
nxt = int(nxt) if isinstance(nxt, (int, float)) and not isinstance(nxt, bool) else None
|
|
167
|
+
if nxt is not None and nxt <= offset:
|
|
168
|
+
raise RuntimeError("MCP tool catalog returned a non-advancing offset")
|
|
169
|
+
offset = nxt
|
|
170
|
+
return found
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _options(schema: dict[str, Json]) -> Type | None:
|
|
174
|
+
"""Options from a tool's input schema: one per property, numbers and booleans coerced."""
|
|
175
|
+
properties = schema.get("properties")
|
|
176
|
+
required = schema.get("required")
|
|
177
|
+
names = set(required) if isinstance(required, list) else set[Json]()
|
|
178
|
+
fields: list[Field] = []
|
|
179
|
+
for key, prop in (properties if isinstance(properties, dict) else {}).items():
|
|
180
|
+
ty = convert(prop)
|
|
181
|
+
if key not in names:
|
|
182
|
+
ty = optional(ty)
|
|
183
|
+
description = prop.get("description") if isinstance(prop, dict) else None
|
|
184
|
+
if isinstance(description, str):
|
|
185
|
+
ty = describe(ty, description)
|
|
186
|
+
fields.append(Field(key, coerce(ty)))
|
|
187
|
+
return object_type(fields) if fields else None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
async def commands(source: Source) -> dict[str, Entry]:
|
|
191
|
+
"""Generates a command per remote tool, calling it through `tools/call`."""
|
|
192
|
+
out: dict[str, Entry] = {}
|
|
193
|
+
for tool in await _tools(source):
|
|
194
|
+
name = str(tool["name"])
|
|
195
|
+
input_schema = tool.get("inputSchema")
|
|
196
|
+
output_schema = tool.get("outputSchema")
|
|
197
|
+
annotations = tool.get("annotations")
|
|
198
|
+
description = tool.get("description")
|
|
199
|
+
out[name] = Command(
|
|
200
|
+
handler=_handler(source, name, annotations),
|
|
201
|
+
description=description if isinstance(description, str) else None,
|
|
202
|
+
options=_options(input_schema) if isinstance(input_schema, dict) else None,
|
|
203
|
+
output=(
|
|
204
|
+
convert(output_schema)
|
|
205
|
+
if isinstance(output_schema, dict) and output_schema.get("type") == "object"
|
|
206
|
+
else None
|
|
207
|
+
),
|
|
208
|
+
mcp=ToolMeta(annotations=annotations) if isinstance(annotations, dict) else None,
|
|
209
|
+
)
|
|
210
|
+
return out
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _handler(source: Source, name: str, annotations: Json) -> Any:
|
|
214
|
+
read_only = isinstance(annotations, dict) and annotations.get("readOnlyHint") is True
|
|
215
|
+
|
|
216
|
+
async def run(c: Context[Any, Any]) -> Json:
|
|
217
|
+
params: dict[str, Json] = {"name": name, "arguments": dict(c.options or {})}
|
|
218
|
+
if source.progressive:
|
|
219
|
+
tool = "call_read_tool" if read_only else "call_write_tool"
|
|
220
|
+
params = {"name": tool, "arguments": params}
|
|
221
|
+
result = await source.request("tools/call", params)
|
|
222
|
+
if result.get("isError"):
|
|
223
|
+
raise Error("MCP_TOOL_ERROR", _text(result))
|
|
224
|
+
return _value(result)
|
|
225
|
+
|
|
226
|
+
return run
|
incur/_model.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""Typed schema classes: `@incur.schema` dataclasses with `incur.field` metadata."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import enum
|
|
7
|
+
import inspect
|
|
8
|
+
import math
|
|
9
|
+
import types
|
|
10
|
+
import typing
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Annotated, Any, Literal, TypeVar, Union, dataclass_transform, overload
|
|
14
|
+
|
|
15
|
+
from . import _js
|
|
16
|
+
from ._errors import Error
|
|
17
|
+
from ._js import Json
|
|
18
|
+
from ._schema import Field, Type, object_type
|
|
19
|
+
|
|
20
|
+
_T = TypeVar("_T")
|
|
21
|
+
|
|
22
|
+
#: Naming rules for `rename_all`, as `serde` spells them.
|
|
23
|
+
RenameRule = Literal[
|
|
24
|
+
"camelCase",
|
|
25
|
+
"kebab-case",
|
|
26
|
+
"lowercase",
|
|
27
|
+
"PascalCase",
|
|
28
|
+
"SCREAMING-KEBAB-CASE",
|
|
29
|
+
"SCREAMING_SNAKE_CASE",
|
|
30
|
+
"snake_case",
|
|
31
|
+
"UPPERCASE",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
_RULES: dict[str, Callable[[list[str]], str]] = {
|
|
35
|
+
"camelCase": lambda w: w[0].lower() + "".join(p.capitalize() for p in w[1:]),
|
|
36
|
+
"kebab-case": lambda w: "-".join(p.lower() for p in w),
|
|
37
|
+
"lowercase": lambda w: "_".join(w).lower(),
|
|
38
|
+
"PascalCase": lambda w: "".join(p.capitalize() for p in w),
|
|
39
|
+
"SCREAMING-KEBAB-CASE": lambda w: "-".join(p.upper() for p in w),
|
|
40
|
+
"SCREAMING_SNAKE_CASE": lambda w: "_".join(p.upper() for p in w),
|
|
41
|
+
"snake_case": "_".join,
|
|
42
|
+
"UPPERCASE": lambda w: "_".join(w).upper(),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
_SCHEMA = "__incur_schema__"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class SchemaError(TypeError):
|
|
49
|
+
"""A schema class, field, or handler declaration that incur cannot describe."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class FieldInfo:
|
|
54
|
+
"""Command-line metadata of a schema field. Create it with `incur.field`."""
|
|
55
|
+
|
|
56
|
+
description: str | None = None
|
|
57
|
+
"""Help text for the field."""
|
|
58
|
+
alias: str | None = None
|
|
59
|
+
"""A single-character short flag."""
|
|
60
|
+
name: str | None = None
|
|
61
|
+
"""The name in input and output, overriding `rename_all`."""
|
|
62
|
+
min: float | None = None
|
|
63
|
+
"""Minimum value, string length, or item count."""
|
|
64
|
+
max: float | None = None
|
|
65
|
+
"""Maximum value, string length, or item count."""
|
|
66
|
+
count: bool = False
|
|
67
|
+
"""Whether the option counts repeated flags."""
|
|
68
|
+
deprecated: bool = False
|
|
69
|
+
"""Whether the option warns when used."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def field(
|
|
73
|
+
description: str | None = None,
|
|
74
|
+
*,
|
|
75
|
+
alias: str | None = None,
|
|
76
|
+
name: str | None = None,
|
|
77
|
+
min: float | None = None,
|
|
78
|
+
max: float | None = None,
|
|
79
|
+
count: bool = False,
|
|
80
|
+
deprecated: bool = False,
|
|
81
|
+
) -> FieldInfo:
|
|
82
|
+
"""Describes a schema field. Use it as `typing.Annotated` metadata.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
description: Help text for the field.
|
|
86
|
+
alias: A single-character short flag, such as `"D"` for `-D`.
|
|
87
|
+
name: The name in input and output, overriding `rename_all`.
|
|
88
|
+
min: Minimum value, string length, or item count.
|
|
89
|
+
max: Maximum value, string length, or item count.
|
|
90
|
+
count: Counts repeated flags (`-vvv`). The field must be a number.
|
|
91
|
+
deprecated: Warns when the option is used.
|
|
92
|
+
"""
|
|
93
|
+
return FieldInfo(description, alias, name, min, max, count, deprecated)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@overload
|
|
97
|
+
def schema(cls: type[_T], /) -> type[_T]: ...
|
|
98
|
+
@overload
|
|
99
|
+
def schema(*, rename_all: RenameRule | None = None) -> Callable[[type[_T]], type[_T]]: ...
|
|
100
|
+
@dataclass_transform(kw_only_default=True, field_specifiers=(dataclasses.field,))
|
|
101
|
+
def schema(
|
|
102
|
+
cls: type[_T] | None = None, /, *, rename_all: RenameRule | None = None
|
|
103
|
+
) -> type[_T] | Callable[[type[_T]], type[_T]]:
|
|
104
|
+
"""Declares a schema class for arguments, options, environment variables, or output.
|
|
105
|
+
|
|
106
|
+
The class becomes a keyword-only dataclass. Each annotated attribute is a field: `str`,
|
|
107
|
+
`bool`, `int`, `float`, `list[T]`, `Literal[...]` of strings, a string `Enum`, `Any`,
|
|
108
|
+
another schema class, or `T | None` for optional fields. Attach `incur.field` metadata with
|
|
109
|
+
`typing.Annotated`, and give defaults as ordinary attribute values.
|
|
110
|
+
|
|
111
|
+
>>> from typing import Annotated
|
|
112
|
+
>>> @schema(rename_all="camelCase")
|
|
113
|
+
... class Options:
|
|
114
|
+
... save_dev: Annotated[bool | None, field("Save as a dev dependency", alias="D")] = None
|
|
115
|
+
>>> Options(save_dev=True)
|
|
116
|
+
Options(save_dev=True)
|
|
117
|
+
|
|
118
|
+
Raises:
|
|
119
|
+
SchemaError: When a field cannot be described.
|
|
120
|
+
"""
|
|
121
|
+
# Annotations may name classes local to the declaring function.
|
|
122
|
+
scope = caller_locals()
|
|
123
|
+
|
|
124
|
+
def wrap(target: type[_T]) -> type[_T]:
|
|
125
|
+
return _declare(target, rename_all, scope)
|
|
126
|
+
|
|
127
|
+
return wrap if cls is None else wrap(cls)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def caller_locals() -> dict[str, Any]:
|
|
131
|
+
"""Returns the local variables of the function calling the caller."""
|
|
132
|
+
frame = inspect.currentframe()
|
|
133
|
+
caller = frame.f_back.f_back if frame and frame.f_back else None
|
|
134
|
+
assert caller is not None, "incur needs Python frames to resolve local annotations"
|
|
135
|
+
return dict(caller.f_locals)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _declare(cls: type[_T], rename_all: str | None, scope: dict[str, Any]) -> type[_T]:
|
|
139
|
+
"""Turns a class into a dataclass and attaches its schema."""
|
|
140
|
+
where = cls.__qualname__
|
|
141
|
+
if rename_all is not None and rename_all not in _RULES:
|
|
142
|
+
raise SchemaError(
|
|
143
|
+
f"{where}: unknown rename_all rule {rename_all!r}; expected one of {', '.join(_RULES)}"
|
|
144
|
+
)
|
|
145
|
+
# Lists are valid JSON defaults; give each instance its own copy.
|
|
146
|
+
annotations = inspect.get_annotations(cls)
|
|
147
|
+
for attr, value in list(vars(cls).items()):
|
|
148
|
+
if isinstance(value, list) and attr in annotations:
|
|
149
|
+
items = typing.cast("list[object]", value)
|
|
150
|
+
setattr(cls, attr, dataclasses.field(default_factory=_copier(items)))
|
|
151
|
+
data_cls = dataclasses.dataclass(kw_only=True)(cls)
|
|
152
|
+
hints = typing.get_type_hints(data_cls, localns=scope, include_extras=True)
|
|
153
|
+
fields: list[Field] = []
|
|
154
|
+
for item in dataclasses.fields(typing.cast("Any", data_cls)):
|
|
155
|
+
label = f"{where}.{item.name}"
|
|
156
|
+
hint, info = _unwrap(hints[item.name], label)
|
|
157
|
+
ty = _describe(hint, label)
|
|
158
|
+
info = info or FieldInfo()
|
|
159
|
+
ty = _apply(ty, info, label)
|
|
160
|
+
default = _default(item)
|
|
161
|
+
if default is not dataclasses.MISSING:
|
|
162
|
+
value = _to_json(default, label)
|
|
163
|
+
if value is not None:
|
|
164
|
+
ty = dataclasses.replace(ty, default=_js.normalize(value))
|
|
165
|
+
if info.name is not None:
|
|
166
|
+
name = info.name
|
|
167
|
+
elif rename_all is not None:
|
|
168
|
+
name = _RULES[rename_all]([w for w in item.name.split("_") if w] or [item.name])
|
|
169
|
+
else:
|
|
170
|
+
name = item.name
|
|
171
|
+
if any(f.name == name for f in fields):
|
|
172
|
+
raise SchemaError(f"{label}: duplicate field name {name!r}")
|
|
173
|
+
if info.alias is not None and any(f.alias == info.alias for f in fields):
|
|
174
|
+
raise SchemaError(f"{label}: duplicate alias {info.alias!r}")
|
|
175
|
+
fields.append(Field(name, ty, info.alias, item.name))
|
|
176
|
+
setattr(data_cls, _SCHEMA, object_type(fields))
|
|
177
|
+
return data_cls
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _copier(value: list[object]) -> Callable[[], list[object]]:
|
|
181
|
+
return lambda: list(value)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _default(item: dataclasses.Field[Any]) -> Any:
|
|
185
|
+
if item.default_factory is not dataclasses.MISSING:
|
|
186
|
+
return item.default_factory()
|
|
187
|
+
return item.default
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _unwrap(hint: Any, label: str) -> tuple[Any, FieldInfo | None]:
|
|
191
|
+
"""Splits `Annotated[T, incur.field(...)]` into `T` and its metadata."""
|
|
192
|
+
if typing.get_origin(hint) is not Annotated:
|
|
193
|
+
return hint, None
|
|
194
|
+
infos = [m for m in hint.__metadata__ if isinstance(m, FieldInfo)]
|
|
195
|
+
if len(infos) > 1:
|
|
196
|
+
raise SchemaError(f"{label}: more than one incur.field()")
|
|
197
|
+
return hint.__origin__, (infos[0] if infos else None)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _describe(hint: Any, label: str) -> Type:
|
|
201
|
+
"""Returns the schema of a type annotation."""
|
|
202
|
+
origin = typing.get_origin(hint)
|
|
203
|
+
if origin is Union or origin is types.UnionType:
|
|
204
|
+
members = [a for a in typing.get_args(hint) if a is not type(None)]
|
|
205
|
+
if len(members) != 1:
|
|
206
|
+
raise SchemaError(f"{label}: unions other than `T | None` are not supported")
|
|
207
|
+
return dataclasses.replace(_describe(_unwrap(members[0], label)[0], label), optional=True)
|
|
208
|
+
if hint is str:
|
|
209
|
+
return Type("string")
|
|
210
|
+
if hint is bool:
|
|
211
|
+
return Type("boolean")
|
|
212
|
+
if hint is int:
|
|
213
|
+
return Type("integer", py=int)
|
|
214
|
+
if hint is float:
|
|
215
|
+
return Type("number", py=float)
|
|
216
|
+
if hint is Any:
|
|
217
|
+
return Type("unknown")
|
|
218
|
+
if origin is list:
|
|
219
|
+
(item,) = typing.get_args(hint)
|
|
220
|
+
return Type("array", items=_describe(_unwrap(item, label)[0], f"{label}[]"))
|
|
221
|
+
if origin is Literal:
|
|
222
|
+
values = typing.get_args(hint)
|
|
223
|
+
if not all(isinstance(v, str) for v in values):
|
|
224
|
+
raise SchemaError(f"{label}: Literal values must be strings")
|
|
225
|
+
return Type("enum", values=list(values))
|
|
226
|
+
if isinstance(hint, type) and issubclass(hint, enum.Enum):
|
|
227
|
+
values = [member.value for member in hint]
|
|
228
|
+
if not all(isinstance(v, str) for v in values):
|
|
229
|
+
raise SchemaError(f"{label}: Enum values must be strings")
|
|
230
|
+
return Type("enum", values=values, py=hint)
|
|
231
|
+
nested = getattr(hint, _SCHEMA, None) if isinstance(hint, type) else None
|
|
232
|
+
if isinstance(nested, Type):
|
|
233
|
+
return dataclasses.replace(nested, py=hint)
|
|
234
|
+
raise SchemaError(f"{label}: unsupported type {hint!r}")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _apply(ty: Type, info: FieldInfo, label: str) -> Type:
|
|
238
|
+
"""Applies `incur.field` metadata to a field schema."""
|
|
239
|
+
if info.alias is not None and (len(info.alias) != 1 or info.alias in "- "):
|
|
240
|
+
raise SchemaError(f"{label}: alias must be one character, got {info.alias!r}")
|
|
241
|
+
if (info.min is not None or info.max is not None) and ty.kind not in (
|
|
242
|
+
"array",
|
|
243
|
+
"integer",
|
|
244
|
+
"number",
|
|
245
|
+
"string",
|
|
246
|
+
):
|
|
247
|
+
raise SchemaError(f"{label}: min and max apply to numbers, strings, and lists")
|
|
248
|
+
if info.count and ty.kind not in ("integer", "number"):
|
|
249
|
+
raise SchemaError(f"{label}: count applies to int and float fields")
|
|
250
|
+
ty = dataclasses.replace(
|
|
251
|
+
ty,
|
|
252
|
+
description=info.description,
|
|
253
|
+
deprecated=info.deprecated,
|
|
254
|
+
min=info.min,
|
|
255
|
+
max=info.max,
|
|
256
|
+
)
|
|
257
|
+
return ty.with_count() if info.count else ty
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def type_of(hint: Any, label: str) -> Type:
|
|
261
|
+
"""Returns the schema of a type used as a command output or context parameter."""
|
|
262
|
+
hint, info = _unwrap(hint, label)
|
|
263
|
+
ty = _describe(hint, label)
|
|
264
|
+
return _apply(ty, info, label) if info else ty
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def schema_of(cls: type) -> Type | None:
|
|
268
|
+
"""Returns the schema attached to a schema class."""
|
|
269
|
+
found = getattr(cls, _SCHEMA, None)
|
|
270
|
+
return found if isinstance(found, Type) else None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def build(ty: Type, value: Any) -> Any:
|
|
274
|
+
"""Converts validated JSON data into the Python value a field declares."""
|
|
275
|
+
if value is None:
|
|
276
|
+
return None
|
|
277
|
+
if ty.kind == "object" and ty.py is not None:
|
|
278
|
+
kwargs = {f.attr: build(f.ty, value.get(f.name)) for f in ty.fields}
|
|
279
|
+
return ty.py(**kwargs)
|
|
280
|
+
if ty.kind == "array" and ty.items is not None:
|
|
281
|
+
return [build(ty.items, item) for item in value]
|
|
282
|
+
if ty.py is not None:
|
|
283
|
+
return ty.py(value)
|
|
284
|
+
return value
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def dump(instance: object) -> dict[str, Json]:
|
|
288
|
+
"""Returns a schema class instance as JSON data, with field names as input spells them.
|
|
289
|
+
|
|
290
|
+
Optional fields that are `None` are omitted, as they are absent from parsed input.
|
|
291
|
+
|
|
292
|
+
>>> @schema(rename_all="camelCase")
|
|
293
|
+
... class Options:
|
|
294
|
+
... dry_run: bool | None = None
|
|
295
|
+
... retries: int = 3
|
|
296
|
+
>>> dump(Options(retries=5))
|
|
297
|
+
{'retries': 5}
|
|
298
|
+
"""
|
|
299
|
+
ty = schema_of(type(instance))
|
|
300
|
+
if ty is None:
|
|
301
|
+
raise SchemaError(f"{type(instance).__qualname__} is not an @incur.schema class")
|
|
302
|
+
out: dict[str, Json] = {}
|
|
303
|
+
for f in ty.fields:
|
|
304
|
+
value = getattr(instance, f.attr)
|
|
305
|
+
if value is None and f.ty.optional:
|
|
306
|
+
continue
|
|
307
|
+
out[f.name] = to_json(value)
|
|
308
|
+
return out
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def to_json(value: object) -> Json:
|
|
312
|
+
"""Converts handler data into JSON data.
|
|
313
|
+
|
|
314
|
+
Accepts JSON-compatible values, tuples, string enums, and schema class instances.
|
|
315
|
+
Non-finite floats become `None`, as `JSON.stringify` writes them.
|
|
316
|
+
|
|
317
|
+
Raises:
|
|
318
|
+
Error: An `UNKNOWN` error when the value has no JSON representation.
|
|
319
|
+
"""
|
|
320
|
+
return _js.normalize(_to_json(value, None))
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _to_json(value: object, label: str | None) -> Json:
|
|
324
|
+
if value is None or isinstance(value, (bool, str, int)):
|
|
325
|
+
return value
|
|
326
|
+
if isinstance(value, float):
|
|
327
|
+
return value if math.isfinite(value) else None
|
|
328
|
+
if isinstance(value, enum.Enum):
|
|
329
|
+
return _to_json(value.value, label)
|
|
330
|
+
if isinstance(value, (list, tuple)):
|
|
331
|
+
items = typing.cast("list[object] | tuple[object, ...]", value)
|
|
332
|
+
return [_to_json(item, label) for item in items]
|
|
333
|
+
if isinstance(value, dict):
|
|
334
|
+
out: dict[str, Json] = {}
|
|
335
|
+
for key, item in typing.cast("dict[object, object]", value).items():
|
|
336
|
+
if not isinstance(key, str):
|
|
337
|
+
raise _unserializable(f"key {key!r} is not a string", label)
|
|
338
|
+
out[key] = _to_json(item, label)
|
|
339
|
+
return out
|
|
340
|
+
if schema_of(type(value)) is not None:
|
|
341
|
+
return dump(value)
|
|
342
|
+
raise _unserializable(f"{type(value).__qualname__} is not JSON serializable", label)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _unserializable(message: str, label: str | None) -> Exception:
|
|
346
|
+
if label is not None:
|
|
347
|
+
return SchemaError(f"{label}: default {message}")
|
|
348
|
+
return Error("UNKNOWN", message)
|