devstuff 2.14.0__py3-none-any.whl → 2.16.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.
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import json
3
4
  import subprocess
4
5
  from collections.abc import Callable
5
6
  from typing import Any
@@ -9,6 +10,12 @@ from dev_setup.agent.config import AgentConfig
9
10
  from dev_setup.agent.sandbox import SandboxError, Workspace
10
11
 
11
12
 
13
+ class InstallFailed(SandboxError):
14
+ """An installer ran and failed. A subclass so the local agent handles it as it always did;
15
+ the MCP server tells it apart from "unknown tool" to add the FR-13 hint (it cannot answer a
16
+ password prompt, so the client has to be told where to run the install instead)."""
17
+
18
+
12
19
  def _tool_line(tool) -> str:
13
20
  state = "installed" if tool.is_installed() else "available"
14
21
  return f"{tool.key} [{state}] {tool.description}"
@@ -58,6 +65,69 @@ def tool_info(ws: Workspace, config: AgentConfig, args: dict[str, Any]) -> str:
58
65
  return "\n".join(lines)
59
66
 
60
67
 
68
+ def _string_list(args: dict[str, Any], name: str) -> list[str]:
69
+ """A list-of-strings argument. `bind()` checks names, not types, so this is the type check."""
70
+ value = args.get(name, [])
71
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
72
+ # A bare string must be refused, not iterated: "eslint" would read as six one-letter keys.
73
+ raise SandboxError(f"'{name}' must be a list of strings, e.g. [\"uv\", \"nvm\"]")
74
+ return value
75
+
76
+
77
+ def outdated(ws: Workspace, config: AgentConfig, args: dict[str, Any]) -> str:
78
+ """`devstuff outdated --json`: the same rows, built by the same function (spec FR-9).
79
+
80
+ `unknown` and `unsupported` rows are returned as such and never as `current` -- that honesty
81
+ is the point of the command, and it is decided in `updates.classify`, not here.
82
+ """
83
+ from dev_setup.updates import State, build_rows
84
+
85
+ updates_only = args.get("updates_only", False)
86
+ if not isinstance(updates_only, bool):
87
+ raise SandboxError("'updates_only' must be true or false")
88
+
89
+ keys = _string_list(args, "packages")
90
+ tool_registry.init()
91
+ named = None
92
+ if keys:
93
+ named = []
94
+ for key in keys:
95
+ tool = tool_registry.get(key)
96
+ if tool is None:
97
+ raise SandboxError(f"unknown catalog tool '{key}'; try search_catalog first")
98
+ named.append(tool)
99
+
100
+ rows = build_rows(named)
101
+ if updates_only:
102
+ rows = [r for r in rows if r.state is State.OUTDATED]
103
+ return json.dumps([r.to_json() for r in rows], indent=2)
104
+
105
+
106
+ def profile_diff(ws: Workspace, config: AgentConfig, args: dict[str, Any]) -> str:
107
+ """`devstuff profile diff @name --json`, for a bundle that ships with devstuff (spec FR-10).
108
+
109
+ Only a bundle name is accepted. A path would let a caller read any YAML file the user can read,
110
+ and `bundles.resolve` matches the name against a directory listing rather than building a path
111
+ from it, so there is nothing to traverse.
112
+ """
113
+ from dev_setup import bundles, profile, snapshot
114
+
115
+ name = args["profile"]
116
+ if not isinstance(name, str) or not bundles.is_bundle(name):
117
+ raise SandboxError(
118
+ f"'profile' must be a bundle name such as @devops, not a file path. "
119
+ f"Bundles: {', '.join(f'@{n}' for n in bundles.names())}"
120
+ )
121
+ try:
122
+ wanted = bundles.resolve(name)
123
+ except profile.ProfileError as exc:
124
+ raise SandboxError(str(exc)) from exc
125
+
126
+ tool_registry.init()
127
+ rows = profile.sort_diff_rows(profile.compare(wanted, snapshot.machine_facts(wanted)))
128
+ return json.dumps([r.to_json() for r in rows], indent=2)
129
+
130
+
61
131
  def install_tool(ws: Workspace, config: AgentConfig, args: dict[str, Any]) -> str:
62
132
  tool_registry.init()
63
133
  tool = tool_registry.get(args["key"])
@@ -77,7 +147,7 @@ def install_tool(ws: Workspace, config: AgentConfig, args: dict[str, Any]) -> st
77
147
  try:
78
148
  version = tool.install()
79
149
  except (subprocess.CalledProcessError, RuntimeError) as exc:
80
- raise SandboxError(f"installing {tool.key} failed: {exc}") from exc
150
+ raise InstallFailed(f"installing {tool.key} failed: {exc}") from exc
81
151
 
82
152
  return f"Installed {tool.name}" + (f" ({version})" if version else "")
83
153
 
@@ -117,6 +187,8 @@ _BRIDGES: dict[str, Bridge] = {
117
187
  "list_tools": list_tools,
118
188
  "search_catalog": search_catalog,
119
189
  "tool_info": tool_info,
190
+ "outdated": outdated,
191
+ "profile_diff": profile_diff,
120
192
  "install_tool": install_tool,
121
193
  }
122
194
 
@@ -17,7 +17,7 @@ VERSION = 1
17
17
  VALID_KEY = re.compile(r"^[a-z][a-z0-9_]*$")
18
18
 
19
19
  IMPLS = {"primitive", "catalog", "function"}
20
- PARAM_TYPES = {"string", "integer", "number", "boolean"}
20
+ PARAM_TYPES = {"string", "integer", "number", "boolean", "array"}
21
21
 
22
22
  SUPPORTED_TOP_FIELDS = {"version", "expose_functions", "exclude_functions", "tools"}
23
23
  SUPPORTED_FIELDS = {"name", "description", "impl", "target", "mutating", "params"}
@@ -17,6 +17,10 @@ class AgentParam:
17
17
 
18
18
  def to_schema(self) -> dict[str, Any]:
19
19
  schema: dict[str, Any] = {"type": self.type}
20
+ if self.type == "array":
21
+ # JSON Schema wants `items`, and a bare array tells a model nothing about what goes
22
+ # in it. Every array parameter is a list of strings: none needs another element type.
23
+ schema["items"] = {"type": "string"}
20
24
  if self.description:
21
25
  schema["description"] = self.description
22
26
  if self.enum:
@@ -86,7 +86,7 @@
86
86
  "description": "Parameter name. Passed to the implementation as a dict key."
87
87
  },
88
88
  "type": {
89
- "enum": ["string", "integer", "number", "boolean"],
89
+ "enum": ["string", "integer", "number", "boolean", "array"],
90
90
  "default": "string",
91
91
  "description": "JSON Schema type advertised to the model."
92
92
  },
@@ -129,6 +129,43 @@ tools:
129
129
  description: Catalog key, e.g. "uv" or "nvm".
130
130
  required: true
131
131
 
132
+ outdated:
133
+ name: Devstuff Outdated
134
+ description: >-
135
+ Report which installed devstuff tools have a newer version available. Returns a
136
+ JSON array with one row per tool: state is "outdated", "current", "unknown" (a
137
+ check exists but could not answer, e.g. offline), "unsupported" (this install
138
+ type has no way to check) or "not-installed". Only "current" means up to date --
139
+ never read "unknown" or "unsupported" as current. Changes nothing.
140
+ impl: catalog
141
+ target: outdated
142
+ mutating: false
143
+ params:
144
+ - name: packages
145
+ type: array
146
+ description: Catalog keys to check, e.g. ["uv", "nvm"]. Omit to check every installed tool.
147
+ required: false
148
+ - name: updates_only
149
+ type: boolean
150
+ description: Return only the tools that have an update available.
151
+ required: false
152
+ default: false
153
+
154
+ profile_diff:
155
+ name: Devstuff Profile Diff
156
+ description: >-
157
+ Compare this machine to a profile that ships with devstuff and return a JSON array,
158
+ one row per tool: "ok", "missing", "drift", "unverifiable", "unpinnable",
159
+ "unknown-key" or "extra". Only "ok" means it matches. Changes nothing.
160
+ impl: catalog
161
+ target: profile_diff
162
+ mutating: false
163
+ params:
164
+ - name: profile
165
+ type: string
166
+ description: Name of a bundled profile, with the leading @, e.g. "@devops" or "@python".
167
+ required: true
168
+
132
169
  install_tool:
