devstuff 2.16.0__py3-none-any.whl → 2.18.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,18 +1,34 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import errno
4
+ import ipaddress
5
+ import os
6
+ import re
3
7
  import sys
8
+ from pathlib import Path
4
9
 
5
10
  import click
6
11
 
7
12
  from dev_setup.catalog import CatalogError
8
- from dev_setup.mcp import process, stdio
13
+ from dev_setup.mcp import http, printconfig, process, stdio, token
9
14
  from dev_setup.mcp.core import Dispatcher, Toolbox
10
15
 
16
+ DEFAULT_HOST = "127.0.0.1"
17
+ DEFAULT_PORT = 8765 # fixed on purpose: a configured client's URL must survive a restart (SD-8)
18
+
19
+ _HOSTNAME = re.compile(r"[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?")
20
+ _ORIGIN = re.compile(r"https?://[^/\s]+")
21
+
11
22
 
12
23
  def _warn(message: str) -> None:
13
24
  click.echo(f"devstuff mcp: {message}", err=True)
14
25
 
15
26
 
27
+ def _fail(message: str) -> None:
28
+ click.echo(f"error: {message}", err=True)
29
+ sys.exit(1)
30
+
31
+
16
32
  def _toolbox(allow_install: bool, allow_functions: bool) -> Toolbox:
17
33
  from dev_setup.agent import registry as agent_registry
18
34
 
@@ -21,19 +37,55 @@ def _toolbox(allow_install: bool, allow_functions: bool) -> Toolbox:
21
37
  )
22
38
 
23
39
 
24
- def _banner(box: Toolbox, allow_install: bool, allow_functions: bool) -> str:
40
+ def _enabled(allow_install: bool, allow_functions: bool) -> str:
25
41
  gated = [
26
42
  label
27
43
  for label, on in (("install_tool", allow_install), ("functions", allow_functions))
28
44
  if on
29
45
  ]
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
- )
46
+ return f"+ {', '.join(gated)}" if gated else "read-only; install_tool and functions are off"
47
+
48
+
49
+ def _is_loopback(host: str) -> bool:
50
+ if host == "localhost":
51
+ return True
52
+ try:
53
+ return ipaddress.ip_address(host).is_loopback
54
+ except ValueError:
55
+ return False
34
56
 
35
57
 
36
58
  @click.command("mcp")
59
+ @click.option(
60
+ "--http", "use_http", is_flag=True,
61
+ help="Serve over HTTP instead of stdio: MCP at POST /mcp, REST at /tools, the OpenAPI document at "
62
+ "/openapi.json. Every request needs the bearer token.",
63
+ )
64
+ @click.option(
65
+ "--host", default=None, metavar="ADDR",
66
+ help=f"[--http] Address to listen on (default {DEFAULT_HOST}, this machine only). A non-loopback "
67
+ "address is allowed, and warned about: there is no TLS.",
68
+ )
69
+ @click.option(
70
+ "--port", type=click.IntRange(0, 65535), default=None, metavar="N",
71
+ help=f"[--http] Port (default {DEFAULT_PORT}). 0 asks the OS. A busy port is an error, never a fallback.",
72
+ )
73
+ @click.option(
74
+ "--token-file", type=click.Path(dir_okay=False, path_type=Path), default=None, metavar="PATH",
75
+ help="[--http] Where the bearer token lives (default ~/.local/state/devstuff/mcp-token). Created "
76
+ "on first use, mode 0600, reused on every run. Its path is printed; its contents never are.",
77
+ )
78
+ @click.option("--rotate-token", is_flag=True, help="[--http] Replace the token with a new one.")
79
+ @click.option(
80
+ "--allow-origin", "allow_origins", multiple=True, metavar="ORIGIN",
81
+ help="[--http] Accept requests carrying this Origin (repeatable). Default: none, so a browser "
82
+ "is refused.",
83
+ )
84
+ @click.option(
85
+ "--allow-host", "allow_hosts", multiple=True, metavar="NAME",
86
+ help="[--http] Accept this name in the Host header (repeatable), e.g. host.docker.internal. "
87
+ "`localhost` and IP addresses are always accepted.",
88
+ )
37
89
  @click.option(
38
90
  "--allow-install", is_flag=True,
39
91
  help="Expose install_tool, which installs a catalog tool as you. Off by default: absent and refused.",
@@ -46,16 +98,64 @@ def _banner(box: Toolbox, allow_install: bool, allow_functions: bool) -> str:
46
98
  "--list-tools", "list_tools", is_flag=True,
47
99
  help="Print the tools these flags would expose, and which gate each sits behind. Starts nothing.",
48
100
  )
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.
101
+ @click.option(
102
+ "--print-config", "print_config", type=click.Choice(printconfig.TARGETS), default=None, metavar="TARGET",
103
+ help="Print a snippet to paste into a client, for the other flags given, and exit: claude-code (the "
104
+ "`claude mcp add` command), claude-desktop (the mcpServers JSON) or openapi (URLs and header). "
105
+ "Starts nothing, and never contains the token.",
106
+ )
107
+ def mcp_cmd(
108
+ use_http: bool,
109
+ host: str | None,
110
+ port: int | None,
111
+ token_file: Path | None,
112
+ rotate_token: bool,
113
+ allow_origins: tuple[str, ...],
114
+ allow_hosts: tuple[str, ...],
115
+ allow_install: bool,
116
+ allow_functions: bool,
117
+ list_tools: bool,
118
+ print_config: str | None,
119
+ ) -> None:
120
+ """Serve devstuff's tools to an MCP client (stdio) or over HTTP, MCP and OpenAPI.
121
+
122
+ By default it speaks MCP over stdio: it reads JSON-RPC from stdin and answers on stdout, and is
123
+ meant to be started by a client (Claude Code, Claude Desktop), not by hand. With --http it
124
+ listens on a port instead.
51
125
 
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.
126
+ Only read-only tools are exposed unless a flag says otherwise, and a tool that is off does not
127
+ merely hide: a call naming it is refused.
55
128
 
56
129
  The server has no terminal. An installer that needs a password fails at once rather than
57
130
  waiting for one nobody can type; run `devstuff install <key>` in a terminal for those.
58
131
  """
132
+ http_only = {
133
+ "--host": host is not None, "--port": port is not None, "--token-file": token_file is not None,
134
+ "--rotate-token": rotate_token, "--allow-origin": bool(allow_origins),
135
+ "--allow-host": bool(allow_hosts),
136
+ }
137
+ if not use_http and any(http_only.values()):
138
+ given = ", ".join(flag for flag, on in http_only.items() if on)
139
+ raise click.UsageError(f"{given} only apply with --http.")
140
+ for name in allow_hosts:
141
+ if not _HOSTNAME.fullmatch(name):
142
+ raise click.UsageError(
143
+ f"--allow-host takes a bare host name (no port, scheme or path), not {name!r}."
144
+ )
145
+ for origin in allow_origins:
146
+ if not _ORIGIN.fullmatch(origin):
147
+ raise click.UsageError(
148
+ f"--allow-origin takes an origin like http://localhost:3000, not {origin!r}."
149
+ )
150
+
151
+ if print_config and list_tools:
152
+ raise click.UsageError("--print-config and --list-tools each print and exit; pass one.")
153
+ if print_config:
154
+ _print_config(
155
+ print_config, use_http, host or DEFAULT_HOST, DEFAULT_PORT if port is None else port,
156
+ token_file, allow_install, allow_functions,
157
+ )
158
+ return
59
159
  if list_tools:
