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.
- mcp_dispatch/__init__.py +59 -0
- mcp_dispatch/__main__.py +3 -0
- mcp_dispatch/agent_instructions/host.md +102 -0
- mcp_dispatch/agent_instructions/plugin.md +222 -0
- mcp_dispatch/check.py +310 -0
- mcp_dispatch/cli.py +276 -0
- mcp_dispatch/command.py +121 -0
- mcp_dispatch/dispatch.py +208 -0
- mcp_dispatch/docs.py +100 -0
- mcp_dispatch/errors.py +32 -0
- mcp_dispatch/lenient.py +172 -0
- mcp_dispatch/mcp_tools.py +195 -0
- mcp_dispatch/py.typed +0 -0
- mcp_dispatch/registry.py +972 -0
- mcp_dispatch/skills.py +533 -0
- mcp_dispatch/tags.py +173 -0
- mcp_dispatch/trials.py +380 -0
- mcp_dispatch-0.1.1.dist-info/METADATA +86 -0
- mcp_dispatch-0.1.1.dist-info/RECORD +22 -0
- mcp_dispatch-0.1.1.dist-info/WHEEL +4 -0
- mcp_dispatch-0.1.1.dist-info/entry_points.txt +2 -0
- mcp_dispatch-0.1.1.dist-info/licenses/LICENSE +21 -0
mcp_dispatch/check.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""The check and the updater: what an assistant will read about a host's
|
|
2
|
+
plugins is checked, not reviewed.
|
|
3
|
+
|
|
4
|
+
``problems(dispatch)`` returns one line per thing that is wrong, each saying
|
|
5
|
+
what to change; an empty list means the plugins are fit to ship. Run it in CI
|
|
6
|
+
(``mcp-dispatch check``) or as a test::
|
|
7
|
+
|
|
8
|
+
from mcp_dispatch.check import problems
|
|
9
|
+
|
|
10
|
+
def test_the_plugins_are_documented():
|
|
11
|
+
assert problems(my_dispatch) == []
|
|
12
|
+
|
|
13
|
+
``update(dispatch)`` writes what is generated: each plugin's
|
|
14
|
+
``skills/index.json`` and, when asked, the pinned contract.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import inspect
|
|
20
|
+
import json
|
|
21
|
+
import shlex
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from mcp_dispatch import skills as skill_files
|
|
26
|
+
from mcp_dispatch.dispatch import Dispatch
|
|
27
|
+
from mcp_dispatch.errors import DispatchError
|
|
28
|
+
from mcp_dispatch.registry import (
|
|
29
|
+
KIND_KEY,
|
|
30
|
+
SKILL_PACKAGE,
|
|
31
|
+
Action,
|
|
32
|
+
Bound,
|
|
33
|
+
Package,
|
|
34
|
+
Param,
|
|
35
|
+
Registry,
|
|
36
|
+
)
|
|
37
|
+
from mcp_dispatch.skills import INDEX, UPDATE, Skill
|
|
38
|
+
|
|
39
|
+
MAX_SUMMARY = 100 # characters of a docstring's first line (its first paragraph)
|
|
40
|
+
MAX_DOC = 2000 # characters of one action's docstring
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _where(action: Action) -> str:
|
|
44
|
+
if action.search:
|
|
45
|
+
return f"{action.package}: the search ({action.name})"
|
|
46
|
+
return action.path
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _shown(tool: str, arguments: dict[str, Any]) -> str:
|
|
50
|
+
return f"{tool} {json.dumps(arguments, ensure_ascii=False)}"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _needs_example(p: Param) -> bool:
|
|
54
|
+
"""A fixed set of values is listed by the help itself and a yes/no
|
|
55
|
+
argument has two; every other argument shows an example."""
|
|
56
|
+
schema = p.adapter.json_schema()
|
|
57
|
+
options = [s for s in schema.get("anyOf", [schema]) if s.get("type") != "null"]
|
|
58
|
+
return not all(
|
|
59
|
+
"enum" in s or "const" in s or s.get("type") == "boolean" for s in options
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _example(registry: Registry, action: Action) -> list[str]:
|
|
64
|
+
where = _where(action)
|
|
65
|
+
path = "" if action.search else f'"path": "{action.path}", '
|
|
66
|
+
form = f"{action.tool} {{{path}...}}"
|
|
67
|
+
try:
|
|
68
|
+
found = list(registry.example_calls(action.doc.example))
|
|
69
|
+
except ValueError as exc:
|
|
70
|
+
return [f"{where}: `Example:` {exc}"]
|
|
71
|
+
if len(found) != 1:
|
|
72
|
+
return [
|
|
73
|
+
f"{where}: `Example:` needs exactly one call, written as {form};"
|
|
74
|
+
f" found {len(found)}"
|
|
75
|
+
]
|
|
76
|
+
tool, arguments = found[0]
|
|
77
|
+
if tool != action.tool:
|
|
78
|
+
return [
|
|
79
|
+
f"{where}: the example goes through `{tool}`; the action is tagged"
|
|
80
|
+
f" for `{action.tool}`: write it as {form}"
|
|
81
|
+
]
|
|
82
|
+
if not action.search and arguments.get("path") != action.path:
|
|
83
|
+
return [
|
|
84
|
+
f'{where}: the example\'s "path" is {json.dumps(arguments.get("path"))};'
|
|
85
|
+
f" write it as {form}"
|
|
86
|
+
]
|
|
87
|
+
if not action.search and next(iter(arguments)) != "path":
|
|
88
|
+
return [
|
|
89
|
+
f'{where}: the example has "path" after other keys; write it first: {form}'
|
|
90
|
+
]
|
|
91
|
+
if action.search and "path" in arguments:
|
|
92
|
+
return [f"{where}: a search takes no path: write the example as {form}"]
|
|
93
|
+
try:
|
|
94
|
+
if action.search:
|
|
95
|
+
# this package's part of the search, whoever else takes part
|
|
96
|
+
registry.bind_search(action, arguments)
|
|
97
|
+
else:
|
|
98
|
+
registry.resolve(tool, arguments)
|
|
99
|
+
except DispatchError as exc:
|
|
100
|
+
return [f"{where}: the example is not a call it accepts: {exc.message}"]
|
|
101
|
+
kind = arguments.get(KIND_KEY)
|
|
102
|
+
if action.search and kind is not None and not isinstance(kind, str):
|
|
103
|
+
return [
|
|
104
|
+
f'{where}: the example searches with "{KIND_KEY}": {json.dumps(kind)};'
|
|
105
|
+
f" `{KIND_KEY}` is one kind, written as text"
|
|
106
|
+
]
|
|
107
|
+
if action.search and action.kinds and kind is not None:
|
|
108
|
+
if not isinstance(kind, str) or kind.strip().lower() not in action.kinds:
|
|
109
|
+
# at run time `t` chooses the package: this one would not be asked
|
|
110
|
+
return [
|
|
111
|
+
f'{where}: the example searches with "{KIND_KEY}": {json.dumps(kind)},'
|
|
112
|
+
f" which this method does not find; its kinds are"
|
|
113
|
+
f" {', '.join(action.kinds)}"
|
|
114
|
+
]
|
|
115
|
+
return []
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def action_problems(registry: Registry, action: Action) -> list[str]:
|
|
119
|
+
"""What is wrong with one action's docstring, which is what an assistant
|
|
120
|
+
reads about it."""
|
|
121
|
+
where, doc, out = _where(action), action.doc, []
|
|
122
|
+
if not doc.summary:
|
|
123
|
+
out.append(
|
|
124
|
+
f"{where}: the docstring needs a first line that says what the action does"
|
|
125
|
+
)
|
|
126
|
+
elif len(doc.summary) > MAX_SUMMARY:
|
|
127
|
+
out.append(
|
|
128
|
+
f"{where}: the docstring's first line, all the text before the first"
|
|
129
|
+
f" empty line, is {len(doc.summary)} characters; at most {MAX_SUMMARY}"
|
|
130
|
+
)
|
|
131
|
+
names = [p.name for p in action.params]
|
|
132
|
+
if names != list(doc.args):
|
|
133
|
+
out.append(
|
|
134
|
+
f"{where}: `Args:` has {', '.join(doc.args) or 'no entry'}; the"
|
|
135
|
+
f" signature has {', '.join(names) or 'no argument'}. One entry per"
|
|
136
|
+
" argument, in the signature's order, and none for the call context"
|
|
137
|
+
)
|
|
138
|
+
for p in action.params:
|
|
139
|
+
if p.name in doc.args and not p.text:
|
|
140
|
+
out.append(f"{where}: the argument `{p.name}` needs a description")
|
|
141
|
+
elif p.name in doc.args and _needs_example(p) and "e.g." not in p.text:
|
|
142
|
+
out.append(
|
|
143
|
+
f"{where}: the argument `{p.name}` needs an example value in its"
|
|
144
|
+
' description, written as: e.g. "..."'
|
|
145
|
+
)
|
|
146
|
+
if not doc.returns:
|
|
147
|
+
out.append(f"{where}: the docstring needs `Returns:`, what comes back")
|
|
148
|
+
for name in doc.unprinted:
|
|
149
|
+
out.append(
|
|
150
|
+
f"{where}: the docstring has a section `{name}:`, which help does not"
|
|
151
|
+
" print; say it in the text above `Args:` or under `Returns:`"
|
|
152
|
+
)
|
|
153
|
+
out += _example(registry, action)
|
|
154
|
+
size = len(inspect.getdoc(action.fn) or "")
|
|
155
|
+
if size > MAX_DOC:
|
|
156
|
+
out.append(
|
|
157
|
+
f"{where}: the docstring is {size} characters; at most {MAX_DOC}."
|
|
158
|
+
" What an assistant needs only sometimes goes into a skill"
|
|
159
|
+
)
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _scanned(registry: Registry, package: Package) -> tuple[list[Skill], list[str]]:
|
|
164
|
+
assert package.skills_dir is not None
|
|
165
|
+
return skill_files.scan(package.name, package.skills_dir, tuple(registry.tools))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def skill_problems(registry: Registry, package: Package) -> list[str]:
|
|
169
|
+
"""What is wrong with a package's skills: a header, an example call, or
|
|
170
|
+
an index that does not say what the headers say."""
|
|
171
|
+
if package.skills_dir is None:
|
|
172
|
+
return []
|
|
173
|
+
skills, out = _scanned(registry, package)
|
|
174
|
+
for skill in skills:
|
|
175
|
+
where = f"{package.name}: skills/{skill.file.name}"
|
|
176
|
+
for tool, arguments in registry.example_calls(skill.text):
|
|
177
|
+
try:
|
|
178
|
+
found = registry.resolve(tool, arguments)
|
|
179
|
+
except DispatchError as exc:
|
|
180
|
+
out.append(
|
|
181
|
+
f"{where}: {_shown(tool, arguments)} is not a call that is"
|
|
182
|
+
f" accepted: {exc.message}"
|
|
183
|
+
)
|
|
184
|
+
continue
|
|
185
|
+
if not isinstance(found, Bound):
|
|
186
|
+
out.append(
|
|
187
|
+
f"{where}: {_shown(tool, arguments)} asks for help; an"
|
|
188
|
+
" example in a skill is a call that does something"
|
|
189
|
+
)
|
|
190
|
+
index = package.skills_dir / INDEX
|
|
191
|
+
if not out:
|
|
192
|
+
if not index.is_file():
|
|
193
|
+
if skills:
|
|
194
|
+
out.append(f"{package.name}: skills/{INDEX} is missing; {UPDATE}")
|
|
195
|
+
elif index.read_text(encoding="utf-8") != skill_files.index_text(skills):
|
|
196
|
+
out.append(f"{package.name}: skills/{INDEX} is out of date; {UPDATE}")
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def problems(dispatch: Dispatch, *, contract: Path | None = None) -> list[str]:
|
|
201
|
+
"""Everything that is wrong with what a host's plugins show an assistant,
|
|
202
|
+
one line each; empty when nothing is."""
|
|
203
|
+
registry = dispatch.registry
|
|
204
|
+
out = []
|
|
205
|
+
for package in registry.packages.values():
|
|
206
|
+
if not package.doc.summary:
|
|
207
|
+
out.append(
|
|
208
|
+
f"{package.name}: the plugin class needs a docstring whose first"
|
|
209
|
+
" line says what the package is for"
|
|
210
|
+
)
|
|
211
|
+
published = [*package.actions.values()]
|
|
212
|
+
if package.search is not None:
|
|
213
|
+
published.append(package.search)
|
|
214
|
+
for action in sorted(published, key=lambda a: a.name):
|
|
215
|
+
out += action_problems(registry, action)
|
|
216
|
+
out += skill_problems(registry, package)
|
|
217
|
+
try:
|
|
218
|
+
dispatch.initial_message # noqa: B018 (raises when it is too long)
|
|
219
|
+
except ValueError as exc:
|
|
220
|
+
out.append(str(exc))
|
|
221
|
+
if contract is not None:
|
|
222
|
+
# the command that writes this file, whether it was named by the
|
|
223
|
+
# project's settings or by --contract
|
|
224
|
+
write = f"run `mcp-dispatch update --contract {shlex.quote(str(contract))}`"
|
|
225
|
+
if not contract.is_file():
|
|
226
|
+
out.append(f"the pinned contract {contract} is missing; {write}")
|
|
227
|
+
else:
|
|
228
|
+
try:
|
|
229
|
+
pinned = json.loads(contract.read_text(encoding="utf-8"))
|
|
230
|
+
except ValueError as exc:
|
|
231
|
+
out.append(
|
|
232
|
+
f"the pinned contract {contract} cannot be read ({exc!r}); {write}"
|
|
233
|
+
)
|
|
234
|
+
else:
|
|
235
|
+
if pinned != _plain(registry.contract()):
|
|
236
|
+
out.append(
|
|
237
|
+
f"the paths or their arguments differ from the pinned contract"
|
|
238
|
+
f" {contract}. If the change is meant, {write}; callers will"
|
|
239
|
+
" have to follow it"
|
|
240
|
+
)
|
|
241
|
+
return out
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def plugins(registry: Registry) -> list[Package]:
|
|
245
|
+
"""The packages that plugins brought: all but the built-in one."""
|
|
246
|
+
return [p for p in registry.packages.values() if p.name != SKILL_PACKAGE]
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def nothing_found(dispatch: Dispatch) -> str:
|
|
250
|
+
"""What the command line says in place of ``ok`` when there is no plugin:
|
|
251
|
+
a plugin whose entry point is missing would otherwise pass for one that
|
|
252
|
+
is in order."""
|
|
253
|
+
return (
|
|
254
|
+
"no plugin was found, so nothing was checked. List the plugin class in"
|
|
255
|
+
f' pyproject.toml under [project.entry-points."{dispatch.group}"] and'
|
|
256
|
+
" install the project again (`uv run` does that by itself)"
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _plain(value: Any) -> Any:
|
|
261
|
+
return json.loads(json.dumps(value))
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def summary(dispatch: Dispatch) -> str:
|
|
265
|
+
"""One line on what was checked and how much is read before a first call."""
|
|
266
|
+
registry = dispatch.registry
|
|
267
|
+
# what the plugins brought; the built-in package is not theirs
|
|
268
|
+
found = plugins(registry)
|
|
269
|
+
actions = sum(len(p.actions) + (p.search is not None) for p in found)
|
|
270
|
+
sizes = dispatch.first_read()
|
|
271
|
+
tools = sum(n for name, n in sizes.items() if name != "initial message")
|
|
272
|
+
return (
|
|
273
|
+
f"ok: {_count(len(found), 'package')},"
|
|
274
|
+
f" {_count(actions, 'published method')},"
|
|
275
|
+
f" {_count(len(registry.skills), 'skill')}. Read before the first call:"
|
|
276
|
+
f" {sum(sizes.values())} characters (the initial message"
|
|
277
|
+
f" {sizes['initial message']}, {len(sizes) - 1} tools {tools})."
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _count(n: int, what: str) -> str:
|
|
282
|
+
return f"{n} {what}" if n == 1 else f"{n} {what}s"
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def update(dispatch: Dispatch, *, contract: Path | None = None) -> list[str]:
|
|
286
|
+
"""Write what is generated and say what was written. A skill that cannot
|
|
287
|
+
be read stops it: ``ValueError`` with what is wrong."""
|
|
288
|
+
registry = dispatch.registry
|
|
289
|
+
wrong, done = [], []
|
|
290
|
+
todo: list[tuple[Path, str]] = []
|
|
291
|
+
for package in registry.packages.values():
|
|
292
|
+
if package.skills_dir is None:
|
|
293
|
+
continue
|
|
294
|
+
skills, bad = _scanned(registry, package)
|
|
295
|
+
wrong += bad
|
|
296
|
+
if skills or (package.skills_dir / INDEX).exists():
|
|
297
|
+
todo.append((package.skills_dir / INDEX, skill_files.index_text(skills)))
|
|
298
|
+
if wrong:
|
|
299
|
+
raise ValueError("\n".join(wrong))
|
|
300
|
+
if contract is not None:
|
|
301
|
+
text = json.dumps(registry.contract(), indent=1, ensure_ascii=False) + "\n"
|
|
302
|
+
todo.append((contract, text))
|
|
303
|
+
for file, text in todo:
|
|
304
|
+
if file.is_file() and file.read_text(encoding="utf-8") == text:
|
|
305
|
+
done.append(f"unchanged {file}")
|
|
306
|
+
else:
|
|
307
|
+
file.parent.mkdir(parents=True, exist_ok=True)
|
|
308
|
+
file.write_text(text, encoding="utf-8")
|
|
309
|
+
done.append(f"wrote {file}")
|
|
310
|
+
return done
|
mcp_dispatch/cli.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""The command line: the guide, the check, the updater, and the help an
|
|
2
|
+
assistant would read.
|
|
3
|
+
|
|
4
|
+
mcp-dispatch guide how to write a plugin (for the assistant that does)
|
|
5
|
+
mcp-dispatch guide host how to set up a host
|
|
6
|
+
mcp-dispatch check is everything an assistant will read in order?
|
|
7
|
+
mcp-dispatch update write the generated files (skills/index.json)
|
|
8
|
+
mcp-dispatch help notes/add what "notes/add?" answers
|
|
9
|
+
mcp-dispatch call create notes/add text="buy milk" make the call
|
|
10
|
+
|
|
11
|
+
``check``, ``update``, ``help`` and ``call`` look at the plugins installed
|
|
12
|
+
under the entry point group, with the standard tools. A project that is a
|
|
13
|
+
host of its own says where its ``Dispatch`` is, in ``pyproject.toml``::
|
|
14
|
+
|
|
15
|
+
[tool.mcp-dispatch]
|
|
16
|
+
host = "my_package.host:dispatch" # a Dispatch, or a function returning one
|
|
17
|
+
contract = "tests/contract.json" # optional: the pinned paths and arguments
|
|
18
|
+
group = "my_host.plugins" # without a host: another entry point group
|
|
19
|
+
call = "my_package.host:store" # optional: what an action gets as `call`
|
|
20
|
+
|
|
21
|
+
``call`` names a function without arguments, called once for every call
|
|
22
|
+
that is made. What it returns is handed to the action; if it is a context
|
|
23
|
+
manager, it is entered for that one call and left after it, so that a host
|
|
24
|
+
can open its transaction there, commit it, and roll it back when the action
|
|
25
|
+
refuses. Left out, actions get ``None``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import argparse
|
|
31
|
+
import importlib
|
|
32
|
+
import sys
|
|
33
|
+
import tomllib
|
|
34
|
+
from collections.abc import Iterator, Sequence
|
|
35
|
+
from contextlib import contextmanager
|
|
36
|
+
from importlib import resources
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import Any
|
|
39
|
+
|
|
40
|
+
from mcp_dispatch import check as checks
|
|
41
|
+
from mcp_dispatch import command
|
|
42
|
+
from mcp_dispatch import registry as registry_module
|
|
43
|
+
from mcp_dispatch.dispatch import Dispatch
|
|
44
|
+
from mcp_dispatch.errors import DispatchError, PluginError
|
|
45
|
+
from mcp_dispatch.registry import GROUP, Bound
|
|
46
|
+
|
|
47
|
+
GUIDES = ("plugin", "host")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def guide(name: str = "plugin") -> str:
|
|
51
|
+
"""The text of a guide that ships in the package."""
|
|
52
|
+
folder = resources.files("mcp_dispatch") / "agent_instructions"
|
|
53
|
+
return (folder / f"{name}.md").read_text(encoding="utf-8")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def settings(directory: Path | None = None) -> dict[str, Any]:
|
|
57
|
+
"""``[tool.mcp-dispatch]`` of the ``pyproject.toml`` in ``directory``."""
|
|
58
|
+
file = (directory or Path.cwd()) / "pyproject.toml"
|
|
59
|
+
if not file.is_file():
|
|
60
|
+
return {}
|
|
61
|
+
found = tomllib.loads(file.read_text(encoding="utf-8"))
|
|
62
|
+
return dict(found.get("tool", {}).get("mcp-dispatch", {}))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class HostError(Exception):
|
|
66
|
+
"""The host a project names cannot be had: the message says why."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@contextmanager
|
|
70
|
+
def _skills_from_files() -> Iterator[None]:
|
|
71
|
+
"""While a host is loaded here its skills are read from their files, not
|
|
72
|
+
from the index, so that a stale index is found and not obeyed. A host
|
|
73
|
+
the project builds itself is told through the registry's default, which
|
|
74
|
+
is put back afterwards."""
|
|
75
|
+
before = registry_module.default_skills_from
|
|
76
|
+
registry_module.default_skills_from = "files"
|
|
77
|
+
try:
|
|
78
|
+
yield
|
|
79
|
+
finally:
|
|
80
|
+
registry_module.default_skills_from = before
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def load(host: str | None, group: str) -> Dispatch:
|
|
84
|
+
"""The host to look at: the one a project names, or the standard tools
|
|
85
|
+
with every plugin installed under ``group``. ``PluginError`` for a plugin
|
|
86
|
+
that cannot be loaded, ``HostError`` for a host that cannot be had."""
|
|
87
|
+
with _skills_from_files():
|
|
88
|
+
if host is None:
|
|
89
|
+
dispatch = Dispatch(group=group)
|
|
90
|
+
dispatch.find_plugins()
|
|
91
|
+
return dispatch
|
|
92
|
+
module, _, name = host.partition(":")
|
|
93
|
+
if not module or not name:
|
|
94
|
+
raise HostError(
|
|
95
|
+
'host is "<module>:<name>", e.g. "my_package.host:dispatch";'
|
|
96
|
+
f" got {host!r}"
|
|
97
|
+
)
|
|
98
|
+
try:
|
|
99
|
+
imported = importlib.import_module(module)
|
|
100
|
+
if not hasattr(imported, name):
|
|
101
|
+
raise HostError(
|
|
102
|
+
f"the host {host} cannot be loaded: the module {module!r}"
|
|
103
|
+
f" has no {name!r}"
|
|
104
|
+
)
|
|
105
|
+
found = getattr(imported, name)
|
|
106
|
+
if not isinstance(found, Dispatch) and callable(found):
|
|
107
|
+
found = found()
|
|
108
|
+
except (PluginError, HostError):
|
|
109
|
+
raise
|
|
110
|
+
except Exception as exc:
|
|
111
|
+
raise HostError(
|
|
112
|
+
f"the host {host} cannot be loaded: {type(exc).__name__}: {exc}"
|
|
113
|
+
) from exc
|
|
114
|
+
if not isinstance(found, Dispatch):
|
|
115
|
+
raise HostError(
|
|
116
|
+
f"{host} is not a Dispatch, nor a function that returns one"
|
|
117
|
+
)
|
|
118
|
+
return found
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _named(spec: str, what: str) -> Any:
|
|
122
|
+
"""The object ``<module>:<name>`` names; ``HostError`` when there is none."""
|
|
123
|
+
module, _, name = spec.partition(":")
|
|
124
|
+
if not module or not name:
|
|
125
|
+
raise HostError(f'{what} is "<module>:<name>"; got {spec!r}')
|
|
126
|
+
try:
|
|
127
|
+
return getattr(importlib.import_module(module), name)
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
raise HostError(
|
|
130
|
+
f"{what} {spec} cannot be loaded: {type(exc).__name__}: {exc}"
|
|
131
|
+
) from exc
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def call(dispatch: Dispatch, tool: str, words: Sequence[str], made: str | None) -> int:
|
|
135
|
+
"""Make one call from the words of a command line and print its answer.
|
|
136
|
+
Returns 0 when it went well, 1 when it was refused, 2 when the words
|
|
137
|
+
are no call."""
|
|
138
|
+
try:
|
|
139
|
+
arguments = command.arguments(words)
|
|
140
|
+
except DispatchError as exc:
|
|
141
|
+
print(exc.render(), file=sys.stderr)
|
|
142
|
+
return 2
|
|
143
|
+
if tool not in dispatch.registry.tools:
|
|
144
|
+
print(
|
|
145
|
+
f"this host has no tool {tool!r}; its tools are "
|
|
146
|
+
+ ", ".join(dispatch.registry.tools),
|
|
147
|
+
file=sys.stderr,
|
|
148
|
+
)
|
|
149
|
+
return 2
|
|
150
|
+
make = _named(made, "call") if made else None
|
|
151
|
+
|
|
152
|
+
def run(bound: Bound) -> str:
|
|
153
|
+
"""One call with what the host hands to it; inside its context, if
|
|
154
|
+
that is one, so that a refusal passes through it on the way out."""
|
|
155
|
+
if make is None:
|
|
156
|
+
return bound.run(None)
|
|
157
|
+
try:
|
|
158
|
+
handed = make()
|
|
159
|
+
except Exception as exc:
|
|
160
|
+
raise HostError(
|
|
161
|
+
f"call {made} cannot be made: {type(exc).__name__}: {exc}"
|
|
162
|
+
) from exc
|
|
163
|
+
if hasattr(handed, "__enter__") and hasattr(handed, "__exit__"):
|
|
164
|
+
with handed as inside:
|
|
165
|
+
return bound.run(inside)
|
|
166
|
+
return bound.run(handed)
|
|
167
|
+
|
|
168
|
+
try:
|
|
169
|
+
said, well = command.outcome(dispatch.registry, tool, arguments, run)
|
|
170
|
+
except HostError:
|
|
171
|
+
raise
|
|
172
|
+
except Exception as exc:
|
|
173
|
+
# what an action raised that is no refusal of its own
|
|
174
|
+
print(f"the call failed: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
175
|
+
if not made:
|
|
176
|
+
print(
|
|
177
|
+
"hint: the action got `None` as `call`. A host says what its"
|
|
178
|
+
' actions get: call = "<module>:<name>" under [tool.mcp-dispatch]'
|
|
179
|
+
" in pyproject.toml, or --call",
|
|
180
|
+
file=sys.stderr,
|
|
181
|
+
)
|
|
182
|
+
return 1
|
|
183
|
+
print(said)
|
|
184
|
+
return 0 if well else 1
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
188
|
+
parser = argparse.ArgumentParser(
|
|
189
|
+
prog="mcp-dispatch",
|
|
190
|
+
description="A few tools, paths behind them, plugins that publish"
|
|
191
|
+
" actions and skills. An assistant that builds on it starts with:"
|
|
192
|
+
" mcp-dispatch guide",
|
|
193
|
+
)
|
|
194
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
195
|
+
one = sub.add_parser("guide", help="how to build on mcp-dispatch")
|
|
196
|
+
one.add_argument("which", nargs="?", default="plugin", choices=GUIDES)
|
|
197
|
+
for name, text in (
|
|
198
|
+
("check", "report everything that is wrong with what an assistant reads"),
|
|
199
|
+
("update", "write the generated files: skills/index.json, the contract"),
|
|
200
|
+
("help", "print what a path ending in ? answers"),
|
|
201
|
+
):
|
|
202
|
+
one = sub.add_parser(name, help=text)
|
|
203
|
+
one.add_argument("--host", help='"<module>:<name>" of a Dispatch')
|
|
204
|
+
one.add_argument("--group", help=f"the entry point group (default {GROUP})")
|
|
205
|
+
if name == "help":
|
|
206
|
+
one.add_argument("path", nargs="?", default="")
|
|
207
|
+
else:
|
|
208
|
+
one.add_argument("--contract", help="the file that pins the contract")
|
|
209
|
+
one = sub.add_parser(
|
|
210
|
+
"call",
|
|
211
|
+
help="make a call as an assistant would: <tool> [<path>] [<key>=<value> ...]",
|
|
212
|
+
)
|
|
213
|
+
one.add_argument("--host", help='"<module>:<name>" of a Dispatch')
|
|
214
|
+
one.add_argument("--group", help=f"the entry point group (default {GROUP})")
|
|
215
|
+
one.add_argument(
|
|
216
|
+
"--call", help='"<module>:<name>" of a function: what actions get as `call`'
|
|
217
|
+
)
|
|
218
|
+
one.add_argument("tool", help="the tool the call goes through, e.g. get")
|
|
219
|
+
one.add_argument(
|
|
220
|
+
"words",
|
|
221
|
+
nargs="*",
|
|
222
|
+
help="the path and key=value arguments, or the call's JSON object",
|
|
223
|
+
)
|
|
224
|
+
args = parser.parse_args(argv)
|
|
225
|
+
if args.command == "guide":
|
|
226
|
+
print(guide(args.which))
|
|
227
|
+
return 0
|
|
228
|
+
|
|
229
|
+
found = settings()
|
|
230
|
+
try:
|
|
231
|
+
dispatch = load(
|
|
232
|
+
args.host or found.get("host"), args.group or found.get("group") or GROUP
|
|
233
|
+
)
|
|
234
|
+
except (PluginError, HostError) as exc:
|
|
235
|
+
# each says what cannot be loaded and why
|
|
236
|
+
print(exc, file=sys.stderr)
|
|
237
|
+
return 1
|
|
238
|
+
if args.command == "help":
|
|
239
|
+
try:
|
|
240
|
+
print(dispatch.registry.help(args.path.rstrip("?")))
|
|
241
|
+
except DispatchError as exc:
|
|
242
|
+
print(exc.render(), file=sys.stderr)
|
|
243
|
+
return 1
|
|
244
|
+
return 0
|
|
245
|
+
if args.command == "call":
|
|
246
|
+
try:
|
|
247
|
+
return call(dispatch, args.tool, args.words, args.call or found.get("call"))
|
|
248
|
+
except HostError as exc:
|
|
249
|
+
print(exc, file=sys.stderr)
|
|
250
|
+
return 1
|
|
251
|
+
pinned = args.contract or found.get("contract")
|
|
252
|
+
contract = Path(pinned) if pinned else None
|
|
253
|
+
if not checks.plugins(dispatch.registry):
|
|
254
|
+
# before anything is written or compared: a contract pinned here
|
|
255
|
+
# would be emptied, and its difference would hide what is wrong
|
|
256
|
+
print(checks.nothing_found(dispatch))
|
|
257
|
+
return 1
|
|
258
|
+
if args.command == "update":
|
|
259
|
+
try:
|
|
260
|
+
for line in checks.update(dispatch, contract=contract):
|
|
261
|
+
print(line)
|
|
262
|
+
except ValueError as exc:
|
|
263
|
+
print(f"nothing was written:\n{exc}", file=sys.stderr)
|
|
264
|
+
return 1
|
|
265
|
+
wrong = checks.problems(dispatch, contract=contract)
|
|
266
|
+
for line in wrong:
|
|
267
|
+
print(line)
|
|
268
|
+
if wrong:
|
|
269
|
+
print(f"{len(wrong)} to fix; `mcp-dispatch guide` says how each is meant")
|
|
270
|
+
return 1
|
|
271
|
+
print(checks.summary(dispatch))
|
|
272
|
+
return 0
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
if __name__ == "__main__":
|
|
276
|
+
raise SystemExit(main())
|