133
170
  name: Install Devstuff Tool
134
171
  description: >-
dev_setup/cli.py CHANGED
@@ -33,6 +33,7 @@ def _register_commands() -> None:
33
33
  from dev_setup.commands.install_cmd import install_cmd
34
34
  from dev_setup.commands.links_cmd import links_cmd
35
35
  from dev_setup.commands.list_cmd import list_cmd
36
+ from dev_setup.commands.mcp_cmd import mcp_cmd
36
37
  from dev_setup.commands.outdated_cmd import outdated_cmd
37
38
  from dev_setup.commands.profile_cmd import profile_cmd
38
39
  from dev_setup.commands.remove_cmd import remove_cmd
@@ -61,6 +62,7 @@ def _register_commands() -> None:
61
62
  cli.add_command(links_cmd, "link")
62
63
  cli.add_command(skills_cmd, "skills")
63
64
  cli.add_command(agent_cmd, "agent")
65
+ cli.add_command(mcp_cmd, "mcp")
64
66
 
65
67
  _add_verbose_option(cli)
66
68
 
@@ -0,0 +1,90 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ import click
6
+
7
+ from dev_setup.catalog import CatalogError
8
+ from dev_setup.mcp import process, stdio
9
+ from dev_setup.mcp.core import Dispatcher, Toolbox
10
+
11
+
12
+ def _warn(message: str) -> None:
13
+ click.echo(f"devstuff mcp: {message}", err=True)
14
+
15
+
16
+ def _toolbox(allow_install: bool, allow_functions: bool) -> Toolbox:
17
+ from dev_setup.agent import registry as agent_registry
18
+
19
+ return Toolbox.from_agent(
20
+ agent_registry.build(), allow_install=allow_install, allow_functions=allow_functions, warn=_warn
21
+ )
22
+
23
+
24
+ def _banner(box: Toolbox, allow_install: bool, allow_functions: bool) -> str:
25
+ gated = [
26
+ label
27
+ for label, on in (("install_tool", allow_install), ("functions", allow_functions))
28
+ if on
29
+ ]
30
+ return (
31
+ f"devstuff mcp: serving {len(box.names())} tools on stdio "
32
+ f"({'+ ' + ', '.join(gated) if gated else 'read-only; install_tool and functions are off'})"
33
+ )
34
+
35
+
36
+ @click.command("mcp")
37
+ @click.option(
38
+ "--allow-install", is_flag=True,
39
+ help="Expose install_tool, which installs a catalog tool as you. Off by default: absent and refused.",
40
+ )
41
+ @click.option(
42
+ "--allow-functions", is_flag=True,
43
+ help="Expose every `type: script` function (fn_<key>). Off by default: absent and refused.",
44
+ )
45
+ @click.option(
46
+ "--list-tools", "list_tools", is_flag=True,
47
+ help="Print the tools these flags would expose, and which gate each sits behind. Starts nothing.",
48
+ )
49
+ def mcp_cmd(allow_install: bool, allow_functions: bool, list_tools: bool) -> None:
50
+ """Serve devstuff's tools to an MCP client over stdio.
51
+
52
+ Reads JSON-RPC from stdin and answers on stdout — it is meant to be started by a client
53
+ (Claude Code, Claude Desktop), not by hand. Only read-only tools are exposed unless a flag
54
+ says otherwise, and a tool that is off does not merely hide: a call naming it is refused.
55
+
56
+ The server has no terminal. An installer that needs a password fails at once rather than
57
+ waiting for one nobody can type; run `devstuff install <key>` in a terminal for those.
58
+ """
59
+ if list_tools:
60
+ _print_tools(_load(allow_install, allow_functions))
61
+ return
62
+
63
+ # Detach first, before the fd move and before anything that could run an installer (FR-11a).
64
+ # Under a shell this forks and the original process becomes a supervisor that never returns.
65
+ process.detach()
66
+ try:
67
+ process.require_no_terminal(gated=allow_install or allow_functions, warn=_warn)
68
+ except process.TerminalReachable as exc:
69
+ click.echo(f"error: {exc}", err=True)
70
+ sys.exit(1)
71
+
72
+ box = _load(allow_install, allow_functions)
73
+ click.echo(_banner(box, allow_install, allow_functions), err=True)
74
+ sys.exit(stdio.run(Dispatcher(box)))
75
+
76
+
77
+ def _load(allow_install: bool, allow_functions: bool) -> Toolbox:
78
+ try:
79
+ return _toolbox(allow_install, allow_functions)
80
+ except CatalogError as exc:
81
+ click.echo(f"error: {exc}", err=True)
82
+ sys.exit(1)
83
+
84
+
85
+ def _print_tools(box: Toolbox) -> None:
86
+ width = max((len(n) for n in box.names()), default=0)
87
+ for name in box.names():
88
+ tool = box.get(name)
89
+ first = (tool.description.splitlines() or [""])[0]
90
+ click.echo(f"{name:<{width}} [{box.gate(name).value}] {first}")
@@ -9,7 +9,7 @@ from rich.markup import escape
9
9
 
10
10
  from dev_setup import registry, ui, verbose
11
11
  from dev_setup.base import Tool
12
- from dev_setup.updates import Row, State, collect_candidates, make_row, sort_rows, summarize
12
+ from dev_setup.updates import Row, State, build_rows, summarize
13
13
 
14
14
  # One glyph + wording per state. `unknown` and `unsupported` deliberately share nothing
15
15
  # with `current`: "could not check" must never read as "up to date" (spec FR-7).
@@ -71,14 +71,8 @@ def outdated_cmd(packages: tuple[str, ...], updates_only: bool, show_all: bool,
71
71
  verbose.step("Checking installed packages for updates...") if interactive else nullcontext()
72
72
  )
73
73
  with progress:
74
- candidates = collect_candidates(named)
74
+ result = build_rows(named)
75
75
 
76
- result = [make_row(tool, status) for tool, status in candidates]
77
- if named is not None:
78
- found = {tool.key for tool, _ in candidates}
79
- result += [make_row(t, None, installed=False) for t in named if t.key not in found]
80
-
81
- result = sort_rows(result)
82
76
  shown = [r for r in result if r.state is State.OUTDATED] if updates_only else result
83
77
 
84
78
  if as_json:
@@ -0,0 +1 @@
1
+ """`devstuff mcp` — devstuff's tools as an MCP / HTTP tool server (docs/specs/mcp)."""
dev_setup/mcp/core.py ADDED
@@ -0,0 +1,443 @@
1
+ """What the MCP server runs, what it will let a client reach, and how it answers (docs/specs/mcp).
2
+
3
+ No sockets, no processes, no file descriptors: a transport hands this module text or a decoded
4
+ frame and gets text or a dict back. That is what lets gating, binding, errors, version
5
+ negotiation and the probe lifecycle be tested with hand-built frames — the reason `profile.py`
6
+ and `apply_plan.py` are built the same way.
7
+
8
+ Three things are decided here and nowhere else:
9
+
10
+ * **What exists** (`Toolbox`): every entry is classified by what it *runs* (FR-1a) and anything
11
+ not exposed is simply absent. Listing and calling read the same object, so there is no second
12
+ path that skips the check (FR-3).
13
+ * **How a call runs** (`Dispatcher.call`): bad arguments and failing bridges become tool errors
14
+ the model can read, never protocol errors (FR-5, FR-6); mutations are serialised and reads are
15
+ never blocked (FR-8); the process-lifetime probe memos are kept honest (FR-8a).
16
+ * **What goes on the wire** (`Dispatcher.handle`): JSON-RPC 2.0 for MCP (FR-15–18).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import re
23
+ import sys
24
+ import threading
25
+ import traceback
26
+ from collections.abc import Callable, Mapping
27
+ from dataclasses import dataclass
28
+ from enum import StrEnum
29
+ from typing import Any
30
+
31
+ from dev_setup import __version__
32
+ from dev_setup.agent import bridges
33
+ from dev_setup.agent.registry import AgentTool
34
+ from dev_setup.agent.sandbox import SandboxError
35
+
36
+ # -- Classification (FR-1a) -----------------------------------------------------------------
37
+
38
+
39
+ class Gate(StrEnum):
40
+ READ_ONLY = "read-only" # always exposed
41
+ INSTALL = "install" # only with --allow-install
42
+ FUNCTION = "function" # only with --allow-functions
43
+ UNCLASSIFIED = "unclassified" # never: an unknown catalog bridge fails closed
44
+ PRIMITIVE = "primitive" # never: workspace tools do not exist on this surface (FR-1)
45
+
46
+
47
+ # One row per bridge in `agent.bridges._BRIDGES`, keyed by *target* — what the entry runs.
48
+ # `test_every_bridge_has_a_gate` fails when a bridge is added without a row, so a new bridge
49
+ # cannot ship without someone deciding which flag, if any, guards it.
50
+ CATALOG_GATES: dict[str, Gate] = {
51
+ "list_tools": Gate.READ_ONLY,
52
+ "search_catalog": Gate.READ_ONLY,
53
+ "tool_info": Gate.READ_ONLY,
54
+ "outdated": Gate.READ_ONLY,
55
+ "profile_diff": Gate.READ_ONLY,
56
+ "install_tool": Gate.INSTALL,
57
+ }
58
+
59
+
60
+ def classify(tool: AgentTool) -> Gate:
61
+ """The gate for one agent-toolbox entry, from `(impl, target)` and nothing else.
62
+
63
+ Never from the key and never from `tool.mutating` alone: both are chosen by the user's
64
+ `agent_tools.yaml`, which can rename `install_tool`, alias it, or label it harmless (F-10a).
65
+ `mutating: true` can only move a read-only entry *into* a gate, never out of one.
66
+ """
67
+ if tool.impl == "primitive":
68
+ return Gate.PRIMITIVE
69
+ if tool.impl == "function":
70
+ return Gate.FUNCTION
71
+ if tool.impl == "catalog":
72
+ gate = CATALOG_GATES.get(tool.target or "", Gate.UNCLASSIFIED)
73
+ if gate is Gate.READ_ONLY and tool.mutating:
74
+ return Gate.FUNCTION
75
+ return gate
76
+ return Gate.UNCLASSIFIED
77
+
78
+
79
+ def is_exposed(gate: Gate, *, allow_install: bool, allow_functions: bool) -> bool:
80
+ """Whether a tool of this class exists for a server started with these flags (FR-3)."""
81
+ if gate is Gate.READ_ONLY:
82
+ return True
83
+ if gate is Gate.INSTALL:
84
+ return allow_install
85
+ if gate is Gate.FUNCTION:
86
+ return allow_functions
87
+ return False
88
+
89
+
90
+ # -- The toolbox (FR-1, FR-16b, FR-16c) ---------------------------------------------------------
91
+
92
+ # The constraint Claude's tool API applies once a client prefixes a name (`mcp__devstuff__<key>`).
93
+ TOOL_NAME = re.compile(r"[a-zA-Z0-9_-]{1,64}")
94
+ # Names the server itself uses. `GET /tools` is an OpenAPI operation named this (FR-22), so a tool
95
+ # with the same key would produce two operations with one operationId.
96
+ RESERVED_NAMES = frozenset({"openai_tool_list"})
97
+
98
+
99
+ class UnknownTool(LookupError):
100
+ """The name is not in the toolbox — never existed, or exists behind a flag that is off.
101
+ The two are deliberately indistinguishable to a caller (FR-3)."""
102
+
103
+
104
+ class Toolbox:
105
+ """The tools a server started with these flags exposes, and the gate each sits behind."""
106
+
107
+ def __init__(self, tools: Mapping[str, AgentTool], gates: Mapping[str, Gate]) -> None:
108
+ self._tools = dict(tools)
109
+ self._gates = dict(gates)
110
+
111
+ @classmethod
112
+ def from_agent(
113
+ cls,
114
+ agent_tools: Mapping[str, AgentTool],
115
+ *,
116
+ allow_install: bool,
117
+ allow_functions: bool,
118
+ warn: Callable[[str], None],
119
+ ) -> Toolbox:
120
+ """Filter the agent's effective toolbox down to what this surface may expose.
121
+
122
+ A tool that is *expected* to be absent (a primitive, a gated tool whose flag is off) is
123
+ dropped silently. One that is absent for a reason the user should know — an entry no
124
+ classification covers, a name a client would reject — is dropped with a warning rather
125
+ than breaking the client's whole `tools/list` (FR-16b).
126
+ """
127
+ tools: dict[str, AgentTool] = {}
128
+ gates: dict[str, Gate] = {}
129
+ for key, tool in agent_tools.items():
130
+ gate = classify(tool)
131
+ if gate is Gate.PRIMITIVE:
132
+ continue
133
+ if gate is Gate.UNCLASSIFIED:
134
+ warn(
135
+ f"tool '{key}' left out: it runs '{tool.target or tool.impl}', which devstuff mcp "
136
+ "does not know how to gate, so it is not exposed"
137
+ )
138
+ continue
139
+ if not is_exposed(gate, allow_install=allow_install, allow_functions=allow_functions):
140
+ continue
141
+ if not TOOL_NAME.fullmatch(key) or key in RESERVED_NAMES:
142
+ warn(
143
+ f"tool '{key}' left out: a tool name must match [a-zA-Z0-9_-]{{1,64}} "
144
+ f"and not be reserved ({', '.join(sorted(RESERVED_NAMES))})"
145
+ )
146
+ continue
147
+ tools[key] = tool
148
+ gates[key] = gate
149
+ return cls(tools, gates)
150
+
151
+ def names(self) -> list[str]:
152
+ return list(self._tools)
153
+
154
+ def get(self, name: str) -> AgentTool | None:
155
+ return self._tools.get(name)
156
+
157
+ def gate(self, name: str) -> Gate:
158
+ return self._gates[name]
159
+
160
+ def input_schema(self, tool: AgentTool) -> dict[str, Any]:
161
+ """FR-16c: `required` omitted when empty (older JSON Schema drafts reject `[]`) and extra
162
+ properties forbidden, so a client's schema check agrees with `bind()`'s own rule."""
163
+ schema = tool.to_schema()["function"]["parameters"]
164
+ out: dict[str, Any] = {"type": "object", "properties": schema["properties"]}
165
+ if schema.get("required"):
166
+ out["required"] = schema["required"]
167
+ out["additionalProperties"] = False
168
+ return out
169
+
170
+ def describe(self) -> list[dict[str, Any]]:
171
+ """The MCP `tools/list` entries."""
172
+ return [
173
+ {
174
+ "name": key,
175
+ "title": tool.name,
176
+ "description": tool.description,
177
+ "inputSchema": self.input_schema(tool),
178
+ }
179
+ for key, tool in self._tools.items()
180
+ ]
181
+
182
+
183
+ # -- Results (FR-7) --------------------------------------------------------------------------
184
+
185
+
186
+ @dataclass(frozen=True)
187
+ class ToolResult:
188
+ """What a call produced. `note` is advisory and kept *out of* `text` so a JSON array in `text`
189
+ stays parseable (FR-7): MCP carries it as a second text item, REST as its own field."""
190
+
191
+ is_error: bool
192
+ text: str
193
+ note: str = ""
194
+
195
+
196
+ INSTALL_NOTE = "an install is in progress; this may change"
197
+
198
+
199
+ def to_mcp_result(result: ToolResult) -> dict[str, Any]:
200
+ content = [{"type": "text", "text": result.text}]
201
+ if result.note:
202
+ content.append({"type": "text", "text": result.note})
203
+ return {"content": content, "isError": result.is_error}
204
+
205
+
206
+ def _install_hint(key: str) -> str:
207
+ # FR-13. Appended to *every* install failure, not keyed on sudo's wording: under -v the error
208
+ # is only "exit code 1" and sudo's line never reaches the result (F-13).
209
+ return (
210
+ f" If this needed a password, it cannot be answered here (the server has no terminal): "
211
+ f"run `devstuff install {key}` in a terminal."
212
+ )
213
+
214
+
215
+ # -- Dispatch (FR-3, FR-5, FR-6, FR-8, FR-8a) ----------------------------------------------------
216
+
217
+
218
+ def _invoke(tool: AgentTool, bound: dict[str, Any]) -> str:
219
+ """Run one bound call. No workspace, no agent config (FR-4, F-5)."""
220
+ if tool.impl == "function":
221
+ return bridges.run_function(None, None, tool.target or "", bound) # type: ignore[arg-type]
222
+ bridge = bridges.get(tool.target or "")
223
+ if bridge is None: # unreachable while test_every_bridge_has_a_gate holds
224
+ raise SandboxError(f"no bridge named '{tool.target}'")
225
+ return bridge(None, None, bound) # type: ignore[arg-type]
226
+
227
+
228
+ def _log_to_stderr(message: str) -> None:
229
+ sys.stderr.write(message.rstrip("\n") + "\n")
230
+
231
+
232
+ def _forget_probes() -> None:
233
+ from dev_setup import generic
234
+
235
+ generic.forget_probes()
236
+
237
+
238
+ class Dispatcher:
239
+ """Runs calls against a `Toolbox` and speaks JSON-RPC for them.
240
+
241
+ `run`, `forget` and `log_error` are injectable so the state machine below is tested with a
242
+ fake machine; the defaults are the real bridges, `generic.forget_probes` and stderr.
243
+ """
244
+
245
+ def __init__(
246
+ self,
247
+ toolbox: Toolbox,
248
+ *,
249
+ run: Callable[[AgentTool, dict[str, Any]], str] = _invoke,
250
+ forget: Callable[[], None] = _forget_probes,
251
+ log_error: Callable[[str], None] = _log_to_stderr,
252
+ ) -> None:
253
+ self.toolbox = toolbox
254
+ self._run = run
255
+ self._forget = forget
256
+ self._log_error = log_error
257
+ # FR-8: one mutation at a time, across *both* gated classes — apt's lock and shared
258
+ # prefixes do not care which flag started the install.
259
+ self._mutation = threading.Lock()
260
+ # FR-8a: the state below is guarded by `_state`. `_mutations` is bumped when a gated call
261
+ # starts and again when it ends, so a read that sees it unchanged saw no mutation at all.
262
+ self._state = threading.Lock()
263
+ self._readers = 0
264
+ self._mutations = 0
265
+ self._running = 0
266
+
267
+ # -- one call ---------------------------------------------------------------------------
268
+
269
+ def call(self, name: str, arguments: dict[str, Any] | None = None) -> ToolResult:
270
+ """Run a tool. Raises `UnknownTool` for a name that is absent or gated off; everything
271
+ else — bad arguments, a bridge that fails, one that crashes — is a `ToolResult`."""
272
+ tool = self.toolbox.get(name)
273
+ if tool is None:
274
+ raise UnknownTool(name)
275
+ try:
276
+ bound = tool.bind(arguments or {})
277
+ except ValueError as exc:
278
+ return ToolResult(True, str(exc))
279
+
280
+ if self.toolbox.gate(name) is Gate.READ_ONLY:
281
+ return self._read(tool, bound)
282
+ return self._mutate(tool, bound)
283
+
284
+ def _execute(self, tool: AgentTool, bound: dict[str, Any]) -> ToolResult:
285
+ """One run of one bridge, with every failure turned into a result (FR-6)."""
286
+ try:
287
+ return ToolResult(False, self._run(tool, bound))
288
+ except bridges.InstallFailed as exc:
289
+ return ToolResult(True, str(exc) + _install_hint(str(bound.get("key", "<key>"))))
290
+ except SandboxError as exc:
291
+ return ToolResult(True, str(exc))
292
+ except SystemExit as exc:
293
+ # A bridge that exits would end its worker thread without ever answering the client.
294
+ return ToolResult(True, f"{tool.key} exited unexpectedly (status {exc.code})")
295
+ except Exception as exc:
296
+ self._log_error(f"{tool.key}: {traceback.format_exc()}")
297
+ first = (str(exc).splitlines() or [""])[0]
298
+ return ToolResult(True, f"{type(exc).__name__}: {first}" if first else type(exc).__name__)
299
+
300
+ def _mutate(self, tool: AgentTool, bound: dict[str, Any]) -> ToolResult:
301
+ with self._mutation:
302
+ with self._state:
303
+ self._mutations += 1
304
+ self._running += 1
305
+ try:
306
+ return self._execute(tool, bound)
307
+ finally:
308
+ # In `finally`: a failure part-way may already have changed the machine, and a
309
+ # memo that says otherwise would be served until the process exits (FR-8a.2).
310
+ try:
311
+ self._forget()
312
+ finally:
313
+ with self._state:
314
+ self._mutations += 1
315
+ self._running -= 1
316
+
317
+ def _read(self, tool: AgentTool, bound: dict[str, Any]) -> ToolResult:
318
+ """Run a read-only tool: never blocked by a mutation, never served stale (FR-8a)."""
319
+ with self._state:
320
+ new_burst = self._readers == 0
321
+ self._readers += 1
322
+ try:
323
+ if new_burst:
324
+ # Outside `_state`: clearing takes the lock of any probe still running, and that wait
325
+ # must not stall every other request's bookkeeping. A concurrent reader that joins in
326
+ # the gap at worst re-probes; it can never be handed a half-cleared memo.
327
+ self._forget()
328
+ result, straddled, installing = self._read_once(tool, bound)
329
+ if straddled and not installing and not result.is_error:
330
+ # A mutation began and ended during this read, so it may hold one memo from before
331
+ # and one from after. The mutation is finished, so one clean re-run is exact.
332
+ self._forget()
333
+ result, straddled, installing = self._read_once(tool, bound)
334
+ if (straddled or installing) and not result.is_error:
335
+ result = ToolResult(False, result.text, INSTALL_NOTE)
336
+ return result
337
+ finally:
338
+ with self._state:
339
+ self._readers -= 1
340
+
341
+ def _read_once(self, tool: AgentTool, bound: dict[str, Any]) -> tuple[ToolResult, bool, bool]:
342
+ with self._state:
343
+ before = self._mutations
344
+ result = self._execute(tool, bound)
345
+ with self._state:
346
+ return result, self._mutations != before, self._running > 0
347
+
348
+ # -- JSON-RPC (FR-15 … FR-18) -------------------------------------------------------------
349
+
350
+ def handle_text(self, text: str) -> str | None:
351
+ """One frame of text in, one frame of text out (None for a notification)."""
352
+ try:
353
+ frame = json.loads(text)
354
+ except ValueError:
355
+ return _dump(_error(None, -32700, "parse error"))
356
+ reply = self.handle(frame)
357
+ return None if reply is None else _dump(reply)
358
+
359
+ def handle(self, frame: Any) -> dict[str, Any] | None:
360
+ """One decoded frame in, one reply out. Never raises."""
361
+ if not isinstance(frame, dict):
362
+ # A batch is a JSON array (FR-18); anything else that is not an object is invalid too.
363
+ what = "batch requests are not supported" if isinstance(frame, list) else "invalid request"
364
+ return _error(None, -32600, what)
365
+ # A notification is the *absence* of the `id` key. Never a falsy value: Claude Code sends an
366
+ # integer 0 for `initialize` and an empty-looking id must still be answered (FR-16a).
367
+ notification = "id" not in frame
368
+ rid = frame.get("id")
369
+ method = frame.get("method")
370
+ if not isinstance(method, str):
371
+ return _error(None if notification else rid, -32600, "invalid request: no method")
372
+ try:
373
+ result = self._method(method, frame.get("params"))
374
+ except _RpcError as exc:
375
+ reply = _error(rid, exc.code, exc.message)
376
+ else:
377
+ reply = {"jsonrpc": "2.0", "id": rid, "result": result}
378
+ return None if notification else reply
379
+
380
+ def _method(self, method: str, params: Any) -> dict[str, Any]:
381
+ if method == "initialize":
382
+ return self._initialize(params)
383
+ if method == "ping":
384
+ return {}
385
+ if method == "tools/list":
386
+ return {"tools": self.toolbox.describe()}
387
+ if method == "tools/call":
388
+ return self._tools_call(params)
389
+ # Everything else — `server/discover`, resources/*, prompts/*, notifications — is "method not
390
+ # found". The current official client opens with `server/discover` and falls back to
391
+ # `initialize` only when told it is unknown; an empty result would stall it (F-2, FR-16).
392
+ raise _RpcError(-32601, f"method not found: {method}")
393
+
394
+ def _initialize(self, params: Any) -> dict[str, Any]:
395
+ wanted = params.get("protocolVersion") if isinstance(params, dict) else None
396
+ # Echo a version we support; otherwise answer with our own latest and let the client decide.
397
+ # Never refuse a session over a version (FR-17).
398
+ version = wanted if wanted in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
399
+ return {
400
+ "protocolVersion": version,
401
+ "capabilities": {"tools": {}},
402
+ "serverInfo": {"name": "devstuff", "version": __version__},
403
+ }
404
+
405
+ def _tools_call(self, params: Any) -> dict[str, Any]:
406
+ if not isinstance(params, dict) or not isinstance(params.get("name"), str):
407
+ raise _RpcError(-32602, "invalid params: 'name' (a string) is required")
408
+ arguments = params.get("arguments")
409
+ if arguments is None:
410
+ arguments = {}
411
+ if not isinstance(arguments, dict):
412
+ raise _RpcError(-32602, "invalid params: 'arguments' must be an object")
413
+ name = params["name"]
414
+ try:
415
+ return to_mcp_result(self.call(name, arguments))
416
+ except UnknownTool:
417
+ raise _RpcError(-32602, f"unknown tool: {name}") from None
418
+
419
+
420
+ # Newest first. The only version the real client was measured to send is 2025-11-25 (F-2, F-3).
421
+ PROTOCOL_VERSIONS = ("2025-11-25",)
422
+
423
+
424
+ class _RpcError(Exception):
425
+ def __init__(self, code: int, message: str) -> None:
426
+ super().__init__(message)
427
+ self.code = code
428
+ self.message = message
429
+
430
+
431
+ def error_text(rid: Any, code: int, message: str) -> str:
432
+ """A ready-to-send error frame, for a transport that must answer before a frame is parsed."""
433
+ return _dump(_error(rid, code, message))
434
+
435
+
436
+ def _error(rid: Any, code: int, message: str) -> dict[str, Any]:
437
+ return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
438
+
439
+
440
+ def _dump(frame: dict[str, Any]) -> str:
441
+ # ensure_ascii escapes U+2028 and friends as well as newlines, so a frame can never contain
442
+ # a character any line-oriented reader might split on (FR-19).
443
+ return json.dumps(frame, separators=(",", ":"))
@@ -0,0 +1,120 @@
1
+ """FR-11a: give the server no controlling terminal (docs/specs/mcp, F-11, SD-12).
2
+
3
+ A `/dev/null` stdin is not "no terminal": `sudo` opens `/dev/tty` directly and prompted on the
4
+ user's terminal even with fd 0 closed off (F-11). An installer waiting on a password nobody can
5
+ type would hang the client's request, so the server detaches at the *process* level, before the
6
+ fd move and before any tool can run.
7
+
8
+ `os.setsid()` does it when a client spawned the server. A shell starting `devstuff mcp --http`
9
+ makes the process a group leader, where `setsid` fails with `EPERM`; then the process forks, the
10
+ child calls `setsid` and is the server, and the original stays behind as a thin supervisor that
11
+ forwards signals and mirrors the exit status — so Ctrl-C and a closed terminal still stop it even
12
+ though it no longer owns the terminal.
13
+
14
+ The alternative, `start_new_session=True` on each of the six subprocess call sites, is the
15
+ per-call-site audit FR-11 already refuses to depend on: the next `subprocess` anyone writes would
16
+ silently reopen it.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import errno
22
+ import os
23
+ import signal
24
+ from collections.abc import Callable
25
+
26
+
27
+ class TerminalReachable(RuntimeError):
28
+ """The server could not give up its controlling terminal and may run an installer."""
29
+
30
+
31
+ def detach(
32
+ *,
33
+ setsid: Callable[[], object] = os.setsid,
34
+ fork: Callable[[], int] = os.fork,
35
+ supervise: Callable[[int], object] | None = None,
36
+ ) -> str:
37
+ """Leave the controlling terminal. Returns how: `"setsid"`, `"forked"` (this is the server
38
+ child), or — only when a test injects `supervise` — `"supervisor"`. The real supervisor never
39
+ returns; it exits with the server's status."""
40
+ try:
41
+ setsid()
42
+ return "setsid"
43
+ except OSError as exc:
44
+ if exc.errno != errno.EPERM:
45
+ raise # not the group-leader case: do not paper over an unexpected failure
46
+ pid = fork()
47
+ if pid == 0:
48
+ setsid() # the child is not a group leader, so this one cannot fail with EPERM
49
+ return "forked"
50
+ (supervise or _supervise)(pid)
51
+ return "supervisor"
52
+
53
+
54
+ def _supervise(child: int) -> None:
55
+ """Forward signals to the server and exit with its status. Never returns."""
56
+ # This process keeps no copy of the client's stdio: the server child owns the channel, and a
57
+ # supervisor holding the pipe open would keep a peer from seeing EOF when the server exits.
58
+ for fd in (0, 1):
59
+ try:
60
+ os.close(fd)
61
+ except OSError:
62
+ pass
63
+
64
+ def forward(signum: int, _frame: object) -> None:
65
+ # SIGHUP is what a closing terminal sends. The server is in its own session and would never
66
+ # see it, so it would be orphaned and keep running: it is turned into the polite stop.
67
+ target = signal.SIGTERM if signum == signal.SIGHUP else signum
68
+ try:
69
+ os.kill(child, target)
70
+ except ProcessLookupError:
71
+ pass
72
+
73
+ for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
74
+ signal.signal(sig, forward)
75
+
76
+ while True:
77
+ try:
78
+ _, status = os.waitpid(child, 0)
79
+ break
80
+ except InterruptedError:
81
+ continue
82
+ except ChildProcessError:
83
+ os._exit(1)
84
+ code = os.waitstatus_to_exitcode(status)
85
+ # A signalled child reads as 128+N, the shell's convention, so a caller can tell it from a status.
86
+ os._exit(code if code >= 0 else 128 - code)
87
+
88
+
89
+ def terminal_reachable(*, open_: Callable[..., int] = os.open) -> bool:
90
+ """Can this process open `/dev/tty`? `O_NOCTTY` so asking never acquires one as a side effect."""
91
+ try:
92
+ fd = open_("/dev/tty", os.O_RDWR | os.O_NOCTTY)
93
+ except OSError:
94
+ return False # ENXIO (no controlling terminal), ENOENT (a container) — either way, none
95
+ try:
96
+ os.close(fd)
97
+ except OSError:
98
+ pass
99
+ return True
100
+
101
+
102
+ def require_no_terminal(
103
+ *,
104
+ gated: bool,
105
+ warn: Callable[[str], None],
106
+ reachable: Callable[[], bool] | None = None,
107
+ ) -> None:
108
+ """Verify the detach worked, and fail closed (FR-11a.3).
109
+
110
+ With a gate flag on, the server can run an installer, so a reachable terminal is a refusal to
111
+ start — nothing that can prompt for a password starts while one is reachable. Read-only, there
112
+ is nothing that prompts, so it warns and continues."""
113
+ if not (reachable or terminal_reachable)():
114
+ return
115
+ if gated:
116
+ raise TerminalReachable(
117
+ "could not detach from the controlling terminal, and --allow-install/--allow-functions "
118
+ "can run an installer that would prompt on it; refusing to start"
119
+ )
120
+ warn("still attached to a controlling terminal (read-only tools never prompt, so continuing)")
dev_setup/mcp/stdio.py ADDED
@@ -0,0 +1,158 @@
1
+ """The stdio transport: newline-delimited JSON-RPC over a private channel (docs/specs/mcp).
2
+
3
+ The protocol owns stdout, and devstuff writes to stdout from places nobody can audit for good: the
4
+ Rich console, `_run`'s verbose branch, `function_runner`, and every child process (F-1). So the
5
+ channel is moved at the *descriptor* level, before any tool can run — private `dup`s of the real
6
+ stdin and stdout, then fd 1 pointed at stderr and fd 0 at `/dev/null`. After that there is no path
7
+ by which a stray byte can reach the client: stdout has no way to *be* the protocol.
8
+
9
+ Requests run on their own threads, because a read must not wait behind an install that takes
10
+ minutes (FR-8, FR-8a). Replies are written under one lock, one line each.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import signal
17
+ import sys
18
+ import threading
19
+ from dataclasses import dataclass
20
+ from typing import BinaryIO
21
+
22
+ from dev_setup import verbose
23
+ from dev_setup.mcp.core import Dispatcher, error_text
24
+
25
+ MAX_FRAME = 1024 * 1024 # FR-18: a request over 1 MiB is refused
26
+
27
+
28
+ @dataclass
29
+ class Channel:
30
+ """The client's end of the conversation, on descriptors nothing else holds."""
31
+
32
+ rfile: BinaryIO
33
+ wfile: BinaryIO
34
+
35
+
36
+ def isolate_stdio() -> Channel:
37
+ """Move the protocol onto private descriptors and repoint the standard ones (FR-11).
38
+
39
+ The private fds are not inheritable (PEP 446 makes `os.dup` results so), so no child can read
40
+ from or write to the channel; fd 0 and fd 1 stay inheritable, so a child that reads stdin sees
41
+ EOF and one that writes stdout lands on stderr.
42
+ """
43
+ for stream in (sys.stdout, sys.stderr):
44
+ try:
45
+ stream.flush()
46
+ except (OSError, ValueError):
47
+ pass
48
+ in_fd = os.dup(0)
49
+ out_fd = os.dup(1)
50
+ devnull = os.open(os.devnull, os.O_RDONLY)
51
+ os.dup2(devnull, 0)
52
+ os.close(devnull)
53
+ os.dup2(2, 1)
54
+ # Unbuffered out: a reply is written whole and at once, and there is no buffer left holding a
55
+ # frame a dead client never took (which would be flushed, and fail, again at interpreter exit).
56
+ return Channel(os.fdopen(in_fd, "rb"), os.fdopen(out_fd, "wb", buffering=0))
57
+
58
+
59
+ class _Shutdown(Exception):
60
+ """Raised by the first SIGINT/SIGTERM to break the main thread out of a blocking read."""
61
+
62
+
63
+ def serve(
64
+ dispatcher: Dispatcher, rfile: BinaryIO, wfile: BinaryIO, *, max_frame: int = MAX_FRAME
65
+ ) -> int:
66
+ """Read frames until EOF (or a shutdown), answer each, and return the exit status.
67
+
68
+ On the way out it waits for every request still running: an installer killed half-way is worse
69
+ than one waited for (FR-30), and a reply to a call that was already accepted is still owed.
70
+ """
71
+ write_lock = threading.Lock()
72
+ workers: list[threading.Thread] = []
73
+
74
+ def reply(text: str) -> None:
75
+ view = memoryview(text.encode("utf-8") + b"\n")
76
+ with write_lock:
77
+ try:
78
+ while view: # a raw file may take less than all of it
79
+ written = wfile.write(view)
80
+ view = view[written:] if written else view
81
+ wfile.flush()
82
+ except (OSError, ValueError):
83
+ # The client has gone. The next read says so (EOF); until then there is nobody to
84
+ # tell, and a write error must never take the loop down.
85
+ pass
86
+
87
+ def work(line: bytes) -> None:
88
+ try:
89
+ text = line.decode("utf-8")
90
+ except UnicodeDecodeError:
91
+ out: str | None = error_text(None, -32700, "parse error: not valid UTF-8")
92
+ else:
93
+ verbose.log(f"mcp ← {_clip(text)}")
94
+ out = dispatcher.handle_text(text)
95
+ if out is not None:
96
+ verbose.trace(f"mcp → {_clip(out)}")
97
+ reply(out)
98
+
99
+ try:
100
+ while True:
101
+ line = rfile.readline(max_frame + 1)
102
+ if not line:
103
+ break # EOF
104
+ if len(line) > max_frame and not line.endswith(b"\n"):
105
+ _discard_line(rfile)
106
+ reply(error_text(None, -32600, f"request too large (limit {max_frame} bytes)"))
107
+ continue
108
+ if not line.strip():
109
+ continue
110
+ workers = [w for w in workers if w.is_alive()]
111
+ worker = threading.Thread(target=work, args=(line,), name="mcp-request")
112
+ workers.append(worker)
113
+ worker.start()
114
+ except _Shutdown:
115
+ pass
116
+
117
+ while True:
118
+ try:
119
+ for worker in workers:
120
+ worker.join()
121
+ break
122
+ except _Shutdown:
123
+ continue # a first signal that arrived late: still wait; a second one exits at once
124
+ return 0
125
+
126
+
127
+ def _discard_line(rfile: BinaryIO) -> None:
128
+ """Drop the rest of an over-long line, so its tail is not read as the next frame."""
129
+ while True:
130
+ chunk = rfile.readline(64 * 1024)
131
+ if not chunk or chunk.endswith(b"\n"):
132
+ return
133
+
134
+
135
+ def _clip(text: str, limit: int = 300) -> str:
136
+ text = text.rstrip("\n")
137
+ return text if len(text) <= limit else text[:limit] + f"… (+{len(text) - limit} chars)"
138
+
139
+
140
+ def run(dispatcher: Dispatcher) -> int:
141
+ """Isolate stdio, install the shutdown signals, and serve until the client goes away.
142
+
143
+ The first SIGINT/SIGTERM stops reading new requests and lets the running ones finish; a second
144
+ exits immediately (FR-30).
145
+ """
146
+ channel = isolate_stdio()
147
+ received = 0
148
+
149
+ def on_signal(signum: int, _frame: object) -> None:
150
+ nonlocal received
151
+ received += 1
152
+ if received > 1:
153
+ os._exit(128 + signum)
154
+ raise _Shutdown
155
+
156
+ signal.signal(signal.SIGINT, on_signal)
157
+ signal.signal(signal.SIGTERM, on_signal)
158
+ return serve(dispatcher, channel.rfile, channel.wfile)
dev_setup/updates.py CHANGED
@@ -140,6 +140,21 @@ def sort_rows(rows: Iterable[Row]) -> list[Row]:
140
140
  return sorted(rows, key=lambda r: (_ORDER[r.state], r.key))