60
160
  _print_tools(_load(allow_install, allow_functions))
61
161
  return
@@ -66,20 +166,87 @@ def mcp_cmd(allow_install: bool, allow_functions: bool, list_tools: bool) -> Non
66
166
  try:
67
167
  process.require_no_terminal(gated=allow_install or allow_functions, warn=_warn)
68
168
  except process.TerminalReachable as exc:
69
- click.echo(f"error: {exc}", err=True)
70
- sys.exit(1)
169
+ _fail(str(exc))
71
170
 
72
171
  box = _load(allow_install, allow_functions)
73
- click.echo(_banner(box, allow_install, allow_functions), err=True)
74
- sys.exit(stdio.run(Dispatcher(box)))
172
+ if not use_http:
173
+ what = _enabled(allow_install, allow_functions)
174
+ click.echo(f"devstuff mcp: serving {len(box.names())} tools on stdio ({what})", err=True)
175
+ sys.exit(stdio.run(Dispatcher(box)))
176
+ _serve_http(
177
+ box, Dispatcher(box), host or DEFAULT_HOST, DEFAULT_PORT if port is None else port,
178
+ token_file, rotate_token, allow_origins, allow_hosts, _enabled(allow_install, allow_functions),
179
+ )
180
+
181
+
182
+ def _print_config(
183
+ target: str, use_http: bool, host: str, port: int, token_file: Path | None,
184
+ allow_install: bool, allow_functions: bool,
185
+ ) -> None:
186
+ path = Path(os.path.abspath(token_file or token.default_path()))
187
+ spec = printconfig.Spec(
188
+ launcher=printconfig.launcher(sys.argv[0], sys.executable), http=use_http, host=host, port=port,
189
+ token_file=path, allow_install=allow_install, allow_functions=allow_functions,
190
+ )
191
+ try:
192
+ rendered = printconfig.render(target, spec)
193
+ except printconfig.ConfigError as exc:
194
+ raise click.UsageError(str(exc)) from exc
195
+ click.echo(rendered.text, nl=False)
196
+ # Notes go to stderr so `--print-config … > file` is the snippet and nothing else.
197
+ for note in rendered.notes:
198
+ _warn(note)
199
+ if use_http and target != "claude-desktop" and not path.exists():
200
+ _warn(f"{path} does not exist yet: the server creates it the first time it starts.")
201
+
202
+
203
+ def _serve_http(
204
+ box: Toolbox, dispatcher: Dispatcher, host: str, port: int, token_file: Path | None,
205
+ rotate: bool, allow_origins: tuple[str, ...], allow_hosts: tuple[str, ...], enabled: str,
206
+ ) -> None:
207
+ try:
208
+ secret, path = token.load(token_file, rotate=rotate)
209
+ except token.TokenError as exc:
210
+ _fail(str(exc))
211
+ try:
212
+ server = http.make_server(
213
+ dispatcher, host=host, port=port, token=secret,
214
+ allow_hosts=allow_hosts, allow_origins=allow_origins,
215
+ )
216
+ except OSError as exc:
217
+ hint = ""
218
+ if exc.errno == errno.EADDRINUSE:
219
+ hint = (
220
+ " Another process is using it. devstuff never picks a different port: a client "
221
+ "configured for this one would fail with no explanation. Stop that process, or pass --port."
222
+ )
223
+ _fail(f"cannot listen on {host}:{port}: {exc.strerror or exc}.{hint}")
224
+
225
+ # With the port held and before any request can arrive: nothing a tool prints may reach the
226
+ # terminal or read from it (FR-11).
227
+ stdio.isolate_stdio(channel=False)
228
+ bound = server.bound_port
229
+ shown = f"[{host}]" if ":" in host else host
230
+ click.echo(
231
+ f"devstuff mcp: serving {len(box.names())} tools on http://{shown}:{bound} ({enabled}); "
232
+ f"bearer token in {path}",
233
+ err=True,
234
+ )
235
+ if not _is_loopback(host):
236
+ _warn(
237
+ f"listening on {host}, not just this machine. There is no TLS: the token crosses the network in "
238
+ f"the clear, and anyone who holds it can use every enabled tool ({enabled}). To reach a "
239
+ "loopback server from another machine, an SSH tunnel is safer."
240
+ )
241
+ sys.exit(http.serve(server))
75
242
 
76
243
 
77
244
  def _load(allow_install: bool, allow_functions: bool) -> Toolbox:
78
245
  try:
79
246
  return _toolbox(allow_install, allow_functions)
80
247
  except CatalogError as exc:
81
- click.echo(f"error: {exc}", err=True)
82
- sys.exit(1)
248
+ _fail(str(exc))
249
+ raise # unreachable: _fail exits
83
250
 
84
251
 
85
252
  def _print_tools(box: Toolbox) -> None:
dev_setup/mcp/core.py CHANGED
@@ -167,6 +167,24 @@ class Toolbox:
167
167
  out["additionalProperties"] = False
168
168
  return out
169
169
 
170
+ def requires_body(self, name: str) -> bool:
171
+ """Whether a REST call to this tool must carry a body: it has a required parameter (FR-23)."""
172
+ return bool(self.input_schema(self._tools[name]).get("required"))
173
+
174
+ def openai_tools(self) -> list[dict[str, Any]]:
175
+ """`GET /tools`: the OpenAI function-calling array, with FR-16c's schema rules (FR-21)."""
176
+ return [
177
+ {
178
+ "type": "function",
179
+ "function": {
180
+ "name": key,
181
+ "description": tool.description,
182
+ "parameters": self.input_schema(tool),
183
+ },
184
+ }
185
+ for key, tool in self._tools.items()
186
+ ]
187
+
170
188
  def describe(self) -> list[dict[str, Any]]:
171
189
  """The MCP `tools/list` entries."""
