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,59 @@
1
+ """A few tools, paths behind them, plugins that publish actions and skills.
2
+
3
+ A plugin author needs :class:`Plugin`, :func:`action`, :func:`searches`, the
4
+ names of the tools and :class:`DispatchError`. A host needs :class:`Dispatch`.
5
+ An assistant that builds on this starts with the guide: ``mcp-dispatch guide``.
6
+ """
7
+
8
+ from mcp_dispatch.dispatch import INITIAL_LIMIT, SKILL_SEARCH, Dispatch
9
+ from mcp_dispatch.errors import BAD_INPUT, NOT_FOUND, DispatchError, PluginError
10
+ from mcp_dispatch.registry import (
11
+ GROUP,
12
+ Action,
13
+ Bound,
14
+ Help,
15
+ Registry,
16
+ build_registry,
17
+ )
18
+ from mcp_dispatch.skills import Skill
19
+ from mcp_dispatch.tags import (
20
+ CREATE,
21
+ DESTROY,
22
+ GET,
23
+ SEARCH,
24
+ SHARE,
25
+ Plugin,
26
+ Tool,
27
+ action,
28
+ searches,
29
+ standard_tools,
30
+ )
31
+
32
+ __version__ = "0.1.1"
33
+
34
+ __all__ = [
35
+ "BAD_INPUT",
36
+ "CREATE",
37
+ "DESTROY",
38
+ "GET",
39
+ "GROUP",
40
+ "INITIAL_LIMIT",
41
+ "NOT_FOUND",
42
+ "SEARCH",
43
+ "SHARE",
44
+ "SKILL_SEARCH",
45
+ "Action",
46
+ "Bound",
47
+ "Dispatch",
48
+ "DispatchError",
49
+ "Help",
50
+ "Plugin",
51
+ "PluginError",
52
+ "Registry",
53
+ "Skill",
54
+ "Tool",
55
+ "action",
56
+ "build_registry",
57
+ "searches",
58
+ "standard_tools",
59
+ ]
@@ -0,0 +1,3 @@
1
+ from mcp_dispatch.cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,102 @@
1
+ # Set up a host for mcp-dispatch
2
+
3
+ A host is the program an assistant connects to. It names the tools, finds the plugins, says what an assistant is told first, and serves. The plugins do the rest (`mcp-dispatch guide`).
4
+
5
+ ```python
6
+ # src/my_package/host.py
7
+ from mcp_dispatch import SKILL_SEARCH, Dispatch
8
+
9
+
10
+ def dispatch() -> Dispatch:
11
+ d = Dispatch() # the standard tools and the search
12
+ d.find_plugins() # every plugin installed under "mcp_dispatch.plugins"
13
+ d.add_initial_message("You keep the lab's bookshelf for its people.")
14
+ d.add_initial_message(SKILL_SEARCH)
15
+ return d
16
+
17
+
18
+ if __name__ == "__main__":
19
+ dispatch().server("bookshelf").run()
20
+ ```
21
+
22
+ ```toml
23
+ # pyproject.toml
24
+ [project]
25
+ dependencies = ["mcp-dispatch[mcp]"]
26
+
27
+ [tool.mcp-dispatch]
28
+ host = "my_package.host:dispatch" # so that check, update and help look at this host
29
+ ```
30
+
31
+ A project that has no host of its own and lists its plugins under another entry point group says so in the same table: `group = "my_host.plugins"`.
32
+
33
+ ## The tools
34
+
35
+ `Dispatch()` has the standard set, one tool per kind of change, so that a client's permission per tool is a switch per risk: `get` reads, `create` writes, `destroy` removes for good, `share` gives access. The `search` tool is always there and is not listed by the host.
36
+
37
+ - Your own words for a standard tool: `Dispatch(standard_tools({"get": "Read the shelf. ..."}))`. A description is read by the assistant before every first call: say what the tool is for and show one call.
38
+ - Your own words for the search: `Dispatch(search="Search the books. ...")`.
39
+ - Your own set: `Dispatch([Tool("read", "...", writes=False), Tool("write", "...")])`. `writes=False` marks a tool that changes nothing; `destructive=True` one whose actions cannot be undone, which a client may ask the person about. One tool must only read. A plugin is written for the names of the tools: with your own set, only plugins tagged for it load.
40
+
41
+ ## The plugins
42
+
43
+ `find_plugins()` adds every plugin installed under the entry point group (`Dispatch(group="my_host.plugins")` for a group of your own). `add("shelf", Shelf)` adds one class by hand. A plugin that cannot be loaded, or that is tagged for a tool you do not have, stops the start: a host that came up without it would answer "not installed" to calls that worked the day before.
44
+
45
+ ## What an assistant is told first
46
+
47
+ The initial message, the tools' descriptions and their schemas are read in every conversation, before the first call. Keep them small; `mcp-dispatch check` prints their size.
48
+
49
+ - `add_initial_message(text)` adds a part; the parts are joined in the order added. The whole has a limit of 2000 characters (`Dispatch(initial_limit=...)`).
50
+ - Say who the assistant works for, what the first call is if there is one, and how to find out more. `SKILL_SEARCH` is the line for the last: it names the search for how-to guides.
51
+ - A skill that every conversation needs: `add_initial_message(d.skill("lend-a-book"))`. One or two at most; every other skill is found when it is needed.
52
+ - What depends on who is calling (their own notes, the one or two skills that fit their role) cannot be in the initial message: a server has one. Put it in the answer of an action, and name that action in the initial message as the first call. Such an action can pick skills with `self.registry.best_skills("<what this caller does>", limit=2)`.
53
+ - If one call has to come first, say so in the search's description as well: `Dispatch(search="Search the books, after the start call has begun the conversation. ...")`, with the start call written out as your first message writes it. A tool called `search` is an obvious first call. On a host whose first message named its start call, conversations that began with one plain request began with the search in a third of the cases, and in none once the search's description said what comes before it.
54
+ - Every part here is a text an assistant acts on. Change one at a time and try the change with a real assistant before you ship it: `mcp_dispatch.trials.run_session` runs one that has your server's tools and nothing else, and reads what it called from the transcript.
55
+
56
+ ## What an action gets as `call`
57
+
58
+ `server(name, call=make)` calls `make(ctx)` for every call and passes the result to the action as its first argument; `ctx` is the MCP context of the request. Left out, actions get `None`.
59
+
60
+ ```python
61
+ store = Store("books.db")
62
+ dispatch().server("bookshelf", call=lambda ctx: store).run()
63
+ ```
64
+
65
+ The server runs each call in a worker thread. An action's `DispatchError` reaches the assistant as `[error:Code] message` with a `hint:` line; any other exception is logged and answered as `[error:Internal]` without details.
66
+
67
+ ## A server of your own
68
+
69
+ A host with its own sign-in, transactions or limits builds its FastMCP server itself and mounts the tools:
70
+
71
+ ```python
72
+ mcp = FastMCP("notes", instructions=d.initial_message) # and your own sign-in, routes, settings
73
+
74
+ async def run(ctx, bound):
75
+ # one call: open the transaction (bound.tool.writes says of which kind),
76
+ # build what the actions get as `call`, run, commit or roll back
77
+ return await in_a_transaction(ctx, lambda call: bound.run(call))
78
+
79
+ d.mount(mcp, run)
80
+ ```
81
+
82
+ `bound.action.path` names the call for a log; `bound.params` are its checked arguments. Let an action's `DispatchError` pass through `run`, so that your transaction rolls back: it reaches the assistant as `[error:Code] message` all the same. Any other exception is yours to log and to answer.
83
+
84
+ ## From a command line
85
+
86
+ Every action can be called without a client, with the same tool, path and arguments:
87
+
88
+ ```
89
+ uv run mcp-dispatch call create shelf/add title=Dune author="Frank Herbert"
90
+ uv run mcp-dispatch call search q=herbert t=book
91
+ uv run mcp-dispatch call create '{"path": "shelf/add", "title": "Dune"}'
92
+ ```
93
+
94
+ A value is passed as its text and read by the action's type hints. What the actions get as `call` there is what a function of yours returns, named in the same table: `call = "my_package.host:store"`. It is called once for each call that is made. If it returns a context manager, that is entered for the one call and left after it: open a transaction there, commit it when the block ends, and roll it back when it ends with an exception, which is how a refused call leaves it. The command returns 0 when the call went well and 1 when it was refused.
95
+
96
+ ## Check
97
+
98
+ ```
99
+ uv run mcp-dispatch check
100
+ ```
101
+
102
+ With `[tool.mcp-dispatch] host = ...` it checks this host: every plugin's docstrings, skills and index, and the size of the initial message. `contract = "tests/contract.json"` in the same table pins the paths and their arguments in a file: the check fails when they differ, and `uv run mcp-dispatch update` writes the file again after a change that is meant.
@@ -0,0 +1,222 @@
1
+ # Write a plugin for mcp-dispatch
2
+
3
+ mcp-dispatch puts a few tools in front of an assistant: `get`, `create`, `destroy`, `share` and `search`. Behind the first four are paths, `<package>/<action>`. A plugin is a Python class; its tagged methods are the actions of one package.
4
+
5
+ The assistant never sees your code. It sees help made from your signatures and docstrings, and the how-to guides (skills) you ship. So a docstring is interface text, and a check reads it as strictly as a compiler reads code.
6
+
7
+ - Your job: the class, its tagged methods with type hints and docstrings, the skills, one entry point.
8
+ - The library's job: the tools, checking a call's arguments against your type hints, help (a path ending in `?`), several calls in one (`{"calls": [...]}`), the search tool, listing and reading skills.
9
+
10
+ Run the check after every step and do not stop before it prints `ok`:
11
+
12
+ ```
13
+ uv run mcp-dispatch check
14
+ ```
15
+
16
+ Each line it prints names one thing to change.
17
+
18
+ ## 1. The class and its entry point
19
+
20
+ ```python
21
+ # src/my_package/plugin.py
22
+ from typing import Any, Literal
23
+
24
+ from mcp_dispatch import CREATE, DispatchError, Plugin, action, searches
25
+
26
+
27
+ class Shelf(Plugin):
28
+ """Books on a shelf: what is there and who has borrowed one."""
29
+ ```
30
+
31
+ The first line of the class docstring says what the package is for.
32
+
33
+ ```toml
34
+ # pyproject.toml
35
+ [project.entry-points."mcp_dispatch.plugins"]
36
+ shelf = "my_package.plugin:Shelf"
37
+ ```
38
+
39
+ The entry point's name is the package, the first part of every path (`shelf/add`): lower case, a-z 0-9 _ -. If the host you write for has its own entry point group, its instructions name it. After a change to `pyproject.toml`, `uv run` installs the project again by itself; with another tool, reinstall the project, or the entry point is not found.
40
+
41
+ ## 2. An action
42
+
43
+ ```python
44
+ @action(CREATE)
45
+ def add(
46
+ self,
47
+ call: Any,
48
+ *,
49
+ title: str,
50
+ author: str | None = None,
51
+ state: Literal["new", "used"] = "used",
52
+ ) -> str:
53
+ """Put a book on the shelf.
54
+
55
+ Args:
56
+ title: The book's title, e.g. "Dune".
57
+ author: Who wrote it, e.g. "Frank Herbert".
58
+ state: The condition it is in.
59
+
60
+ Returns:
61
+ The id of the book, for `shelf/lend`.
62
+
63
+ Example:
64
+ create {"path": "shelf/add", "title": "Dune", "author": "Frank Herbert"}
65
+ """
66
+ # internal notes go here, in a comment: help never reads comments
67
+ book = call.add_book(title, author, state) # `call` is the host's
68
+ return f'{book} "{title}" is on the shelf'
69
+
70
+ @action(CREATE)
71
+ def lend(self, call: Any, *, book: str, to: str) -> str:
72
+ """Record that someone has borrowed a book.
73
+
74
+ Args:
75
+ book: The book's id, as the search shows it, e.g. "b12".
76
+ to: Who borrows it, e.g. "mira".
77
+
78
+ Returns:
79
+ Who has the book now.
80
+
81
+ Example:
82
+ create {"path": "shelf/lend", "book": "b12", "to": "mira"}
83
+ """
84
+ if not call.has_book(book):
85
+ raise DispatchError(
86
+ "NotFound",
87
+ f"no book has the id {book!r}",
88
+ hint='search {"q": "<a word of its title>", "t": "book"} finds it',
89
+ )
90
+ call.lend_book(book, to)
91
+ return f"{to} has {book}"
92
+ ```
93
+
94
+ The tag names the tool the action is called through:
95
+
96
+ | Tag | For an action that |
97
+ |---|---|
98
+ | `GET` | only reads |
99
+ | `CREATE` | adds something or changes it, and can be undone or corrected |
100
+ | `DESTROY` | removes something for good |
101
+ | `SHARE` | gives someone access, changes it or takes it away |
102
+
103
+ The question for `DESTROY` and `SHARE` is "can it be undone?", not "does it delete?". A tag that names a tool the host does not have stops the host from starting.
104
+
105
+ The shape:
106
+
107
+ - `def name(self, call, *, <arguments>) -> str`. `call` is what the host hands to every call (for example its connection and who is calling); the host's own instructions say what it holds. It is never listed under `Args:`.
108
+ - Every other argument is keyword-only, has a type hint and is one JSON key of the call. None may be called `path` or `calls`.
109
+ - The type hints are the validation. `Literal["new", "used"]` for a fixed set of values: the help lists them and anything else is refused before your code runs. `int`, `bool`, `list[str]`, `str | None = None` work as they read.
110
+ - Return text. Keep it compact, give the ids the assistant needs for its next call, and where one call usually follows, end with a line `next: <tool> {json}`.
111
+ - To refuse a call, raise `DispatchError(code, message, hint=...)` as `lend` does. The hint names the call that helps, as it is sent. Codes: `NotFound`, `BadInput`, `Forbidden`, `Conflict`.
112
+ - One action does one thing to one thing. For several, the assistant sends `{"calls": [{...}, {...}]}` and each runs on its own: do not add list forms of your arguments for that.
113
+ - One plugin object serves every caller: keep nothing about a call on `self`.
114
+ - Names are short where a short one is plain, and there is one name per thing, with no aliases: `t` for a kind, `q` for what to look for.
115
+
116
+ The docstring, Google style, written for an assistant that has never seen the code:
117
+
118
+ - First line: what the action does, at most 100 characters.
119
+ - `Args:` one entry per argument, in the order of the signature. Each shows an example value, written `e.g. "Dune"`. An argument with a `Literal` or a `bool` hint needs none.
120
+ - `Returns:` what comes back.
121
+ - `Example:` exactly one call, written `<tool> {"path": "<package>/<action>", ...}` with `path` first. It must be a call the action accepts.
122
+ - No file, table or module names. At most 2000 characters; what an assistant needs only sometimes goes into a skill.
123
+ - If your linter wants every parameter documented (ruff `D417`), switch that rule off for plugin modules: `call` is not documented.
124
+
125
+ ## 3. The search, if the package has things to find
126
+
127
+ There is one search, the tool `search`, and it takes no path. A package takes part with one method:
128
+
129
+ ```python
130
+ @searches(kinds=["book"])
131
+ def find(self, call: Any, *, q: str, limit: int = 10) -> str:
132
+ """Find books by a word of their title or author.
133
+
134
+ Args:
135
+ q: What to look for, e.g. "herbert".
136
+ limit: How many at most, e.g. 5.
137
+
138
+ Returns:
139
+ One line per book: its id, title and author.
140
+
141
+ Example:
142
+ search {"q": "herbert", "t": "book"}
143
+ """
144
+ return "\n".join(call.find_books(q)[:limit]) or "No book matches."
145
+ ```
146
+
147
+ `kinds` names the kinds it finds. A search with `"t": "book"` goes to this method; a search without `t` asks every package. The method is not a path of its own and is documented like an action.
148
+
149
+ ## 4. Skills
150
+
151
+ A skill is a how-to guide: which calls to make for a task, in which order, and why. Write one when a task takes more than one call, or a decision that no single docstring can carry. It is a markdown file in `skills/` beside the module that defines the plugin class, here `src/my_package/skills/lend-a-book.md`. Its first line is the `---` that opens the header:
152
+
153
+ ```markdown
154
+ ---
155
+ title: Lend a book
156
+ summary: record who borrowed a book, and add the book first if it is new
157
+ answers:
158
+ - how do I lend a book to someone?
159
+ - someone took a book home, what do I record?
160
+ - the book is not on the shelf yet, what now?
161
+ ---
162
+
163
+ # Lend a book
164
+
165
+ 1. Find the book: search {"q": "dune", "t": "book"}
166
+ 2. If it is not there, add it first: create {"path": "shelf/add", "title": "Dune"}
167
+ 3. Lend it: create {"path": "shelf/lend", "book": "<the book's id>", "to": "mira"}
168
+ ```
169
+
170
+ - The file's name is the skill's name: lower case words with hyphens.
171
+ - The header has `title` and `summary`, one line each, and `answers`: the questions the skill answers, at least one and better three to six, in the words of someone who does not know the answer yet. The search matches a question against these three, so they decide whether the skill is found.
172
+ - No argument lists: the help has them. Say which calls, in which order, and why.
173
+ - Write every example call as `<tool> {json}`, the JSON exactly as it is sent: each is read as JSON and checked against the signatures. A blank for the assistant to fill is a string, quotes included: `"book": "<the book's id>"`. A number or a yes/no has no blank: write a real value, `"count": 5`, and say in the sentence what it stands for. `"count": <how many>` is not JSON and fails the check.
174
+ - After adding or changing a skill, run `uv run mcp-dispatch update`. It writes `skills/index.json`, which a running host reads in place of the files. Commit it. A host refuses to start when the index does not list the files that are there.
175
+
176
+ An assistant finds a skill with `search {"q": "lend a book", "t": "skill"}` and reads it with `get {"path": "skill/get", "name": "lend-a-book"}`.
177
+
178
+ ## 5. Check, update, read it as the assistant will
179
+
180
+ ```
181
+ uv run mcp-dispatch update # writes skills/index.json, then checks
182
+ uv run mcp-dispatch check # checks only; run it in CI
183
+ uv run mcp-dispatch help shelf/ # what "shelf/?" answers: the actions
184
+ uv run mcp-dispatch help shelf/add # what "shelf/add?" answers
185
+ ```
186
+
187
+ Read the help once as if you had never seen the code: it is all the assistant has.
188
+
189
+ A test calls an action as an assistant does:
190
+
191
+ ```python
192
+ from mcp_dispatch import Bound, Registry
193
+
194
+ from my_package.plugin import Shelf
195
+
196
+
197
+ class Books: # stands in for what the host hands to every call
198
+ def add_book(self, title, author, state):
199
+ return "b12"
200
+
201
+
202
+ registry = Registry(skills_from="files")
203
+ registry.register("shelf", Shelf)
204
+ found = registry.resolve("create", {"path": "shelf/add", "title": "Dune"})
205
+ assert isinstance(found, Bound)
206
+ assert "Dune" in found.run(Books()) # the argument is what the action gets as `call`
207
+ ```
208
+
209
+ and one test keeps the check in the suite:
210
+
211
+ ```python
212
+ from mcp_dispatch import Dispatch
213
+ from mcp_dispatch.check import problems
214
+
215
+
216
+ def test_everything_an_assistant_reads_is_in_order():
217
+ dispatch = Dispatch(skills_from="files") # the skill files, as the check reads them
218
+ assert dispatch.find_plugins(), "no plugin was found: is its entry point listed?"
219
+ assert problems(dispatch) == []
220
+ ```
221
+
222
+ Setting up a host (the tools, the first message, the server): `uv run mcp-dispatch guide host`.