141
141
 
142
142
 
143
+ def build_rows(named: Sequence[Tool] | None = None) -> list[Row]:
144
+ """Every row `outdated` reports, in display order — the one place that decides what they are.
145
+
146
+ `named` limits the check to those tools; one that is not installed gets a `not-installed` row
147
+ rather than vanishing, because the caller asked about it by name. Shared by the command and
148
+ the `outdated` agent/MCP bridge so the two cannot disagree about an answer.
149
+ """
150
+ candidates = collect_candidates(named)
151
+ rows = [make_row(tool, status) for tool, status in candidates]
152
+ if named is not None:
153
+ found = {tool.key for tool, _ in candidates}
154
+ rows += [make_row(t, None, installed=False) for t in named if t.key not in found]
155
+ return sort_rows(rows)
156
+
157
+
143
158
  def summarize(rows: Iterable[Row]) -> dict[State, int]:
144
159
  """Count rows per state. Every state is present, so the counts always sum to the rows."""
145
160
  counts = dict.fromkeys(State, 0)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: devstuff
3
- Version: 2.14.0
3
+ Version: 2.16.0
4
4
  Summary: Development environment setup CLI for Linux
5
5
  Project-URL: Repository, https://github.com/thesawdawg/dev-setup-py
6
6
  Author-email: Sawyer <sawyerksu@gmail.com>