172
190
  return [
@@ -203,6 +221,14 @@ def to_mcp_result(result: ToolResult) -> dict[str, Any]:
203
221
  return {"content": content, "isError": result.is_error}
204
222
 
205
223
 
224
+ def rest_result(result: ToolResult) -> dict[str, Any]:
225
+ """The REST body for a call: the same facts as MCP's result (FR-23). `note` only when there is one."""
226
+ out: dict[str, Any] = {"is_error": result.is_error, "text": result.text}
227
+ if result.note:
228
+ out["note"] = result.note
229
+ return out
230
+
231
+
206
232
  def _install_hint(key: str) -> str:
207
233
  # FR-13. Appended to *every* install failure, not keyed on sudo's wording: under -v the error
208
234
  # is only "exit code 1" and sudo's line never reaches the result (F-13).
@@ -387,8 +413,9 @@ class Dispatcher:
387
413
  if method == "tools/call":
388
414
  return self._tools_call(params)
389
415
  # 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).
416
+ # found", which is JSON-RPC's own answer for a method a server does not implement. The current
417
+ # official client opens with `server/discover` and falls back to `initialize`. Neither real client
418
+ # *enforces* -32601 (both also fall back on `{}`, F-16), so only a raw-frame test pins it.
392
419
  raise _RpcError(-32601, f"method not found: {method}")
393
420
 
394
421
  def _initialize(self, params: Any) -> dict[str, Any]:
dev_setup/mcp/http.py ADDED
@@ -0,0 +1,422 @@
1
+ """The HTTP front end: MCP over `POST /mcp`, REST, and the OpenAPI document (docs/specs/mcp).
2
+
3
+ Every route sits behind the same three checks, in this order, **before** any route is looked at:
4
+
5
+ 1. `Origin` and `Host` (FR-26) — a web page can send requests to `http://localhost:8765`, and DNS
6
+ rebinding makes the browser's own origin checks meaningless, so a request from a browser or a
7
+ rebinding page is refused here. Failure is `403` and is checked *before* the token, so the answer
8
+ never reveals whether a token would have been accepted.
9
+ 2. The bearer token (FR-24), compared in constant time. `401`.
10
+ 3. Only then the route, the method and the body.
11
+
12
+ There are no CORS headers, ever (FR-28): a browser is not a supported client. There are no sessions
13
+ and no SSE stream (SD-6): `GET /mcp` is `405`, which Claude Code reads as "this server has no
14
+ stream" and carries on (F-8).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hmac
20
+ import ipaddress
21
+ import json
22
+ import os
23
+ import signal
24
+ import socket
25
+ import threading
26
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27
+ from typing import Any
28
+ from urllib.parse import urlsplit
29
+
30
+ from dev_setup import verbose
31
+ from dev_setup.mcp import openapi
32
+ from dev_setup.mcp.core import (
33
+ Dispatcher,
34
+ UnknownTool,
35
+ rest_result,
36
+ )
37
+
38
+ MAX_BODY = 1024 * 1024 # FR-18: a request body over 1 MiB is refused
39
+ _DRAIN_LIMIT = 16 * MAX_BODY # how much of a refused body is read and thrown away before closing
40
+
41
+
42
+ def host_allowed(header: str | None, *, port: int, allow_hosts: frozenset[str]) -> bool:
43
+ """Whether a `Host` header names this server (FR-26).
44
+
45
+ The port must be the bound one, and the name must be `localhost`, an IP-address literal, or one
46
+ given with `--allow-host`. Any other hostname is refused: DNS rebinding needs a *name* the
47
+ attacker controls, which an address literal is not — and a container reaches the host as
48
+ `host.docker.internal` or a bridge IP, so the rule must not hard-code the bound address.
49
+ """
50
+ if not header or any(ch in header for ch in "@/\\ ?#\t"):
51
+ return False # userinfo, a path or whitespace: not a host and port, whatever it parses as
52
+ try:
53
+ parts = urlsplit("//" + header)
54
+ name, host_port = parts.hostname, parts.port
55
+ except ValueError:
56
+ return False
57
+ if name is None or host_port != port:
58
+ return False
59
+ if name == "localhost":
60
+ return True
61
+ try:
62
+ ipaddress.ip_address(name)
63
+ return True
64
+ except ValueError:
65
+ return name in allow_hosts
66
+
67
+
68
+ class _IdleAware:
69
+ """The request stream, reporting whether its connection is waiting for a request.
70
+
71
+ The handler reads one line at a time and the connection only *waits* inside that read. A
72
+ keep-alive connection a client has left open is blocked there; a connection running a tool is
73
+ not, because its request line has already been read. Shutdown needs the difference: it must wait
74
+ for the second kind and not for the first (FR-30).
75
+ """
76
+
77
+ def __init__(self, raw: Any, server: McpHTTPServer, conn: socket.socket) -> None:
78
+ self._raw, self._server, self._conn = raw, server, conn
79
+
80
+ def readline(self, *args: Any) -> bytes:
81
+ self._server.track(self._conn, idle=True)
82
+ try:
83
+ return self._raw.readline(*args)
84
+ finally:
85
+ self._server.track(self._conn, idle=False)
86
+
87
+ def __getattr__(self, name: str) -> Any:
88
+ return getattr(self._raw, name)
89
+
90
+
91
+ class McpHTTPServer(ThreadingHTTPServer):
92
+ """A threaded server that carries what its handlers need.
93
+
94
+ Request threads are **not** daemons: `server_close()` joins them, so closing the server waits for
95
+ a running install rather than killing it half-way (FR-30).
96
+ """
97
+
98
+ daemon_threads = False
99
+ allow_reuse_address = True # a restart is not blocked by TIME_WAIT; a *busy* port still fails
100
+ request_queue_size = 32
101
+
102
+ def __init__(
103
+ self,
104
+ address: tuple[str, int],
105
+ dispatcher: Dispatcher,
106
+ *,
107
+ token: str,
108
+ allow_hosts: frozenset[str],
109
+ allow_origins: frozenset[str],
110
+ ) -> None:
111
+ family = socket.getaddrinfo(address[0], address[1], type=socket.SOCK_STREAM)[0][0]
112
+ self.address_family = family
113
+ self.dispatcher = dispatcher
114
+ self.token = token.encode("utf-8")
115
+ self.allow_hosts = allow_hosts
116
+ self.allow_origins = allow_origins
117
+ self.stopping = False
118
+ self._connections: dict[socket.socket, bool] = {} # connection -> waiting for a request?
119
+ self._connections_lock = threading.Lock()
120
+ super().__init__(address, _Handler)
121
+
122
+ def track(self, conn: socket.socket, *, idle: bool) -> None:
123
+ with self._connections_lock:
124
+ self._connections[conn] = idle
125
+
126
+ def untrack(self, conn: socket.socket) -> None:
127
+ with self._connections_lock:
128
+ self._connections.pop(conn, None)
129
+
130
+ def server_close(self) -> None:
131
+ """Stop for good, waiting for requests that are *running* — not for idle connections.
132
+
133
+ `ThreadingMixIn.server_close` joins every request thread, and a thread whose client left a
134
+ keep-alive connection open is blocked reading a request that will never come. Those are woken
135
+ (their read ends); a busy connection finishes its response and is then told to close.
136
+ """
137
+ self.stopping = True
138
+ with self._connections_lock:
139
+ idle = [c for c, waiting in self._connections.items() if waiting]
140
+ for conn in idle:
141
+ try:
142
+ conn.shutdown(socket.SHUT_RD)
143
+ except OSError:
144
+ pass
145
+ super().server_close()
146
+
147
+ def server_bind(self) -> None:
148
+ # HTTPServer.server_bind asks the resolver for this machine's FQDN, which can stall for
149
+ # seconds on a host with a bad resolver; nothing here uses the name.
150
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
151
+ self.socket.bind(self.server_address)
152
+ self.server_address = self.socket.getsockname()
153
+ self.server_name = str(self.server_address[0])
154
+ self.server_port = self.server_address[1]
155
+
156
+ @property
157
+ def bound_port(self) -> int:
158
+ return int(self.server_address[1])
159
+
160
+
161
+ class _Handler(BaseHTTPRequestHandler):
162
+ protocol_version = "HTTP/1.1" # keep-alive: clients reuse a connection for a whole session
163
+ server: McpHTTPServer # type: ignore[assignment]
164
+
165
+ # -- plumbing -----------------------------------------------------------------------------
166
+
167
+ def setup(self) -> None:
168
+ super().setup()
169
+ self.rfile = _IdleAware(self.rfile, self.server, self.connection)
170
+ self.server.track(self.connection, idle=True)
171
+
172
+ def finish(self) -> None:
173
+ self.server.untrack(self.connection)
174
+ super().finish()
175
+
176
+ def version_string(self) -> str:
177
+ return "devstuff" # not the Python and library versions the default advertises
178
+
179
+ def log_message(self, format: str, *args: Any) -> None:
180
+ verbose.log(f"http {self.address_string()} {format % args}")
181
+
182
+ def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None:
183
+ # The base class calls this for a malformed request line, an over-long header, an unknown
184
+ # protocol version. It would answer in HTML; every body here is JSON.
185
+ self.close_connection = True
186
+ try:
187
+ self._send(code, {"error": message or "bad request"})
188
+ except OSError:
189
+ pass
190
+
191
+ def _send_raw_json(self, status: int, text: str) -> None:
192
+ """Send an already-serialised JSON body (a JSON-RPC reply is built as text by the core)."""
193
+ self._send_bytes(status, text.encode("utf-8"), has_body=True, headers=None)
194
+
195
+ def _send(self, status: int, payload: Any | None, *, headers: dict[str, str] | None = None) -> None:
196
+ body = b"" if payload is None else json.dumps(payload).encode("utf-8")
197
+ self._send_bytes(status, body, has_body=payload is not None, headers=headers)
198
+
199
+ def _send_bytes(
200
+ self, status: int, body: bytes, *, has_body: bool, headers: dict[str, str] | None
201
+ ) -> None:
202
+ self._settle_request_body()
203
+ if self.server.stopping:
204
+ self.close_connection = True
205
+ self.send_response(status)
206
+ if has_body:
207
+ self.send_header("Content-Type", "application/json")
208
+ self.send_header("Content-Length", str(len(body)))
209
+ self.send_header("Cache-Control", "no-store")
210
+ for name, value in (headers or {}).items():
211
+ self.send_header(name, value)
212
+ if self.close_connection:
213
+ self.send_header("Connection", "close")
214
+ self.end_headers()
215
+ if self.command != "HEAD":
216
+ self.wfile.write(body)
217
+ verbose.log(f"http {self.command} {self.path} -> {status}")
218
+
219
+ def _error(self, status: int, message: str, **kw: Any) -> None:
220
+ self._send(status, {"error": message}, **kw)
221
+
222
+ # -- the request body ---------------------------------------------------------------------
223
+
224
+ def _content_length(self) -> int | None:
225
+ """The declared body length, or None when it cannot be trusted (sets `close_connection`)."""
226
+ if "Transfer-Encoding" in self.headers:
227
+ return None # chunked bodies are not decoded here; reading one as the next request is worse
228
+ raw = self.headers.get("Content-Length")
229
+ if raw is None:
230
+ return 0
231
+ if not raw.isascii() or not raw.isdigit():
232
+ return None
233
+ return int(raw)
234
+
235
+ def _settle_request_body(self) -> None:
236
+ """Before answering, consume (or abandon the connection over) a body nobody read, so its
237
+ bytes are not parsed as the next request — and so a client sending a large refused body
238
+ still receives the answer instead of a connection reset."""
239
+ if getattr(self, "_body_settled", False):
240
+ return
241
+ self._body_settled = True
242
+ length = self._content_length()
243
+ if length is None:
244
+ self.close_connection = True
245
+ return
246
+ if length == 0:
247
+ return
248
+ if length > _DRAIN_LIMIT:
249
+ self.close_connection = True
250
+ return
251
+ remaining = length
252
+ try:
253
+ while remaining > 0:
254
+ chunk = self.rfile.read(min(remaining, 65536))
255
+ if not chunk:
256
+ self.close_connection = True
257
+ return
258
+ remaining -= len(chunk)
259
+ except OSError:
260
+ self.close_connection = True
261
+ return
262
+ if length > MAX_BODY:
263
+ self.close_connection = True # we did read it, but a client that sends this much can reconnect
264
+
265
+ def _read_body(self) -> bytes | None:
266
+ """The body, or None after having answered `400`/`413` already."""
267
+ length = self._content_length()
268
+ if length is None:
269
+ self._error(400, "invalid Content-Length, or a chunked body (not supported)")
270
+ return None
271
+ if length > MAX_BODY:
272
+ self._error(413, f"request body over {MAX_BODY} bytes")
273
+ return None
274
+ data = self.rfile.read(length) if length else b""
275
+ self._body_settled = True
276
+ if len(data) != length:
277
+ self.close_connection = True
278
+ self._error(400, "request body shorter than its Content-Length")
279
+ return None
280
+ return data
281
+
282
+ # -- the checks in front of every route -----------------------------------------------------
283
+
284
+ def _origin_ok(self) -> bool:
285
+ origins = self.headers.get_all("Origin") or []
286
+ return all(o in self.server.allow_origins for o in origins)
287
+
288
+ def _authorized(self) -> bool:
289
+ header = self.headers.get("Authorization", "")
290
+ scheme, _, credential = header.partition(" ")
291
+ presented = credential.strip().encode("utf-8", "replace") if scheme.lower() == "bearer" else b""
292
+ # Compared even when empty, so a missing credential takes the same path as a wrong one.
293
+ return hmac.compare_digest(presented, self.server.token) and bool(presented)
294
+
295
+ # -- routing --------------------------------------------------------------------------------
296
+
297
+ def _handle(self) -> None:
298
+ self._body_settled = False
299
+ srv = self.server
300
+ if not self._origin_ok() or not host_allowed(
301
+ self.headers.get("Host"), port=srv.bound_port, allow_hosts=srv.allow_hosts
302
+ ):
303
+ return self._error(403, "forbidden host or origin")
304
+ if not self._authorized():
305
+ return self._error(401, "missing or invalid bearer token", headers={"WWW-Authenticate": "Bearer"})
306
+
307
+ path = urlsplit(self.path).path
308
+ method = self.command
309
+ if path == "/mcp":
310
+ return self._mcp() if method == "POST" else self._not_allowed("POST")
311
+ if path == "/tools":
312
+ return self._tool_list() if method == "GET" else self._not_allowed("GET")
313
+ if path == "/openapi.json":
314
+ return self._document() if method == "GET" else self._not_allowed("GET")
315
+ name = path.removeprefix("/tools/") if path.startswith("/tools/") else ""
316
+ if name and "/" not in name:
317
+ # A method check first, for every name: GET on a gated-off tool must look exactly like
318
+ # GET on one that never existed (FR-3).
319
+ return self._rest_call(name) if method == "POST" else self._not_allowed("POST")
320
+ return self._error(404, "not found")
321
+
322
+ do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = _handle
323
+
324
+ def _not_allowed(self, allow: str) -> None:
325
+ self._error(405, f"method not allowed; use {allow}", headers={"Allow": allow})
326
+
327
+ # -- the routes -----------------------------------------------------------------------------
328
+
329
+ def _mcp(self) -> None:
330
+ raw = self._read_body()
331
+ if raw is None:
332
+ return
333
+ try:
334
+ text = raw.decode("utf-8")
335
+ except UnicodeDecodeError:
336
+ from dev_setup.mcp.core import error_text
337
+
338
+ reply: str | None = error_text(None, -32700, "parse error: not valid UTF-8")
339
+ else:
340
+ reply = self.server.dispatcher.handle_text(text)
341
+ if reply is None:
342
+ return self._send(202, None) # a notification: accepted, nothing to say
343
+ self._send_raw_json(200, reply)
344
+
345
+ def _tool_list(self) -> None:
346
+ self._send(200, self.server.dispatcher.toolbox.openai_tools())
347
+
348
+ def _document(self) -> None:
349
+ # `Host` was validated above, so it is a name this client can reach us by — a container gets
350
+ # `host.docker.internal`, not `127.0.0.1`, in the URL it will follow.
351
+ url = f"http://{self.headers.get('Host')}"
352
+ self._send(200, openapi.build(self.server.dispatcher.toolbox, server_url=url))
353
+
354
+ def _rest_call(self, name: str) -> None:
355
+ dispatcher = self.server.dispatcher
356
+ if dispatcher.toolbox.get(name) is None:
357
+ return self._error(404, "not found") # unknown and gated-off read the same (FR-3)
358
+ raw = self._read_body()
359
+ if raw is None:
360
+ return
361
+ if not raw.strip():
362
+ if dispatcher.toolbox.requires_body(name):
363
+ return self._error(400, "this tool has a required parameter: send a JSON object body")
364
+ arguments: dict[str, Any] = {}
365
+ else:
366
+ try:
367
+ arguments = json.loads(raw.decode("utf-8"))
368
+ except (UnicodeDecodeError, ValueError, RecursionError):
369
+ return self._error(400, "the body is not valid JSON")
370
+ if not isinstance(arguments, dict):
371
+ return self._error(400, "the body must be a JSON object")
372
+ try:
373
+ result = dispatcher.call(name, arguments)
374
+ except UnknownTool:
375
+ return self._error(404, "not found")
376
+ self._send(200, rest_result(result))
377
+
378
+
379
+ def make_server(
380
+ dispatcher: Dispatcher,
381
+ *,
382
+ host: str,
383
+ port: int,
384
+ token: str,
385
+ allow_hosts: tuple[str, ...] | frozenset[str] = (),
386
+ allow_origins: tuple[str, ...] | frozenset[str] = (),
387
+ ) -> McpHTTPServer:
388
+ """Bind and return the server. Raises `OSError` when the address is busy or unusable."""
389
+ return McpHTTPServer(
390
+ (host, port),
391
+ dispatcher,
392
+ token=token,
393
+ allow_hosts=frozenset(h.lower() for h in allow_hosts),
394
+ allow_origins=frozenset(allow_origins),
395
+ )
396
+
397
+
398
+ def serve(server: McpHTTPServer) -> int:
399
+ """Serve until SIGINT/SIGTERM, then wait for running calls and return 0 (FR-30).
400
+
401
+ The first signal stops accepting requests; a request already running is allowed to finish,
402
+ because an installer killed half-way is worse than one waited for. A second signal exits at once.
403
+ """
404
+ received = 0
405
+
406
+ def on_signal(signum: int, _frame: object) -> None:
407
+ nonlocal received
408
+ received += 1
409
+ if received > 1:
410
+ os._exit(128 + signum)
411
+ # `shutdown()` waits for `serve_forever` to return, and that loop is running on this very
412
+ # thread — calling it from here would wait for itself.
413
+ threading.Thread(target=server.shutdown, name="mcp-shutdown", daemon=True).start()
414
+
415
+ signal.signal(signal.SIGINT, on_signal)
416
+ signal.signal(signal.SIGTERM, on_signal)
417
+ try:
418
+ # The default poll interval is 0.5s, which is how long a shutdown would wait to notice.
419
+ server.serve_forever(poll_interval=0.1)
420
+ finally:
421
+ server.server_close() # joins the request threads: a running install finishes first
422
+ return 0
@@ -0,0 +1,139 @@
1
+ """The OpenAPI 3.1 document for the REST front end (docs/specs/mcp, G-2, FR-22).
2
+
3
+ Pure: a toolbox goes in, a dict comes out. It is generated from the **same** `Toolbox` object that
4
+ answers `tools/list`, so the three framings cannot disagree about which tools exist or what their
5
+ arguments are (FR-22b); `tests/test_mcp_openapi.py` checks that, and checks the *server* against the
6
+ document rather than trusting the two to agree (FR-22c).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ from dev_setup import __version__
14
+ from dev_setup.mcp.core import Gate, Toolbox
15
+
16
+ # The one operation that is not a tool. Its id is a legal tool name on purpose — a client that turns
17
+ # every operationId into a function name can — and a tool *key* equal to it is left out of the
18
+ # toolbox, so the two kinds of operation can never collide (core.RESERVED_NAMES).
19
+ CATALOG_OPERATION_ID = "openai_tool_list"
20
+
21
+ _DESCRIPTION = (
22
+ "devstuff's tools as plain HTTP. `GET /tools` lists them in the OpenAI function-calling shape and "
23
+ "`POST /tools/{name}` runs one. Every request needs `Authorization: Bearer <token>`.\n\n"
24
+ "`POST /mcp` is the same tool set spoken as MCP (Streamable HTTP, JSON responses only). It is the "
25
+ "MCP protocol's own endpoint rather than a REST operation, so it is not listed below."
26
+ )
27
+
28
+ _CHANGES_MACHINE = " This tool changes this machine."
29
+
30
+
31
+ def _error(description: str) -> dict[str, Any]:
32
+ return {
33
+ "description": description,
34
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}},
35
+ }
36
+
37
+
38
+ def _tool_operation(box: Toolbox, key: str) -> dict[str, Any]:
39
+ tool = box.get(key)
40
+ assert tool is not None
41
+ description = tool.description
42
+ if box.gate(key) is not Gate.READ_ONLY:
43
+ description += _CHANGES_MACHINE
44
+ schema = box.input_schema(tool)
45
+ request: dict[str, Any] = {"content": {"application/json": {"schema": schema}}}
46
+ if schema.get("required"):
47
+ request["required"] = True
48
+ return {
49
+ "operationId": key,
50
+ "summary": tool.name,
51
+ "description": description,
52
+ "requestBody": request,
53
+ "responses": {
54
+ "200": {
55
+ "description": "The tool ran. `is_error` is true when the tool itself failed.",
56
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ToolResult"}}},
57
+ },
58
+ "400": _error("The body is not valid JSON, or not a JSON object, or is missing and required."),
59
+ "401": _error("Missing or wrong bearer token."),
60
+ "403": _error("Forbidden `Host` or `Origin`."),
61
+ "404": _error("No such tool, or it is not enabled on this server."),
62
+ "405": _error("Wrong method for this path."),
63
+ "413": _error("The request body is over 1 MiB."),
64
+ },
65
+ }
66
+
67
+
68
+ def build(box: Toolbox, *, server_url: str) -> dict[str, Any]:
69
+ paths: dict[str, Any] = {
70
+ "/tools": {
71
+ "get": {
72
+ "operationId": CATALOG_OPERATION_ID,
73
+ "summary": "List the tools",
74
+ "description": "The enabled tools as an array of OpenAI function-calling objects.",
75
+ "responses": {
76
+ "200": {
77
+ "description": "The tools.",
78
+ "content": {
79
+ "application/json": {
80
+ "schema": {
81
+ "type": "array",
82
+ "items": {"$ref": "#/components/schemas/OpenAIFunction"},
83
+ }
84
+ }
85
+ },
86
+ },
87
+ "401": _error("Missing or wrong bearer token."),
88
+ "403": _error("Forbidden `Host` or `Origin`."),
89
+ "405": _error("Wrong method for this path."),
90
+ },
91
+ }
92
+ }
93
+ }
94
+ for key in box.names():
95
+ paths[f"/tools/{key}"] = {"post": _tool_operation(box, key)}
96
+ return {
97
+ "openapi": "3.1.0",
98
+ "info": {"title": "devstuff", "version": __version__, "description": _DESCRIPTION},
99
+ "servers": [{"url": server_url}],
100
+ "security": [{"bearerAuth": []}],
101
+ "paths": paths,
102
+ "components": {
103
+ "securitySchemes": {"bearerAuth": {"type": "http", "scheme": "bearer"}},
104
+ "schemas": {
105
+ "ToolResult": {
106
+ "type": "object",
107
+ "properties": {
108
+ "is_error": {"type": "boolean"},
109
+ "text": {"type": "string"},
110
+ "note": {"type": "string", "description": "Advisory; kept apart from `text`."},
111
+ },
112
+ "required": ["is_error", "text"],
113
+ "additionalProperties": False,
114
+ },
115
+ "Error": {
116
+ "type": "object",
117
+ "properties": {"error": {"type": "string"}},
118
+ "required": ["error"],
119
+ "additionalProperties": False,
120
+ },
121
+ "OpenAIFunction": {
122
+ "type": "object",
123
+ "properties": {
124
+ "type": {"const": "function"},
125
+ "function": {
126
+ "type": "object",
127
+ "properties": {
128
+ "name": {"type": "string"},
129
+ "description": {"type": "string"},
130
+ "parameters": {"type": "object"},
131
+ },
132
+ "required": ["name", "description", "parameters"],
133
+ },
134
+ },
135
+ "required": ["type", "function"],
136
+ },
137
+ },
138
+ },
139
+ }
@@ -0,0 +1,146 @@
1
+ """`devstuff mcp --print-config TARGET`: a snippet to paste into a client (docs/specs/mcp, FR-31, F-16).
2
+
3
+ Pure: it formats what it is given and touches no file, socket or process. The one secret on the page,
4
+ the bearer token, is a *path* in every snippet — the client's own shell reads the file when the command
5
+ runs — so a snippet is safe to paste into a ticket or a chat.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import shlex
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ TARGETS = ("claude-code", "claude-desktop", "openapi")
17
+ NAME = "devstuff"
18
+
19
+ _WILDCARDS = ("", "0.0.0.0", "::") # "every address": a place to listen, not a place to connect
20
+
21
+
22
+ class ConfigError(ValueError):
23
+ """A snippet that cannot be printed honestly for these flags."""
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Spec:
28
+ launcher: tuple[str, ...]
29
+ http: bool
30
+ host: str
31
+ port: int
32
+ token_file: Path
33
+ allow_install: bool
34
+ allow_functions: bool
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Rendered:
39
+ text: str
40
+ notes: tuple[str, ...] = ()
41
+
42
+
43
+ def launcher(argv0: str, executable: str) -> tuple[str, ...]:
44
+ """How to start the devstuff that is running now, as absolute words.
45
+
46
+ A GUI application usually does not inherit the shell's `PATH`, so a bare `devstuff` would work in
47
+ a terminal and fail in Claude Desktop. A console script keeps the path it was started by (a
48
+ symlink such as `~/.local/bin/devstuff` is stable; the venv it points into is not). Anything else
49
+ — `python -m dev_setup`, the `./devstuff` wrapper — is this interpreter running the module, which
50
+ is exactly the code that is answering.
51
+ """
52
+ if argv0:
53
+ candidate = Path(argv0)
54
+ if candidate.name == "devstuff":
55
+ absolute = Path(os.path.abspath(candidate))
56
+ if absolute.is_file() and os.access(absolute, os.X_OK):
57
+ return (str(absolute),)
58
+ return (os.path.abspath(executable), "-m", "dev_setup")
59
+
60
+
61
+ def _gate_flags(spec: Spec) -> list[str]:
62
+ flags = []
63
+ if spec.allow_install:
64
+ flags.append("--allow-install")
65
+ if spec.allow_functions:
66
+ flags.append("--allow-functions")
67
+ return flags
68
+
69
+
70
+ def _connect_host(spec: Spec) -> tuple[str, tuple[str, ...]]:
71
+ if spec.host in _WILDCARDS:
72
+ shown = spec.host or "every address"
73
+ return "127.0.0.1", (
74
+ f"the server would be listening on every address ({shown}); the URL below uses 127.0.0.1, "
75
+ "which reaches it from this machine. From another machine, use this machine's own name "
76
+ "or address.",
77
+ )
78
+ return (f"[{spec.host}]" if ":" in spec.host else spec.host), ()
79
+
80
+
81
+ def _base_url(spec: Spec) -> tuple[str, tuple[str, ...]]:
82
+ if spec.port == 0:
83
+ raise ConfigError(
84
+ "--port 0 asks the OS for a port, so there is no port to write down yet. Pick a port "
85
+ "(the default is fine) and pass it to both the server and --print-config."
86
+ )
87
+ host, notes = _connect_host(spec)
88
+ return f"http://{host}:{spec.port}", notes
89
+
90
+
91
+ def _server_command(spec: Spec) -> str:
92
+ """The line that starts the server these snippets talk to, for the note on stderr."""
93
+ words = [*spec.launcher, "mcp", "--http"]
94
+ if spec.host:
95
+ words += ["--host", spec.host]
96
+ words += ["--port", str(spec.port)]
97
+ if spec.token_file:
98
+ words += ["--token-file", str(spec.token_file)]
99
+ words += _gate_flags(spec)
100
+ return shlex.join(words)
101
+
102
+
103
+ def _claude_code(spec: Spec) -> Rendered:
104
+ if not spec.http:
105
+ words = ["claude", "mcp", "add", NAME, "--", *spec.launcher, "mcp", *_gate_flags(spec)]
106
+ return Rendered(shlex.join(words) + "\n")
107
+ base, notes = _base_url(spec)
108
+ # `$(cat …)` is expanded by the shell that runs this command, so the token is read when it is
109
+ # pasted and never appears in what is printed. Quoting restarts inside `$( )`.
110
+ header = f'"Authorization: Bearer $(cat {shlex.quote(str(spec.token_file))})"'
111
+ text = f"claude mcp add --transport http {NAME} {base}/mcp --header {header}\n"
112
+ return Rendered(text, (*notes, f"this talks to a server you start yourself: {_server_command(spec)}"))
113
+
114
+
115
+ def _claude_desktop(spec: Spec) -> Rendered:
116
+ if spec.http:
117
+ raise ConfigError(
118
+ "Claude Desktop launches a command and talks to it over stdio, so there is no HTTP form to "
119
+ "print. Leave out --http."
120
+ )
121
+ command, *args = spec.launcher
122
+ entry = {"command": command, "args": [*args, "mcp", *_gate_flags(spec)]}
123
+ return Rendered(json.dumps({"mcpServers": {NAME: entry}}, indent=2) + "\n")
124
+
125
+
126
+ def _openapi(spec: Spec) -> Rendered:
127
+ if not spec.http:
128
+ raise ConfigError("the OpenAPI document is served by the HTTP server: add --http.")
129
+ base, notes = _base_url(spec)
130
+ text = (
131
+ f"Base URL: {base}\n"
132
+ f"OpenAPI URL: {base}/openapi.json\n"
133
+ f"Header: Authorization: Bearer <the contents of {spec.token_file}>\n"
134
+ )
135
+ return Rendered(text, (*notes, f"this talks to a server you start yourself: {_server_command(spec)}"))
136
+
137
+
138
+ _RENDERERS = {"claude-code": _claude_code, "claude-desktop": _claude_desktop, "openapi": _openapi}
139
+
140
+
141
+ def render(target: str, spec: Spec) -> Rendered:
142
+ try:
143
+ renderer = _RENDERERS[target]
144
+ except KeyError:
145
+ raise ConfigError(f"unknown target {target!r}; choose one of: {', '.join(TARGETS)}.") from None
146
+ return renderer(spec)
dev_setup/mcp/stdio.py CHANGED
@@ -33,9 +33,13 @@ class Channel:
33
33
  wfile: BinaryIO
34
34
 
35
35
 
36
- def isolate_stdio() -> Channel:
36
+ def isolate_stdio(*, channel: bool = True) -> Channel | None:
37
37
  """Move the protocol onto private descriptors and repoint the standard ones (FR-11).
