mcp-dispatch 0.1.1__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,121 @@
1
+ """A call made without a client: the same tools, paths and arguments, from a
2
+ command line or a test.
3
+
4
+ mcp-dispatch call create shelf/add title=Dune author="Frank Herbert"
5
+ mcp-dispatch call search q=herbert t=book
6
+ mcp-dispatch call create '{"path": "shelf/add", "title": "Dune"}'
7
+
8
+ ``answer`` is what the tools of an MCP server do with a call (mcp_tools.py),
9
+ without the server: one call or a list of them, help for a path that ends in
10
+ ``?``, a refusal as ``[error:Code] ...``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from collections.abc import Callable, Mapping, Sequence
17
+ from typing import Any
18
+
19
+ from mcp_dispatch.errors import BAD_INPUT, DispatchError
20
+ from mcp_dispatch.registry import (
21
+ PATH_KEY,
22
+ Bound,
23
+ Help,
24
+ Registry,
25
+ failed,
26
+ label,
27
+ repaired,
28
+ report,
29
+ )
30
+
31
+ #: what a host does with one checked call: it answers with its text
32
+ Run = Callable[[Bound], str]
33
+
34
+ FORM = (
35
+ "a call is written <tool> [<path>] [<key>=<value> ...], e.g."
36
+ " create shelf/add title=Dune, or with its JSON as an example shows it:"
37
+ """ create '{"path": "shelf/add", "title": "Dune"}'"""
38
+ )
39
+
40
+
41
+ def arguments(words: Sequence[str]) -> dict[str, Any]:
42
+ """The arguments of a call from the words of a command line.
43
+
44
+ Either one JSON object, the call as an example writes it; or the path,
45
+ if the tool takes one, and ``key=value`` words. A value is passed on as
46
+ its text: the action's type hints turn ``5`` into a number, ``true``
47
+ into a yes, and ``["a", "b"]`` into a list. ``DispatchError`` for words
48
+ that are neither.
49
+ """
50
+ if len(words) == 1 and words[0].lstrip().startswith("{"):
51
+ try:
52
+ found = json.loads(words[0])
53
+ except ValueError as exc:
54
+ raise DispatchError(
55
+ BAD_INPUT, f"the call is not JSON: {exc}", hint=FORM
56
+ ) from exc
57
+ return dict(found)
58
+ out: dict[str, Any] = {}
59
+ for n, word in enumerate(words):
60
+ key, sign, value = word.partition("=")
61
+ if not sign and n == 0:
62
+ out[PATH_KEY] = word
63
+ elif not sign or not key:
64
+ raise DispatchError(BAD_INPUT, f"{word!r} is not <key>=<value>", hint=FORM)
65
+ elif key in out:
66
+ raise DispatchError(BAD_INPUT, f"`{key}` is given twice", hint=FORM)
67
+ else:
68
+ out[key] = value
69
+ return out
70
+
71
+
72
+ def outcome(
73
+ registry: Registry, tool: str, arguments: Mapping[str, Any], run: Run | None = None
74
+ ) -> tuple[str, bool]:
75
+ """What a call on ``tool`` is answered with, and whether it went well:
76
+ for a list of calls, whether every one did. See :func:`answer`."""
77
+ if tool not in registry.tools:
78
+ raise ValueError(
79
+ f"this host has no tool {tool!r}; its tools are "
80
+ + ", ".join(registry.tools)
81
+ )
82
+ run = run or (lambda bound: bound.run(None))
83
+
84
+ def one(item: Mapping[str, Any]) -> str:
85
+ try:
86
+ found = registry.resolve(tool, item)
87
+ if isinstance(found, Help):
88
+ return found.text
89
+ try:
90
+ said = run(found)
91
+ except DispatchError as exc:
92
+ said = exc.render()
93
+ return repaired(found.repairs, said)
94
+ except DispatchError as exc:
95
+ return exc.render()
96
+
97
+ try:
98
+ batch = registry.batch(arguments, tool)
99
+ except DispatchError as exc:
100
+ return exc.render(), False
101
+ if batch is None:
102
+ said = one(arguments)
103
+ return said, not failed(said)
104
+ answers = [(label(item, tool), one(item)) for item in batch.calls]
105
+ well = not any(failed(said) for _, said in answers)
106
+ return repaired(batch.repairs, report(answers)), well
107
+
108
+
109
+ def answer(
110
+ registry: Registry, tool: str, arguments: Mapping[str, Any], run: Run | None = None
111
+ ) -> str:
112
+ """What a call on ``tool`` is answered with, as text.
113
+
114
+ ``run(bound)`` makes one checked call and answers with its text: a host
115
+ opens its transaction there and hands its actions what they get as
116
+ ``call`` (``bound.run(<that>)``). Left out, actions get ``None``. A
117
+ ``DispatchError`` is answered as ``[error:Code] ...``; any other
118
+ exception is the caller's. ``ValueError`` for a tool the host does not
119
+ have.
120
+ """
121
+ return outcome(registry, tool, arguments, run)[0]
@@ -0,0 +1,208 @@
1
+ """A host in a few lines: the tools, the plugins, what an assistant is told
2
+ first, and the server.
3
+
4
+ from mcp_dispatch import SKILL_SEARCH, Dispatch
5
+
6
+ dispatch = Dispatch() # the standard tools and the search
7
+ dispatch.find_plugins() # every plugin that is installed
8
+ dispatch.add_initial_message("You keep the lab's notes for its people.")
9
+ dispatch.add_initial_message(SKILL_SEARCH)
10
+ dispatch.server("lab-notes").run()
11
+
12
+ What an assistant reads before its first call is the initial message, the
13
+ tools' descriptions and their schemas, in every conversation. It is kept
14
+ small: the initial message has a limit, and what is not needed at once goes
15
+ into a skill, which is found through the search when it is needed.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import logging
22
+ from collections.abc import Callable, Sequence
23
+ from typing import TYPE_CHECKING, Any, Literal
24
+
25
+ from mcp_dispatch.errors import DispatchError
26
+ from mcp_dispatch.registry import GROUP, Bound, Registry
27
+ from mcp_dispatch.skills import Skill
28
+ from mcp_dispatch.tags import Plugin, Tool
29
+
30
+ if TYPE_CHECKING:
31
+ from mcp.server.fastmcp import FastMCP
32
+
33
+ from mcp_dispatch.mcp_tools import Run
34
+
35
+ log = logging.getLogger("mcp_dispatch")
36
+
37
+ #: characters of the initial message unless the host sets its own limit
38
+ INITIAL_LIMIT = 2000
39
+
40
+ #: a part for the initial message: how an assistant finds the how-to guides
41
+ SKILL_SEARCH = (
42
+ "When you do not know how to do something here, find the how-to guide first:"
43
+ ' `search` with {"q": "<the task in your own words>", "t": "skill"}.'
44
+ )
45
+
46
+
47
+ class Dispatch:
48
+ """One host: its tools, its plugins and what it tells an assistant first.
49
+
50
+ ``tools`` is the list of :class:`Tool` an action can be tagged with, in
51
+ the order a client sees them; left out, the standard set. ``search``
52
+ replaces what a client is told about the search tool. ``group`` is the
53
+ entry point group :meth:`find_plugins` looks in. ``initial_limit`` is how
54
+ many characters the initial message may have; ``None`` for no limit.
55
+ ``skills_from`` is ``"index"`` for a running host, which reads each
56
+ plugin's generated ``skills/index.json``, or ``"files"`` for a test or a
57
+ check, which reads the skill files themselves; left out, the index,
58
+ unless the command line is looking at this host.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ tools: Sequence[Tool] | None = None,
64
+ *,
65
+ search: str | None = None,
66
+ group: str = GROUP,
67
+ initial_limit: int | None = INITIAL_LIMIT,
68
+ skills_from: Literal["index", "files"] | None = None,
69
+ ) -> None:
70
+ self.registry = Registry(tools, search=search, skills_from=skills_from)
71
+ self.group = group
72
+ self.initial_limit = initial_limit
73
+ self._initial: list[str] = []
74
+
75
+ # ------------------------------------------------------------- the plugins
76
+
77
+ def find_plugins(self) -> list[str]:
78
+ """Add every plugin installed under the entry point group and return
79
+ their names. One that cannot be loaded stops the start."""
80
+ before = set(self.registry.packages)
81
+ self.registry.load_entry_points(self.group)
82
+ return sorted(set(self.registry.packages) - before)
83
+
84
+ def add(self, name: str, plugin: type[Plugin]) -> None:
85
+ """Add one plugin class by hand, under ``name``, the first part of
86
+ its paths."""
87
+ self.registry.register(name, plugin)
88
+
89
+ # ----------------------------------------------------- the initial message
90
+
91
+ def add_initial_message(self, text: str) -> None:
92
+ """Add a part to what an assistant is told when it connects. The
93
+ parts are joined in the order they were added."""
94
+ text = text.strip()
95
+ if not text:
96
+ raise ValueError("a part of the initial message has no text")
97
+ self._initial.append(text)
98
+
99
+ def skill(self, name: str) -> str:
100
+ """The text of one skill, e.g. as a part of the initial message."""
101
+ found = self.registry.skills.get(name.strip().lower())
102
+ if found is None:
103
+ raise ValueError(
104
+ f"no skill is called {name!r}; installed: "
105
+ + (", ".join(sorted(self.registry.skills)) or "none")
106
+ )
107
+ return found.text
108
+
109
+ def best_skills(self, q: str, limit: int = 2) -> list[Skill]:
110
+ """The skills that fit a task said in plain words, best first."""
111
+ return self.registry.best_skills(q, limit)
112
+
113
+ @property
114
+ def initial_message(self) -> str:
115
+ """The parts, joined; refused when it is longer than the limit."""
116
+ text = "\n\n".join(self._initial)
117
+ if self.initial_limit is not None and len(text) > self.initial_limit:
118
+ raise ValueError(
119
+ f"the initial message is {len(text)} characters; the limit is"
120
+ f" {self.initial_limit}. An assistant reads it in every"
121
+ " conversation: move what is not needed at once into a skill, or"
122
+ " raise the limit with Dispatch(initial_limit=...)"
123
+ )
124
+ return text
125
+
126
+ def first_read(self) -> dict[str, int]:
127
+ """How many characters an assistant reads before its first call: the
128
+ initial message, then each tool's description and schema."""
129
+ from mcp_dispatch import mcp_tools
130
+
131
+ sizes = {"initial message": len("\n\n".join(self._initial))}
132
+ for tool in mcp_tools.listed(self.registry):
133
+ schema = json.dumps(mcp_tools.schema(tool), ensure_ascii=False)
134
+ sizes[tool.name] = len(tool.description) + len(schema)
135
+ return sizes
136
+
137
+ # -------------------------------------------------------------- the server
138
+
139
+ def mount(
140
+ self,
141
+ mcp: FastMCP,
142
+ run: Run,
143
+ *,
144
+ example_path: str | None = None,
145
+ open_world: bool = False,
146
+ ) -> None:
147
+ """Add the tools to a server the host built itself. ``run(ctx, bound)``
148
+ makes one checked call and answers with its text: the host opens its
149
+ transaction (``bound.tool.writes`` says of which kind), builds what
150
+ its actions get as ``call`` and returns ``bound.run(call)``."""
151
+ _need_mcp()
152
+ from mcp_dispatch import mcp_tools
153
+
154
+ mcp_tools.register(
155
+ mcp, self.registry, run, example_path=example_path, open_world=open_world
156
+ )
157
+
158
+ def server(
159
+ self,
160
+ name: str,
161
+ *,
162
+ call: Callable[[Any], Any] | None = None,
163
+ example_path: str | None = None,
164
+ open_world: bool = False,
165
+ **fastmcp: Any,
166
+ ) -> FastMCP:
167
+ """A server with the tools and the initial message, ready to run:
168
+ ``dispatch.server("notes").run()``.
169
+
170
+ ``call(ctx)`` makes what every action gets as its first argument from
171
+ the MCP context of the call; left out, actions get ``None``. Each call
172
+ runs in a worker thread. An action's ``DispatchError`` is answered as
173
+ ``[error:Code] ...``; any other exception is logged and answered as
174
+ ``[error:Internal]`` without its details.
175
+ """
176
+ _need_mcp()
177
+ import anyio.to_thread
178
+ from mcp.server.fastmcp import FastMCP
179
+
180
+ async def run(ctx: Any, bound: Bound) -> str:
181
+ def work() -> str:
182
+ try:
183
+ return bound.run(call(ctx) if call is not None else None)
184
+ except DispatchError as exc:
185
+ return exc.render()
186
+ except Exception:
187
+ log.exception("%s failed", bound.action.path)
188
+ return DispatchError(
189
+ "Internal",
190
+ "something went wrong on the server",
191
+ hint="try again later",
192
+ ).render()
193
+
194
+ return await anyio.to_thread.run_sync(work)
195
+
196
+ mcp = FastMCP(name, instructions=self.initial_message or None, **fastmcp)
197
+ self.mount(mcp, run, example_path=example_path, open_world=open_world)
198
+ return mcp
199
+
200
+
201
+ def _need_mcp() -> None:
202
+ """Serving needs the MCP SDK, which a plugin does not: it is an extra."""
203
+ try:
204
+ import mcp # noqa: F401
205
+ except ImportError as exc:
206
+ raise ImportError(
207
+ 'serving needs the MCP SDK: install "mcp-dispatch[mcp]"'
208
+ ) from exc
mcp_dispatch/docs.py ADDED
@@ -0,0 +1,100 @@
1
+ """Google-style docstrings, read into the parts the help prints.
2
+
3
+ Only the docstring is read, never a comment: what an action's author writes
4
+ in a comment block below the docstring cannot reach an assistant.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import inspect
10
+ import re
11
+ from dataclasses import dataclass, field
12
+
13
+ _SECTIONS = {
14
+ "Args": "args",
15
+ "Arguments": "args",
16
+ "Returns": "returns",
17
+ "Example": "example",
18
+ "Examples": "example",
19
+ }
20
+ #: sections of a Google docstring that help does not print. They are read as
21
+ #: sections all the same, so that their text is not taken for the end of the
22
+ #: section before them.
23
+ _UNPRINTED = (
24
+ "Attributes", "Note", "Notes", "Raises", "References", "See Also", "Todo",
25
+ "Warning", "Warnings", "Warns", "Yields",
26
+ ) # fmt: skip
27
+ # What a section says may begin on the line of its name.
28
+ _SECTION_RE = re.compile(
29
+ rf"^({'|'.join(map(re.escape, (*_SECTIONS, *_UNPRINTED)))}):(?:\s+(.*))?$"
30
+ )
31
+ _ARG_RE = re.compile(r"^(\*{0,2}\w+)\s*(?:\([^)]*\))?:\s*(.*)$")
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Doc:
36
+ summary: str = ""
37
+ body: str = ""
38
+ args: dict[str, str] = field(default_factory=dict)
39
+ returns: str = ""
40
+ example: str = ""
41
+ #: the names of sections that are there and that help does not print
42
+ unprinted: tuple[str, ...] = ()
43
+
44
+
45
+ def _indent(line: str) -> int:
46
+ return len(line) - len(line.lstrip())
47
+
48
+
49
+ def _args(lines: list[str]) -> dict[str, str]:
50
+ """One entry per parameter; a deeper-indented line continues the entry."""
51
+ out: dict[str, str] = {}
52
+ lines = [line for line in lines if line.strip()]
53
+ if not lines:
54
+ return out
55
+ base = min(_indent(line) for line in lines)
56
+ name: str | None = None
57
+ for line in lines:
58
+ found = _ARG_RE.match(line.strip()) if _indent(line) == base else None
59
+ if found:
60
+ name = found.group(1).lstrip("*")
61
+ out[name] = found.group(2).strip()
62
+ elif name is not None:
63
+ out[name] = f"{out[name]} {line.strip()}".strip()
64
+ return out
65
+
66
+
67
+ def parse(text: str | None) -> Doc:
68
+ lines = inspect.cleandoc(text or "").splitlines()
69
+ parts: dict[str, list[str]] = {"head": []}
70
+ current = "head"
71
+ unprinted: list[str] = []
72
+ for line in lines:
73
+ found = _SECTION_RE.match(line.rstrip()) if _indent(line) == 0 else None
74
+ if found is None:
75
+ parts[current].append(line)
76
+ continue
77
+ name, rest = found.group(1), found.group(2)
78
+ if name in _SECTIONS:
79
+ current = _SECTIONS[name]
80
+ elif rest and current == "head":
81
+ # "Note: it looks only once." in the text above the sections is a
82
+ # sentence of that text, not a section
83
+ parts[current].append(line)
84
+ continue
85
+ else:
86
+ current = f"unprinted {name}"
87
+ unprinted.append(name)
88
+ parts.setdefault(current, [])
89
+ if rest: # what a section says may begin on the line of its name
90
+ parts[current].append(rest)
91
+ head = "\n".join(parts["head"]).strip()
92
+ summary, _, body = head.partition("\n\n")
93
+ return Doc(
94
+ summary=" ".join(summary.split()),
95
+ body="\n".join(" ".join(p.split()) for p in body.split("\n\n")).strip(),
96
+ args=_args(parts.get("args", [])),
97
+ returns=" ".join(" ".join(parts.get("returns", [])).split()),
98
+ example=inspect.cleandoc("\n".join(parts.get("example", []))).strip(),
99
+ unprinted=tuple(dict.fromkeys(unprinted)),
100
+ )
mcp_dispatch/errors.py ADDED
@@ -0,0 +1,32 @@
1
+ """The exception the dispatcher raises for a call it refuses, and how it reads
2
+ to the caller; and the one for a plugin that cannot be loaded."""
3
+
4
+ from __future__ import annotations
5
+
6
+ BAD_INPUT = "BadInput"
7
+ NOT_FOUND = "NotFound"
8
+
9
+
10
+ class DispatchError(Exception):
11
+ """A refusal the caller (an assistant) should see as text.
12
+
13
+ Rendered as ``[error:<code>] <message>`` plus an optional ``hint:`` line.
14
+ An action may raise it, or an error of its host's that reads the same.
15
+ """
16
+
17
+ def __init__(self, code: str, message: str, hint: str | None = None) -> None:
18
+ super().__init__(f"[{code}] {message}")
19
+ self.code = code
20
+ self.message = message
21
+ self.hint = hint
22
+
23
+ def render(self) -> str:
24
+ text = f"[error:{self.code}] {self.message}"
25
+ if self.hint:
26
+ text += f"\nhint: {self.hint}"
27
+ return text
28
+
29
+
30
+ class PluginError(RuntimeError):
31
+ """A plugin that cannot be loaded. It stops the host from starting; the
32
+ message names the plugin and what is wrong with it."""
@@ -0,0 +1,172 @@
1
+ """JSON that arrived as text, read with the slips an assistant makes repaired.
2
+
3
+ Only for JSON inside a string: a list of calls or a list argument sent as its
4
+ text. The arguments of a tool call themselves are parsed by the client and
5
+ never pass through here. ``loads`` returns the value and what was repaired,
6
+ so the reply can say so; text that is JSON already comes back with no repairs.
7
+
8
+ Repaired: single quotes, unquoted keys, unquoted words as values, ``=`` for
9
+ ``:``, a trailing comma, Python's ``True``/``False``/``None``, a line break
10
+ inside a string, closing brackets missing at the end. Anything else (a missing
11
+ comma, text after the end) is refused: guessing there could change the meaning.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ from typing import Any
19
+
20
+ _NUMBER_RE = re.compile(r"-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?")
21
+ _WORD_RE = re.compile(r"[A-Za-z_][\w.\-]*")
22
+ _ESCAPES = {
23
+ "n": "\n", "t": "\t", "r": "\r", "b": "\b", "f": "\f",
24
+ "/": "/", "\\": "\\", '"': '"', "'": "'",
25
+ } # fmt: skip
26
+ _WORDS = {"true": True, "false": False, "null": None}
27
+ _PYTHON_WORDS = {"True": True, "False": False, "None": None}
28
+
29
+
30
+ class _Parser:
31
+ def __init__(self, text: str) -> None:
32
+ self.text = text
33
+ self.at = 0
34
+ self.repairs: list[str] = []
35
+
36
+ def note(self, what: str) -> None:
37
+ if what not in self.repairs:
38
+ self.repairs.append(what)
39
+
40
+ def peek(self) -> str:
41
+ while self.at < len(self.text) and self.text[self.at].isspace():
42
+ self.at += 1
43
+ return self.text[self.at] if self.at < len(self.text) else ""
44
+
45
+ def fail(self, what: str) -> ValueError:
46
+ return ValueError(f"{what} at character {self.at + 1}")
47
+
48
+ def value(self) -> Any:
49
+ c = self.peek()
50
+ if c == "{":
51
+ return self.object()
52
+ if c == "[":
53
+ return self.array()
54
+ if c in ('"', "'"):
55
+ return self.string()
56
+ found = _NUMBER_RE.match(self.text, self.at)
57
+ if found:
58
+ self.at = found.end()
59
+ return json.loads(found.group(0))
60
+ found = _WORD_RE.match(self.text, self.at)
61
+ if not found:
62
+ raise self.fail(f"unexpected {c!r}" if c else "the text ends early")
63
+ self.at = found.end()
64
+ word = found.group(0)
65
+ if word in _WORDS:
66
+ return _WORDS[word]
67
+ if word in _PYTHON_WORDS:
68
+ self.note(f"`{word}` for `{json.dumps(_PYTHON_WORDS[word])}`")
69
+ return _PYTHON_WORDS[word]
70
+ self.note(f"unquoted text `{word}`")
71
+ return word
72
+
73
+ def string(self) -> str:
74
+ quote = self.text[self.at]
75
+ if quote == "'":
76
+ self.note("single quotes")
77
+ self.at += 1
78
+ out: list[str] = []
79
+ while True:
80
+ if self.at >= len(self.text):
81
+ raise self.fail("a string is not closed")
82
+ c = self.text[self.at]
83
+ self.at += 1
84
+ if c == quote:
85
+ return "".join(out)
86
+ if c == "\n":
87
+ self.note("a line break inside a string")
88
+ if c != "\\":
89
+ out.append(c)
90
+ continue
91
+ escape = self.text[self.at : self.at + 1]
92
+ self.at += 1
93
+ if escape == "u":
94
+ digits = self.text[self.at : self.at + 4]
95
+ if not re.fullmatch(r"[0-9a-fA-F]{4}", digits):
96
+ raise self.fail("a \\u escape needs four hex digits")
97
+ out.append(chr(int(digits, 16)))
98
+ self.at += 4
99
+ elif escape in _ESCAPES:
100
+ out.append(_ESCAPES[escape])
101
+ else:
102
+ raise self.fail(f"unknown escape \\{escape}")
103
+
104
+ def key(self) -> str:
105
+ if self.peek() in ('"', "'"):
106
+ return self.string()
107
+ found = _WORD_RE.match(self.text, self.at)
108
+ if not found:
109
+ raise self.fail("a key is expected")
110
+ self.at = found.end()
111
+ self.note(f"unquoted key `{found.group(0)}`")
112
+ return found.group(0)
113
+
114
+ def closed(self, close: str) -> bool:
115
+ """At the end of an object or a list; one cut off at the end of the
116
+ text counts as closed."""
117
+ c = self.peek()
118
+ if c == close:
119
+ self.at += 1
120
+ return True
121
+ if not c:
122
+ self.note(f"missing closing `{close}`")
123
+ return True
124
+ return False
125
+
126
+ def separator(self, close: str) -> None:
127
+ c = self.peek()
128
+ if c == ",":
129
+ self.at += 1
130
+ if self.peek() == close:
131
+ self.note("a trailing comma")
132
+ elif c and c != close:
133
+ raise self.fail(f"`,` or `{close}` is expected")
134
+
135
+ def object(self) -> dict[str, Any]:
136
+ self.at += 1
137
+ out: dict[str, Any] = {}
138
+ while not self.closed("}"):
139
+ key = self.key()
140
+ c = self.peek()
141
+ if c == "=":
142
+ self.note("`=` for `:`")
143
+ elif c != ":":
144
+ raise self.fail("`:` is expected after a key")
145
+ self.at += 1
146
+ out[key] = self.value()
147
+ self.separator("}")
148
+ return out
149
+
150
+ def array(self) -> list[Any]:
151
+ self.at += 1
152
+ out: list[Any] = []
153
+ while not self.closed("]"):
154
+ out.append(self.value())
155
+ self.separator("]")
156
+ return out
157
+
158
+
159
+ def loads(text: str) -> tuple[Any, tuple[str, ...]]:
160
+ """The value of a JSON text and what had to be repaired to read it.
161
+
162
+ Raises ``ValueError`` when it is not JSON even with the repairs.
163
+ """
164
+ try:
165
+ return json.loads(text), ()
166
+ except ValueError:
167
+ pass
168
+ parser = _Parser(text)
169
+ value = parser.value()
170
+ if parser.peek():
171
+ raise parser.fail("text after the end")
172
+ return value, tuple(parser.repairs)