@@ -1159,6 +1159,33 @@ confirmation.
1159
1159
 
1160
1160
  ---
1161
1161
 
1162
+ ## MCP server (`devstuff mcp`)
1163
+
1164
+ `devstuff mcp` serves devstuff's tools to an MCP client over **stdio**. It is started *by* the client, not by
1165
+ hand. Register it with Claude Code:
1166
+
1167
+ ```bash
1168
+ claude mcp add devstuff -- devstuff mcp # read-only tools only
1169
+ claude mcp add devstuff -- devstuff mcp --allow-install # also install_tool
1170
+ ```
1171
+
1172
+ | Flag | Effect |
1173
+ |---|---|
1174
+ | *(none)* | `list_tools`, `search_catalog`, `tool_info`, `outdated`, `profile_diff` — nothing that changes the machine |
1175
+ | `--allow-install` | adds `install_tool`, which installs a catalog tool as you |
1176
+ | `--allow-functions` | adds every `type: script` function as `fn_<key>` |
1177
+ | `--list-tools` | print what these flags would expose, and which gate each tool sits behind; starts nothing |
1178
+
1179
+ A tool whose flag is off is not hidden but **absent and refused**: a call naming it is answered as an unknown tool.
1180
+ Workspace tools (`read_file`, `run_command`, …) never exist here — the client already has files and a shell.
1181
+
1182
+ The server has **no terminal**: an installer that needs a `sudo` password fails at once with a message telling the
1183
+ client to run `devstuff install <key>` in a terminal, rather than waiting for a password nobody can type.
1184
+ Logs (`-v`, `-vv`) go to stderr. HTTP and OpenAPI front ends are still to come; see
1185
+ [`docs/specs/mcp/`](docs/specs/mcp/).
1186
+
1187
+ ---
1188
+
1162
1189
  ## Agent