38
38
 
39
+ `channel=False` is the HTTP server: it has no protocol on stdio, but an installer that prints to
40
+ fd 1 or reads fd 0 must still be kept off the terminal, so the standard descriptors are repointed
41
+ and nothing is kept.
42
+
39
43
  The private fds are not inheritable (PEP 446 makes `os.dup` results so), so no child can read
40
44
  from or write to the channel; fd 0 and fd 1 stay inheritable, so a child that reads stdin sees
41
45
  EOF and one that writes stdout lands on stderr.
@@ -45,12 +49,14 @@ def isolate_stdio() -> Channel:
45
49
  stream.flush()
46
50
  except (OSError, ValueError):
47
51
  pass
48
- in_fd = os.dup(0)
49
- out_fd = os.dup(1)
52
+ in_fd = os.dup(0) if channel else -1
53
+ out_fd = os.dup(1) if channel else -1
50
54
  devnull = os.open(os.devnull, os.O_RDONLY)
51
55
  os.dup2(devnull, 0)
52
56
  os.close(devnull)
53
57
  os.dup2(2, 1)
58
+ if not channel:
59
+ return None
54
60
  # Unbuffered out: a reply is written whole and at once, and there is no buffer left holding a
55
61
  # frame a dead client never took (which would be flushed, and fail, again at interpreter exit).
56
62
  return Channel(os.fdopen(in_fd, "rb"), os.fdopen(out_fd, "wb", buffering=0))
@@ -144,6 +150,7 @@ def run(dispatcher: Dispatcher) -> int:
144
150
  exits immediately (FR-30).
145
151
  """
146
152
  channel = isolate_stdio()
153
+ assert channel is not None
147
154
  received = 0
148
155
 
149
156
  def on_signal(signum: int, _frame: object) -> None:
dev_setup/mcp/token.py ADDED
@@ -0,0 +1,85 @@
1
+ """The bearer token for `devstuff mcp --http` (docs/specs/mcp, FR-24, SD-7, SD-8).
2
+
3
+ It lives in a file, not on a command line or in a URL: a file path can be logged and pasted safely,
4
+ and a token cannot. The file persists across restarts, so a client's `Authorization` header stays
5
+ right (a fresh token per run broke every configured client on every restart — SD-8). It is held to
6
+ an ssh key's standard: owned by the user, private, and **never printed** — not here, not in an
7
+ error, not in the banner.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import secrets
14
+ import stat
15
+ from pathlib import Path
16
+
17
+ MIN_LENGTH = 16 # a hand-written token shorter than this is a password, and this one guards an installer
18
+
19
+
20
+ class TokenError(RuntimeError):
21
+ """The token file cannot be used. Messages never contain the token."""
22
+
23
+
24
+ def default_path() -> Path:
25
+ state = os.environ.get("XDG_STATE_HOME")
26
+ base = Path(state) if state else Path.home() / ".local" / "state"
27
+ return base / "devstuff" / "mcp-token"
28
+
29
+
30
+ def load(path: Path | None = None, *, rotate: bool = False) -> tuple[str, Path]:
31
+ """The token and the file it came from, creating or replacing the file as asked.
32
+
33
+ A file readable or writable by group or others is refused *even when rotating*: the old secret
34
+ was exposed, and quietly fixing the mode would hide that from the one person who needs to know.
35
+ """
36
+ path = path or default_path()
37
+ try:
38
+ if not path.exists() and not path.is_symlink():
39
+ return _write(path), path
40
+ _check_mode(path)
41
+ if rotate:
42
+ return _write(path), path
43
+ return _read(path), path
44
+ except OSError as exc:
45
+ raise TokenError(f"cannot use token file {path}: {exc.strerror or exc}") from exc
46
+
47
+
48
+ def _check_mode(path: Path) -> None:
49
+ mode = stat.S_IMODE(os.stat(path).st_mode)
50
+ if mode & 0o077:
51
+ raise TokenError(
52
+ f"token file {path} has unsafe permissions ({mode:04o}): it must not be accessible to group "
53
+ f"or others. Fix it with `chmod 600 {path}`, or replace it with --rotate-token after "
54
+ "treating the old token as exposed"
55
+ )
56
+
57
+
58
+ def _read(path: Path) -> str:
59
+ value = path.read_text(encoding="utf-8").strip()
60
+ if len(value) < MIN_LENGTH or not value.isascii() or not value.isprintable() or " " in value:
61
+ raise TokenError(
62
+ f"token file {path} does not hold a usable token (at least {MIN_LENGTH} printable characters, "
63
+ "one line, no spaces). Put one there, or let --rotate-token write a new one"
64
+ )
65
+ return value
66
+
67
+
68
+ def _write(path: Path) -> str:
69
+ value = secrets.token_urlsafe(32)
70
+ created = not path.parent.exists()
71
+ path.parent.mkdir(parents=True, exist_ok=True)
72
+ if created:
73
+ # A directory this module creates is private. One that already exists is left alone:
74
+ # `--token-file` may point into a directory the user keeps for other reasons.
75
+ path.parent.chmod(0o700)
76
+ tmp = path.with_name(f".{path.name}.{secrets.token_hex(4)}.tmp")
77
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
78
+ try:
79
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
80
+ handle.write(value + "\n")
81
+ os.replace(tmp, path) # atomic: a reader never sees a half-written token
82
+ except BaseException:
83
+ tmp.unlink(missing_ok=True)
84
+ raise
85
+ return value
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: devstuff
3
- Version: 2.16.0
3
+ Version: 2.18.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>
@@ -1181,8 +1181,59 @@ Workspace tools (`read_file`, `run_command`, …) never exist here — the clien
1181
1181
 