1163
1190
 
1164
1191
  `devstuff agent` opens an interactive session with a **local** model (via [Ollama](https://ollama.com))
@@ -1260,6 +1287,8 @@ deny_patterns: [] # extra regexes refused on top of the built-in
1260
1287
  | `list_tools` | | List the devstuff catalog with install state |
1261
1288
  | `search_catalog` | | Find a catalog tool by name or description |
1262
1289
  | `tool_info` | | Details for one catalog tool |
1290
+ | `outdated` | | Which installed tools have a newer version (the rows `devstuff outdated --json` prints) |
1291
+ | `profile_diff` | | Compare this machine to a bundled profile such as `@devops` (the rows `profile diff --json` prints) |
1263
1292
  | `install_tool` | ! | Install a catalog tool (handles sudo itself) |
1264
1293
  | `fn_<key>` | ! | Every `type: script` entry in `functions.yaml`, exposed automatically |
1265
1294
 
@@ -1,13 +1,13 @@
1
1
  dev_setup/__init__.py,sha256=BfTc-iAf16B_sxLK1PM3P7QlMGy7k33ColMK0o6KkdA,158
2
2
  dev_setup/__main__.py,sha256=w-Vnqe3bgAw_UNlPywPkbOqoFKcEk2H2S79wrQjXvU4,102
3
- dev_setup/agent_tools.schema.json,sha256=veXnih00xW4w9yK3ruWz-npUrCnJmcQpQdFvfcu7v_I,4928
4
- dev_setup/agent_tools.yaml,sha256=56E70B1W7hBqjGhYhhCAGzFQvi1nUZ04cnNiqZlMjyY,4506
3
+ dev_setup/agent_tools.schema.json,sha256=lNu8N5nm4VPzUJar3gI7SHP7rPrJAcVwaA7Sx0Zd26Y,4937
4
+ dev_setup/agent_tools.yaml,sha256=YQy6Y6MS65nsRd3MsfuyilaiVBQp89t1TDimeIJw6L8,5944
5
5
  dev_setup/apply_exec.py,sha256=czzQxxYHWCAmAsgd9BvMPYlG2b63g0b3RHbbO5UyPRA,6364
6
6
  dev_setup/apply_plan.py,sha256=L_ZmSGnjM7T1hKT7RLXSvCZgjbRpX_AaTKg5N9fp1zs,8474
7
7
  dev_setup/base.py,sha256=j2EQ5gzeGgtveWQN_BgbLcZianMENJ7PQy8EQ9J9MPE,1946
8
8
  dev_setup/bundles.py,sha256=h-WdjwNI82SQCgXiJ-EoiwuI81umb09Q0NNUYyzH1FI,2285
9
9
  dev_setup/catalog.py,sha256=PrimTBUYoh8cW9QYhXUxP8qSMeK51kzQjUoPEGD9EBw,6530
10
- dev_setup/cli.py,sha256=M4si1b2yZ44Y3zfdwF-D0v__ZhDnemLl8vLrFKonWDg,3320
10
+ dev_setup/cli.py,sha256=KHdraEvcUf1IqSLkGjXyChSccBduPPvxvNefWfL4qzg,3407
11
11
  dev_setup/doctor.py,sha256=1shwNLT5wFxiGT5oBVqbF478B7lcHVwT_e50aFb2I20,16962
12
12
  dev_setup/function_runner.py,sha256=08F6jvB9-oOyE5ivYtRjnL16JTGsfRnkpvkjSVrJhsM,6957
13
13
  dev_setup/functions.schema.json,sha256=VVdpH3xWsdbtqw47S1QqpBcs4O9wd3XZ_s0Q3sGwv0Q,6220
@@ -24,19 +24,19 @@ dev_setup/registry.py,sha256=eHEuo4p0O0CHDWatFuOlSFiSAz5L6YFYmv9tAGHYMt4,2510
24
24
  dev_setup/snapshot.py,sha256=A2G_6pHSaGhDT1PJAZ6eW83GdSdCGs2r79yH8FCa0Qs,5330
25
25
  dev_setup/tools.yaml,sha256=m2MEYq_mZuzEU8vCJgPWHdhLuqRjQGNWheqhwQgMXXQ,34234
26
26
  dev_setup/ui.py,sha256=B0t4hYlZ7jIMIdldMCImLNBJT1NQgZ4ff8ItjfHRNl0,23879
27
- dev_setup/updates.py,sha256=D6dH6G_Bv07XWSyzXvYESbV5s2d0N7euHu69zUyBbs4,5289
27
+ dev_setup/updates.py,sha256=p9_nbfaX_73hE71kr5ZDZA5o85T9XTR0mjbo15f950I,6046
28
28
  dev_setup/verbose.py,sha256=N3U9JAYOvFwdd8DT6W7Pqq6RCIUfbcQnPsm0O1TnvQY,5003
29
29
  dev_setup/agent/__init__.py,sha256=znrgxUCr_y0Qp-f41S6EaTv-hoTYwoZ9mOMLVge-IJg,226
30
30
  dev_setup/agent/approval.py,sha256=DNPV5iM_UpCx39xFzCu8kyr03tjfyfD7iVcTfQMJRwY,3630
31
- dev_setup/agent/bridges.py,sha256=RX5coPXJUSkyZApxgUZghz_57ibcPrWHVz3D44S6z2Q,4814
32
- dev_setup/agent/catalog.py,sha256=-5SbDxlT_W8PHoFRJA905eJ9aIe6cHtNrAtZJcImwkY,6304
31
+ dev_setup/agent/bridges.py,sha256=m1e5bYLib8jwvi7uKvOQwnuKv6sG3f98uhZjzWSoyfs,7858
32
+ dev_setup/agent/catalog.py,sha256=yh4x50GuUwwk6IaESDbosbTU4ehCsITUCWG0-BuAAFk,6313
33
33
  dev_setup/agent/completion.py,sha256=BhreXV0MwyMejAFmXe6gX6h64nTH713RIy-Dy0KK-Ig,1854
34
34
  dev_setup/agent/config.py,sha256=a0vagUWyKd1MOBsdJeNGVRlAGZdqfozPRNJyNxXN16Q,5970
35
35
  dev_setup/agent/loop.py,sha256=PKmGokOkKNLcwaSlnZ0v8XhwIx0N4t1Zj6Ia1kSflNM,4982
36
36
  dev_setup/agent/ollama.py,sha256=B1YfJQQzdF5hagd3Q_6rGe82IISwolhP-zMZh_7DN1o,8774
37
37
  dev_setup/agent/preflight.py,sha256=pTaDqrwGI99b5WedU4ujyggTEcrUZmBh4mo8UYrMYd4,3463
38
38
  dev_setup/agent/primitives.py,sha256=g8WuzQZuqLU-Nv_XlLBcsOVsrBku-_5yWRHEXD5i4ZY,3714
39
- dev_setup/agent/registry.py,sha256=Glj7VM-L4ttVYK9YtX63jvsrnU6Rr7-GN0RdqsJjaio,5368
39
+ dev_setup/agent/registry.py,sha256=LT2W5dAJgAVlSwJ5wgJctkOnRKOE_7jkYW1Hz0E_pWg,5644
40
40
  dev_setup/agent/sandbox.py,sha256=wS_9kwc6r0spKSX8CBJFDkhWSiVG60D8dCKBrKbVnYA,10891
41
41
  dev_setup/agent/session.py,sha256=1UB0Mxz-cflDHqOfj1PFzufb1yz1ECbcObXIPubZfMU,12654
42
42
  dev_setup/agent/transcript.py,sha256=hJQuSLriAe5hvnD3SCMqOWduuYtblyhmqzZQ3jDco1Y,1868
@@ -61,7 +61,8 @@ dev_setup/commands/help_cmd.py,sha256=O2dnhqsMZx5tVHdJVixixCJwc9TYlKdlZ2vYYPApl0
61
61
  dev_setup/commands/install_cmd.py,sha256=YgVm8r2RevoSrfBBAvZpDmL0NOQFdOGTFp3aIx-9xwo,8519
62
62
  dev_setup/commands/links_cmd.py,sha256=kvnoBXdM9QWRZRIwWgnmWqVkOYE7AZxywFTQD5_Uwv4,4924
63
63
  dev_setup/commands/list_cmd.py,sha256=Env6bwAmREDek4L-ZB2CIfvLT4PgaKcz5sQKJ1GhL8g,2913
64
- dev_setup/commands/outdated_cmd.py,sha256=YljnMw-KZd1jcZO5FEce3H6nrX1MnWOt0fRBSAdlpQE,5070
64
+ dev_setup/commands/mcp_cmd.py,sha256=JPPIvSYXWHHwg9IZA2KsZ0KeIc1kD-X_iVsc231Fn58,3291
65
+ dev_setup/commands/outdated_cmd.py,sha256=afwYyq0M-tWVOk2qyXQqsdWSTK6yuFbVpbrOmMPKS_w,4757
65
66
  dev_setup/commands/profile_cmd.py,sha256=jo7al_nBwuWtzOLYKjcqEGmHp4eQrzM5s7ahv6iiGaw,18299
66
67
  dev_setup/commands/remove_cmd.py,sha256=Az0qMes4M5237c_ntQ1SemS38gTpLZy2GhSK_gUrw3s,4974
67
68
  dev_setup/commands/run_cmd.py,sha256=e1xfWt09UALiAe03AxzdvZyYpj0V7WKk2-E_nbk9hIw,2933
@@ -113,7 +114,11 @@ dev_setup/configure/starship/model.py,sha256=ct1YrR3xLqcKMP20TvKZQ0Oc-OxHMrRjnei
113
114
  dev_setup/configure/starship/preview.py,sha256=ZaNhNA3AeHHtPnMqrJbB9XVVXDFbH1R36jm8xyYdt2U,6145
114
115
  dev_setup/configure/starship/render.py,sha256=25O8w4IteVd_ELwmIWhcYAn042W6yZ--zbTMcJpzVJc,11277
115
116
  dev_setup/configure/starship/wizard.py,sha256=F3-xVQmZjYtiQAICyJXeSogjcASSsVbaP2b8YHAX9TM,28726
116
- devstuff-2.14.0.dist-info/METADATA,sha256=b2qlJDqyH_cdiuL9YdBtkb-6BlpUBdBPuVJ-M3abYyg,93513
117
- devstuff-2.14.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
118
- devstuff-2.14.0.dist-info/entry_points.txt,sha256=48ITy9ENdXDFrTHwAyVPUpq1MDmgFqcOisOo5mAR6OQ,53
119
- devstuff-2.14.0.dist-info/RECORD,,
117
+ dev_setup/mcp/__init__.py,sha256=a3DUEjK_mIpC4QsaPaArwKqaVvtujfzSu8WMpMh6G70,89
118
+ dev_setup/mcp/core.py,sha256=5IlKkPXDUsdyKVbpSw3yDjkmY_92hdXlAOdK_a7SXsA,18898
119
+ dev_setup/mcp/process.py,sha256=IV203HLaCelWb89IhV73_8NWNAGglXRtXpwpHk39dD4,4752
120
+ dev_setup/mcp/stdio.py,sha256=lCd0RIt5dpGR4hWcezm4glwM-_Z2fBZB24JlmjqDF0Q,5753
121
+ devstuff-2.16.0.dist-info/METADATA,sha256=7qsx0pAYrjY7rMRT0_nvoVzHES8qhmbVSGb7aPn2WiQ,95104
122
+ devstuff-2.16.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
123
+ devstuff-2.16.0.dist-info/entry_points.txt,sha256=48ITy9ENdXDFrTHwAyVPUpq1MDmgFqcOisOo5mAR6OQ,53
124
+ devstuff-2.16.0.dist-info/RECORD,,