1182
1182
  The server has **no terminal**: an installer that needs a `sudo` password fails at once with a message telling the
1183
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/).
1184
+ Logs (`-v`, `-vv`) go to stderr. Design and measurements: [`docs/specs/mcp/`](docs/specs/mcp/).
1185
+
1186
+ ### Over HTTP, and as an OpenAPI tool server
1187
+
1188
+ ```bash
1189
+ devstuff mcp --http # 127.0.0.1:8765, this machine only
1190
+ devstuff mcp --http --allow-install # …and install_tool
1191
+ claude mcp add --transport http devstuff http://127.0.0.1:8765/mcp \
1192
+ --header "Authorization: Bearer $(cat ~/.local/state/devstuff/mcp-token)"
1193
+ ```
1194
+
1195
+ One server, three ways in — all of them show **the same tools**, and all need `Authorization: Bearer <token>`:
1196
+
1197
+ | Path | What it is |
1198
+ |---|---|
1199
+ | `POST /mcp` | MCP (Streamable HTTP, JSON responses; no sessions, no stream) — Claude Code, Claude Desktop, any MCP client |
1200
+ | `GET /tools` | The tools as an OpenAI function-calling array |
1201
+ | `POST /tools/<name>` | Run one tool: a JSON object body in, `{"is_error": …, "text": …}` out |
1202
+ | `GET /openapi.json` | An OpenAPI 3.1 document for the two rows above — point Open WebUI or any OpenAPI tool client at it |
1203
+
1204
+ The token is created on first use in `~/.local/state/devstuff/mcp-token` (mode `0600`) and **reused on every
1205
+ run**, so a client's configuration survives a restart. `devstuff` prints the file's path, never its contents.
1206
+ `--rotate-token` replaces it; a token file that group or others can read is refused.
1207
+
1208
+ | Flag | Meaning |
1209
+ |---|---|
1210
+ | `--host ADDR` / `--port N` | Default `127.0.0.1:8765`. A busy port is an error — it never picks another, which would break every configured client. `--port 0` asks the OS |
1211
+ | `--allow-host NAME` | Also accept this name in the `Host` header, e.g. `host.docker.internal` (Open WebUI in Docker reaches the host that way). `localhost` and IP addresses are always accepted |
1212
+ | `--allow-origin ORIGIN` | Accept requests from this browser origin. Default none: a request carrying an `Origin` is refused, so a web page cannot drive the server |
1213
+ | `--token-file PATH` | Keep the token elsewhere |
1214
+
1215
+ ### Configuring a client
1216
+
1217
+ `--print-config TARGET` prints a snippet for the other flags you give, then exits — it starts nothing, creates no
1218
+ token file and **never contains the token** (the HTTP command reads it from the file when you run it). Commands use
1219
+ the absolute path of the `devstuff` that is running, since a GUI application usually does not inherit your shell's
1220
+ `PATH`.
1221
+
1222
+ ```bash
1223
+ devstuff mcp --allow-install --print-config claude-code # claude mcp add devstuff -- /…/devstuff mcp --allow-install
1224
+ devstuff mcp --print-config claude-desktop # the mcpServers JSON for claude_desktop_config.json
1225
+ devstuff mcp --http --print-config claude-code # the --transport http … --header "…$(cat <token file>)" form
1226
+ devstuff mcp --http --port 9000 --print-config openapi # base URL, /openapi.json URL and the header to send
1227
+ ```
1228
+
1229
+ The snippet alone is on stdout (notes go to stderr), so `… --print-config claude-desktop > snippet.json` is clean.
1230
+ `claude-desktop` has no HTTP form, `openapi` needs `--http`, and `--port 0` cannot be printed. Claude Code's
1231
+ `claude mcp list` is the quickest check that a configuration works. Claude Desktop is untested here.
1232
+
1233
+ A non-loopback `--host` is allowed and **warned about**: there is no TLS, so the token crosses the network in the
1234
+ clear, and anyone holding it can use every enabled tool. To reach a loopback server from another machine, tunnel
1235
+ instead, with the *same* local port (the `Host` header must carry the bound port):
1236
+ `ssh -L 8765:127.0.0.1:8765 you@host`.
1186
1237
 
1187
1238
  ---
1188
1239
 
@@ -61,7 +61,7 @@ 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/mcp_cmd.py,sha256=JPPIvSYXWHHwg9IZA2KsZ0KeIc1kD-X_iVsc231Fn58,3291
64
+ dev_setup/commands/mcp_cmd.py,sha256=UkScDupval0pHZhV1Mex6I8s9pnE7OS2Qf6zQhcQaxM,10261
65
65
  dev_setup/commands/outdated_cmd.py,sha256=afwYyq0M-tWVOk2qyXQqsdWSTK6yuFbVpbrOmMPKS_w,4757
66
66
  dev_setup/commands/profile_cmd.py,sha256=jo7al_nBwuWtzOLYKjcqEGmHp4eQrzM5s7ahv6iiGaw,18299
67
67
  dev_setup/commands/remove_cmd.py,sha256=Az0qMes4M5237c_ntQ1SemS38gTpLZy2GhSK_gUrw3s,4974
@@ -115,10 +115,14 @@ dev_setup/configure/starship/preview.py,sha256=ZaNhNA3AeHHtPnMqrJbB9XVVXDFbH1R36
115
115
  dev_setup/configure/starship/render.py,sha256=25O8w4IteVd_ELwmIWhcYAn042W6yZ--zbTMcJpzVJc,11277
116
116
  dev_setup/configure/starship/wizard.py,sha256=F3-xVQmZjYtiQAICyJXeSogjcASSsVbaP2b8YHAX9TM,28726
117
117
  dev_setup/mcp/__init__.py,sha256=a3DUEjK_mIpC4QsaPaArwKqaVvtujfzSu8WMpMh6G70,89
118
- dev_setup/mcp/core.py,sha256=5IlKkPXDUsdyKVbpSw3yDjkmY_92hdXlAOdK_a7SXsA,18898
118
+ dev_setup/mcp/core.py,sha256=I0zNOWLByBAcpJjE1oz9Bh2VefZF9sZL88TfTENwFHo,20038
119
+ dev_setup/mcp/http.py,sha256=w51uX-5LdgqS7M673JhGe_dHH9Oqdeg6qMkNrP6UjnU,17605
120
+ dev_setup/mcp/openapi.py,sha256=pT8cB_RnupVDi0ZQjSx13o2LnfylDhsv4UWiL5bbIt0,5864
121
+ dev_setup/mcp/printconfig.py,sha256=3u_b4UpDwJ95u0_AfZuZuch1_-bOojdAg-08c5l6g28,5442
119
122
  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,,
123
+ dev_setup/mcp/stdio.py,sha256=k-s2722_N2j92umkKo_Bq6KijfQGKFRudYVsh2H4xAk,6121
124
+ dev_setup/mcp/token.py,sha256=Pr7MCY6FtY8g2oQWB291mMooiZY0eu659Qk3mh9auWE,3397
125
+ devstuff-2.18.0.dist-info/METADATA,sha256=SCgNioi3McSeKjnnliE2LTT9KbWhFCAQByKu3WuKP5M,98475
126
+ devstuff-2.18.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
127
+ devstuff-2.18.0.dist-info/entry_points.txt,sha256=48ITy9ENdXDFrTHwAyVPUpq1MDmgFqcOisOo5mAR6OQ,53
128
+ devstuff-2.18.0.dist-info/RECORD,,