wingbox-http 0.13.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ # macOS
2
+ .DS_Store
3
+
4
+ # Python
5
+ __pycache__/
6
+ *.py[cod]
7
+ .ruff_cache/
8
+
9
+ # What Wingbox writes into a project (the graph, its cache, the report and the map)
10
+ .wingbox/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AILERON TECHNOLOGIES
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.5
2
+ Name: wingbox-http
3
+ Version: 0.13.0
4
+ Summary: Streamable HTTP transport for the Wingbox MCP server: call the code graph of a repository from another machine.
5
+ Project-URL: Homepage, https://wingbox.dev
6
+ Project-URL: Repository, https://github.com/aileron-tech/wingbox
7
+ Project-URL: Documentation, https://github.com/aileron-tech/wingbox#over-http-from-another-machine
8
+ Project-URL: Issues, https://github.com/aileron-tech/wingbox/issues
9
+ Author: Aileron Technologies
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: code-graph,impact-analysis,mcp,mcp-server,streamable-http,wingbox
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: wingbox==0.13.0
23
+ Description-Content-Type: text/markdown
24
+
25
+ # wingbox-http
26
+
27
+ Call the [Wingbox](https://wingbox.dev) code graph of a repository from another
28
+ machine. `wingbox-http` serves the Wingbox MCP server over the Streamable HTTP
29
+ transport of the Model Context Protocol: the same tools as `wingbox mcp` on
30
+ stdio (`impact`, `usages`, `build` and the rest), at one URL.
31
+
32
+ Use it when the repository and its graph live on a build server, a dev
33
+ container or a remote workstation, and the coding agent runs somewhere else.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install "wingbox[http]" # or: pipx install wingbox && pipx inject wingbox wingbox-http
39
+ ```
40
+
41
+ The transport is a package of its own on purpose: `wingbox` itself holds no
42
+ listening code. `wingbox-http` uses the Python standard library only, listens
43
+ and answers, and opens no connection of its own.
44
+
45
+ ## Run
46
+
47
+ On the machine that holds the repository:
48
+
49
+ ```bash
50
+ export WINGBOX_HTTP_TOKEN="$(openssl rand -hex 32)" # keep it; clients send it
51
+ wingbox mcp --http --root /path/to/project --host 0.0.0.0 --port 8765 \
52
+ --tls-cert fullchain.pem --tls-key privkey.pem
53
+ ```
54
+
55
+ `wingbox-http ...` is the same command. The server answers at
56
+ `https://<host>:8765/mcp`.
57
+
58
+ | Option | Meaning |
59
+ |---|---|
60
+ | `--root DIR` | The repository to serve (default: the current directory) |
61
+ | `--host ADDRESS` | Address to listen on (default `127.0.0.1`). Any other address needs a token |
62
+ | `--port N` | Port (default `8765`) |
63
+ | `--token-file FILE` | Read the token from the first line of FILE instead of `WINGBOX_HTTP_TOKEN` |
64
+ | `--tls-cert FILE`, `--tls-key FILE` | Serve HTTPS with this certificate and key |
65
+ | `--allow-origin ORIGIN` | Also accept browser requests from this origin; repeatable |
66
+ | `--build-missing` | Build the code graph in the background when the repository has none |
67
+
68
+ Without arguments the server listens on `127.0.0.1` only and asks for no
69
+ token: that is for an SSH tunnel (`ssh -L 8765:127.0.0.1:8765 host`) or a
70
+ reverse proxy that checks who calls.
71
+
72
+ ## Connect an agent
73
+
74
+ Claude Code:
75
+
76
+ ```bash
77
+ claude mcp add --transport http wingbox https://host.example:8765/mcp \
78
+ --header "Authorization: Bearer $WINGBOX_HTTP_TOKEN"
79
+ ```
80
+
81
+ Codex:
82
+
83
+ ```bash
84
+ codex mcp add wingbox --url https://host.example:8765/mcp --bearer-token-env-var WINGBOX_HTTP_TOKEN
85
+ ```
86
+
87
+ Any other MCP client: the Streamable HTTP transport, URL `https://host.example:8765/mcp`,
88
+ header `Authorization: Bearer <token>`.
89
+
90
+ ## What is exposed
91
+
92
+ Whoever holds the token can read the code graph of the repository (file names,
93
+ symbols, dependencies, the lines Wingbox quotes) and start a `build`, which
94
+ writes `.wingbox/` in the repository. No tool reads a file outside the
95
+ repository, runs a command you give it, or deletes anything.
96
+
97
+ - The token is a shared secret of at least 32 characters, compared in constant
98
+ time. It is taken from the environment or a file, never from the command
99
+ line, and is never logged.
100
+ - Listening on any address other than loopback is refused without a token.
101
+ - Without `--tls-cert` and `--tls-key` the token travels unencrypted: use them,
102
+ or put the port behind a TLS proxy or a private network.
103
+ - A request with an `Origin` header that is not a loopback origin or one given
104
+ with `--allow-origin` is answered 403, so a web page cannot call the server
105
+ through the browser of someone on the same network.
106
+
107
+ ## Protocol
108
+
109
+ One endpoint, `POST /mcp`, for protocol revisions 2026-07-28 and 2025-11-25
110
+ down to 2024-11-05. Each request is answered with JSON; a `tools/call` that
111
+ runs longer than a second is answered as an event stream, with a keep-alive
112
+ line every ten seconds, when the client accepts one, so a long `build` is not
113
+ cut by an idle timeout on the way. The server keeps no session and opens no
114
+ stream of its own: `GET` and `DELETE` are answered 405. Calls run one after
115
+ another, as on stdio.
116
+
117
+ License: MIT.
@@ -0,0 +1,93 @@
1
+ # wingbox-http
2
+
3
+ Call the [Wingbox](https://wingbox.dev) code graph of a repository from another
4
+ machine. `wingbox-http` serves the Wingbox MCP server over the Streamable HTTP
5
+ transport of the Model Context Protocol: the same tools as `wingbox mcp` on
6
+ stdio (`impact`, `usages`, `build` and the rest), at one URL.
7
+
8
+ Use it when the repository and its graph live on a build server, a dev
9
+ container or a remote workstation, and the coding agent runs somewhere else.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install "wingbox[http]" # or: pipx install wingbox && pipx inject wingbox wingbox-http
15
+ ```
16
+
17
+ The transport is a package of its own on purpose: `wingbox` itself holds no
18
+ listening code. `wingbox-http` uses the Python standard library only, listens
19
+ and answers, and opens no connection of its own.
20
+
21
+ ## Run
22
+
23
+ On the machine that holds the repository:
24
+
25
+ ```bash
26
+ export WINGBOX_HTTP_TOKEN="$(openssl rand -hex 32)" # keep it; clients send it
27
+ wingbox mcp --http --root /path/to/project --host 0.0.0.0 --port 8765 \
28
+ --tls-cert fullchain.pem --tls-key privkey.pem
29
+ ```
30
+
31
+ `wingbox-http ...` is the same command. The server answers at
32
+ `https://<host>:8765/mcp`.
33
+
34
+ | Option | Meaning |
35
+ |---|---|
36
+ | `--root DIR` | The repository to serve (default: the current directory) |
37
+ | `--host ADDRESS` | Address to listen on (default `127.0.0.1`). Any other address needs a token |
38
+ | `--port N` | Port (default `8765`) |
39
+ | `--token-file FILE` | Read the token from the first line of FILE instead of `WINGBOX_HTTP_TOKEN` |
40
+ | `--tls-cert FILE`, `--tls-key FILE` | Serve HTTPS with this certificate and key |
41
+ | `--allow-origin ORIGIN` | Also accept browser requests from this origin; repeatable |
42
+ | `--build-missing` | Build the code graph in the background when the repository has none |
43
+
44
+ Without arguments the server listens on `127.0.0.1` only and asks for no
45
+ token: that is for an SSH tunnel (`ssh -L 8765:127.0.0.1:8765 host`) or a
46
+ reverse proxy that checks who calls.
47
+
48
+ ## Connect an agent
49
+
50
+ Claude Code:
51
+
52
+ ```bash
53
+ claude mcp add --transport http wingbox https://host.example:8765/mcp \
54
+ --header "Authorization: Bearer $WINGBOX_HTTP_TOKEN"
55
+ ```
56
+
57
+ Codex:
58
+
59
+ ```bash
60
+ codex mcp add wingbox --url https://host.example:8765/mcp --bearer-token-env-var WINGBOX_HTTP_TOKEN
61
+ ```
62
+
63
+ Any other MCP client: the Streamable HTTP transport, URL `https://host.example:8765/mcp`,
64
+ header `Authorization: Bearer <token>`.
65
+
66
+ ## What is exposed
67
+
68
+ Whoever holds the token can read the code graph of the repository (file names,
69
+ symbols, dependencies, the lines Wingbox quotes) and start a `build`, which
70
+ writes `.wingbox/` in the repository. No tool reads a file outside the
71
+ repository, runs a command you give it, or deletes anything.
72
+
73
+ - The token is a shared secret of at least 32 characters, compared in constant
74
+ time. It is taken from the environment or a file, never from the command
75
+ line, and is never logged.
76
+ - Listening on any address other than loopback is refused without a token.
77
+ - Without `--tls-cert` and `--tls-key` the token travels unencrypted: use them,
78
+ or put the port behind a TLS proxy or a private network.
79
+ - A request with an `Origin` header that is not a loopback origin or one given
80
+ with `--allow-origin` is answered 403, so a web page cannot call the server
81
+ through the browser of someone on the same network.
82
+
83
+ ## Protocol
84
+
85
+ One endpoint, `POST /mcp`, for protocol revisions 2026-07-28 and 2025-11-25
86
+ down to 2024-11-05. Each request is answered with JSON; a `tools/call` that
87
+ runs longer than a second is answered as an event stream, with a keep-alive
88
+ line every ten seconds, when the client accepts one, so a long `build` is not
89
+ cut by an idle timeout on the way. The server keeps no session and opens no
90
+ stream of its own: `GET` and `DELETE` are answered 405. Calls run one after
91
+ another, as on stdio.
92
+
93
+ License: MIT.
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "wingbox-http"
7
+ version = "0.13.0"
8
+ description = "Streamable HTTP transport for the Wingbox MCP server: call the code graph of a repository from another machine."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Aileron Technologies" }]
14
+ keywords = ["mcp", "mcp-server", "streamable-http", "code-graph", "impact-analysis", "wingbox"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Environment :: Console",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Software Development",
24
+ ]
25
+ # The version follows wingbox, and each release requires exactly its own wingbox (REQ-HTTP-021).
26
+ dependencies = ["wingbox==0.13.0"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://wingbox.dev"
30
+ Repository = "https://github.com/aileron-tech/wingbox"
31
+ Documentation = "https://github.com/aileron-tech/wingbox#over-http-from-another-machine"
32
+ Issues = "https://github.com/aileron-tech/wingbox/issues"
33
+
34
+ [project.scripts]
35
+ wingbox-http = "wingbox_http:run"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/wingbox_http"]
39
+
40
+ [tool.hatch.build.targets.sdist]
41
+ include = ["/src", "/README.md", "/LICENSE", "/pyproject.toml"]
@@ -0,0 +1,68 @@
1
+ """Streamable HTTP transport for the Wingbox MCP server: `wingbox-http`, or `wingbox mcp --http`.
2
+
3
+ The same server as `wingbox mcp` on stdio, reachable at http://ADDRESS:PORT/mcp.
4
+ It listens and answers; it opens no connection of its own.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import signal
10
+ import sys
11
+ from collections.abc import Mapping
12
+ from typing import Optional
13
+
14
+ from wingbox import cli, mcp_server
15
+
16
+ from wingbox_http import listener, settings, transport
17
+
18
+
19
+ def main(args: list[str], cwd: str, env: Optional[Mapping[str, str]] = None) -> int:
20
+ if any(argument in ("-h", "--help") for argument in args):
21
+ print(settings.USAGE)
22
+ return 0
23
+ chosen = settings.read(args, cwd, os.environ if env is None else env)
24
+ if isinstance(chosen, settings.Problem):
25
+ print(f"[wingbox] ERROR: {chosen.message}\n{settings.USAGE}", file=sys.stderr)
26
+ return 2
27
+ log = sys.stderr # kept: a running tool redirects sys.stderr into its answer
28
+ server = mcp_server.Server(chosen.root)
29
+ policy = transport.Policy(
30
+ access=chosen.access,
31
+ origins=chosen.origins,
32
+ versions=mcp_server.SUPPORTED_VERSIONS,
33
+ modern_versions=mcp_server.MODERN_VERSIONS,
34
+ meta_version=mcp_server.META_VERSION,
35
+ )
36
+ try:
37
+ httpd = listener.make_listener(
38
+ chosen.host, chosen.port, policy, lambda line: mcp_server.handle_line(server, line), tls=chosen.tls, log=log
39
+ )
40
+ except OSError as error: # the port is taken, the address is not ours, the certificate cannot be read
41
+ print(f"[wingbox] ERROR: cannot listen on {chosen.host}:{chosen.port}: {error}", file=sys.stderr)
42
+ return 2
43
+ scheme = "https" if chosen.tls is not None else "http"
44
+ host = f"[{chosen.host}]" if ":" in chosen.host else chosen.host
45
+ print(f"[wingbox] MCP server {cli._version()} on {scheme}://{host}:{httpd.server_address[1]}{transport.ENDPOINT} for {chosen.root}", file=log)
46
+ if isinstance(chosen.access, transport.Open):
47
+ print("[wingbox] no token is set: any program on this machine can call the tools", file=log)
48
+ elif chosen.tls is None and not settings.is_loopback(chosen.host):
49
+ print("[wingbox] WARNING: no TLS: the token travels unencrypted; pass --tls-cert and --tls-key or put a TLS proxy in front", file=log)
50
+ try:
51
+ if chosen.build_missing:
52
+ server.start_first_build()
53
+ httpd.serve_forever()
54
+ except KeyboardInterrupt:
55
+ pass
56
+ finally:
57
+ server.stop_first_build()
58
+ httpd.server_close()
59
+ return 0
60
+
61
+
62
+ def _stop(_signal: int, _frame: object) -> None:
63
+ raise KeyboardInterrupt
64
+
65
+
66
+ def run() -> None:
67
+ signal.signal(signal.SIGTERM, _stop) # a container or a service manager stops the server this way
68
+ sys.exit(main(sys.argv[1:], os.getcwd()))
@@ -0,0 +1,3 @@
1
+ from wingbox_http import run
2
+
3
+ run()
@@ -0,0 +1,174 @@
1
+ """The listening side of the transport: sockets, TLS, threads. The decisions are in transport.py.
2
+
3
+ One worker thread runs the calls of the MCP server one after another, as on
4
+ stdio: the server keeps one loaded graph and its commands are not written for
5
+ concurrent use. A tools/call that is not answered within `first_wait` seconds
6
+ is answered as an event stream, when the client accepts one, with a comment
7
+ line every `keep_alive` seconds, so that a long build is not cut by an idle
8
+ timeout on the way.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import socket
14
+ import ssl
15
+ import sys
16
+ from collections.abc import Callable, Mapping
17
+ from concurrent.futures import Future, ThreadPoolExecutor
18
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
+ from typing import IO, Any, Optional
20
+
21
+ from wingbox_http import transport
22
+ from wingbox_http.settings import Tls
23
+
24
+ Handle = Callable[[str], Optional[Mapping[str, Any]]]
25
+ FIRST_WAIT_SECONDS = 1.0
26
+ KEEP_ALIVE_SECONDS = 10.0
27
+ READ_TIMEOUT_SECONDS = 30
28
+
29
+
30
+ class Listener(ThreadingHTTPServer):
31
+ daemon_threads = True
32
+
33
+ def __init__(self, address: tuple[str, int], policy: transport.Policy, handle: Handle, first_wait: float, keep_alive: float, log: IO[str]) -> None:
34
+ if ":" in address[0]:
35
+ self.address_family = socket.AF_INET6
36
+ self.policy = policy
37
+ self.handle = handle
38
+ self.first_wait = first_wait
39
+ self.keep_alive = keep_alive
40
+ self.log = log
41
+ self.calls = ThreadPoolExecutor(max_workers=1, thread_name_prefix="wingbox-mcp")
42
+ super().__init__(address, _Handler)
43
+
44
+ def server_close(self) -> None:
45
+ self.calls.shutdown(wait=False, cancel_futures=True)
46
+ super().server_close()
47
+
48
+ def handle_error(self, request: Any, client_address: Any) -> None:
49
+ # a failed TLS handshake, a reset connection: one line, not a traceback
50
+ print(f"[wingbox] http {client_address[0]}: {sys.exc_info()[1]!r}", file=self.log)
51
+
52
+
53
+ class _Handler(BaseHTTPRequestHandler):
54
+ protocol_version = "HTTP/1.1"
55
+ server_version = "wingbox-http"
56
+ sys_version = ""
57
+ timeout = READ_TIMEOUT_SECONDS
58
+ server: Listener
59
+
60
+ def log_message(self, format: str, *args: Any) -> None:
61
+ # the request line and the status only: never a header, so never the token
62
+ print(f"[wingbox] http {self.address_string()} {format % args}", file=self.server.log)
63
+
64
+ def _answer(self) -> None:
65
+ headers = {name.lower(): value for name, value in self.headers.items()}
66
+ head = transport.Request(self.command, self.path, headers, b"")
67
+ admitted = transport.admit(self.server.policy, head)
68
+ if isinstance(admitted, transport.Refuse):
69
+ self._refuse(admitted)
70
+ return
71
+ length = headers.get("content-length", "")
72
+ if not length.isdigit():
73
+ self._refuse(transport.Refuse(411, (), transport.error_body(transport.INVALID_REQUEST, "Length required: send Content-Length")))
74
+ return
75
+ if int(length) > transport.MAX_BODY_BYTES:
76
+ self._refuse(transport.Refuse(413, (), transport.error_body(transport.INVALID_REQUEST, f"Request body over {transport.MAX_BODY_BYTES} bytes")))
77
+ return
78
+ body = self.rfile.read(int(length))
79
+ decision = transport.decide(self.server.policy, transport.Request(self.command, self.path, headers, body))
80
+ if isinstance(decision, transport.Refuse):
81
+ self._refuse(decision)
82
+ return
83
+ future = self.server.calls.submit(self.server.handle, decision.line)
84
+ stream = decision.method == "tools/call" and transport.accepts_stream(headers.get("accept", ""))
85
+ try:
86
+ reply = future.result(timeout=self.server.first_wait if stream else None)
87
+ except TimeoutError:
88
+ self._stream(future)
89
+ return
90
+ except Exception as error: # the MCP server answers every message; this is a defect in it
91
+ self._failed(error)
92
+ return
93
+ status = transport.reply_status(reply, decision.modern)
94
+ self._send(status, (), b"" if reply is None else _encode(reply), close=status >= 400)
95
+
96
+ do_GET = do_POST = do_DELETE = do_PUT = do_PATCH = do_OPTIONS = do_HEAD = _answer
97
+
98
+ def _failed(self, error: BaseException) -> None:
99
+ print(f"[wingbox] http call failed: {error!r}", file=self.server.log)
100
+ self._send(500, (), transport.error_body(transport.INTERNAL_ERROR, f"Internal error: {error}"), close=True)
101
+
102
+ def _refuse(self, refusal: transport.Refuse) -> None:
103
+ # the body of a refused request is not read, so the connection cannot be used again
104
+ self._send(refusal.status, refusal.headers, refusal.body, close=True)
105
+
106
+ def _send(self, status: int, headers: tuple[tuple[str, str], ...], body: bytes, close: bool) -> None:
107
+ self.send_response(status)
108
+ for name, value in headers:
109
+ self.send_header(name, value)
110
+ if body:
111
+ self.send_header("Content-Type", "application/json")
112
+ self.send_header("Content-Length", str(len(body)))
113
+ if close:
114
+ self.send_header("Connection", "close")
115
+ self.close_connection = True
116
+ self.end_headers()
117
+ if body and self.command != "HEAD":
118
+ self.wfile.write(body)
119
+
120
+ def _stream(self, future: Future) -> None:
121
+ self.close_connection = True
122
+ try:
123
+ self.send_response(200)
124
+ self.send_header("Content-Type", "text/event-stream")
125
+ self.send_header("Cache-Control", "no-store")
126
+ self.send_header("X-Accel-Buffering", "no")
127
+ self.send_header("Connection", "close")
128
+ self.end_headers()
129
+ while True:
130
+ try:
131
+ reply = future.result(timeout=self.server.keep_alive)
132
+ payload = _encode(reply) if reply is not None else b""
133
+ break
134
+ except TimeoutError:
135
+ self.wfile.write(b": keep-alive\n\n")
136
+ self.wfile.flush()
137
+ except Exception as error:
138
+ print(f"[wingbox] http call failed: {error!r}", file=self.server.log)
139
+ payload = transport.error_body(transport.INTERNAL_ERROR, f"Internal error: {error}")
140
+ break
141
+ self.wfile.write(b"event: message\ndata: " + payload + b"\n\n")
142
+ self.wfile.flush()
143
+ except OSError as error:
144
+ # the client left; the call itself cannot be interrupted and its answer is dropped
145
+ print(f"[wingbox] http {self.address_string()} left before the answer: {error!r}", file=self.server.log)
146
+
147
+
148
+ def _encode(reply: Mapping[str, Any]) -> bytes:
149
+ return json.dumps(reply, separators=(",", ":")).encode("ascii")
150
+
151
+
152
+ def make_listener(
153
+ host: str,
154
+ port: int,
155
+ policy: transport.Policy,
156
+ handle: Handle,
157
+ first_wait: float = FIRST_WAIT_SECONDS,
158
+ keep_alive: float = KEEP_ALIVE_SECONDS,
159
+ tls: Optional[Tls] = None,
160
+ log: Optional[IO[str]] = None,
161
+ ) -> Listener:
162
+ """A bound listener; the caller runs serve_forever() and server_close()."""
163
+ httpd = Listener((host, port), policy, handle, first_wait, keep_alive, sys.stderr if log is None else log)
164
+ if tls is not None:
165
+ try:
166
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
167
+ context.minimum_version = ssl.TLSVersion.TLSv1_2
168
+ context.load_cert_chain(tls.certificate, tls.key)
169
+ # the handshake runs in the thread of the connection, so a slow client cannot hold the accept loop
170
+ httpd.socket = context.wrap_socket(httpd.socket, server_side=True, do_handshake_on_connect=False)
171
+ except (OSError, ssl.SSLError):
172
+ httpd.server_close()
173
+ raise
174
+ return httpd
@@ -0,0 +1,140 @@
1
+ """The settings of `wingbox-http` from its arguments, the environment and the token file."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import ipaddress
6
+ import os
7
+ import re
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from typing import Optional, Union
11
+
12
+ from wingbox_http.transport import Access, Open, Token
13
+
14
+ DEFAULT_HOST = "127.0.0.1"
15
+ DEFAULT_PORT = 8765
16
+ TOKEN_VARIABLE = "WINGBOX_HTTP_TOKEN"
17
+ TOKEN_MIN_LENGTH = 32
18
+ _TOKEN = re.compile(r"^[\x21-\x7e]+$")
19
+ _ORIGIN = re.compile(r"^https?://[^/\s]+$")
20
+
21
+ USAGE = f"""usage: wingbox-http [--root DIR] [--build-missing] [--host ADDRESS] [--port N]
22
+ [--token-file FILE] [--tls-cert FILE --tls-key FILE]
23
+ [--allow-origin ORIGIN]...
24
+
25
+ Serve the Wingbox MCP server for the repository at DIR (default: the current
26
+ directory) over the Streamable HTTP transport, at http://ADDRESS:N/mcp
27
+ (default {DEFAULT_HOST}:{DEFAULT_PORT}). `wingbox mcp --http` is the same command.
28
+
29
+ --host ADDRESS the address to listen on. Any address other than loopback
30
+ needs a token.
31
+ --token-file FILE read the token from the first line of FILE; without it
32
+ the token is taken from the environment variable
33
+ {TOKEN_VARIABLE}. At least {TOKEN_MIN_LENGTH} characters. Clients send it
34
+ as `Authorization: Bearer <token>`.
35
+ --tls-cert, --tls-key serve HTTPS with this certificate and private key.
36
+ --allow-origin ORIGIN also accept browser requests from this origin
37
+ (scheme://host[:port]); loopback origins always pass.
38
+ --build-missing build the code graph of DIR in the background when it
39
+ has none."""
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Tls:
44
+ certificate: str
45
+ key: str
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Settings:
50
+ root: str
51
+ host: str
52
+ port: int
53
+ access: Access
54
+ origins: frozenset[str]
55
+ tls: Optional[Tls]
56
+ build_missing: bool
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Problem:
61
+ message: str
62
+
63
+
64
+ class _Rejected(Exception):
65
+ pass
66
+
67
+
68
+ class _Parser(argparse.ArgumentParser):
69
+ def error(self, message: str): # argparse would print and exit
70
+ raise _Rejected(message)
71
+
72
+
73
+ def is_loopback(host: str) -> bool:
74
+ if host.lower() == "localhost":
75
+ return True
76
+ try:
77
+ return ipaddress.ip_address(host).is_loopback
78
+ except ValueError:
79
+ return False
80
+
81
+
82
+ def _token(path: Optional[str], env: Mapping[str, str]) -> Union[Access, Problem]:
83
+ if path is not None:
84
+ try:
85
+ with open(path, encoding="utf-8") as handle:
86
+ value = handle.readline().strip()
87
+ except (OSError, UnicodeDecodeError) as error:
88
+ return Problem(f"--token-file cannot be read: {error}")
89
+ source = f"the first line of {path}"
90
+ else:
91
+ value = env.get(TOKEN_VARIABLE, "")
92
+ if not value:
93
+ return Open()
94
+ source = TOKEN_VARIABLE
95
+ if len(value) < TOKEN_MIN_LENGTH or _TOKEN.match(value) is None:
96
+ return Problem(f"{source} is not a usable token: at least {TOKEN_MIN_LENGTH} visible ASCII characters without spaces")
97
+ return Token(value)
98
+
99
+
100
+ def read(args: list[str], cwd: str, env: Mapping[str, str]) -> Union[Settings, Problem]:
101
+ parser = _Parser(prog="wingbox-http", add_help=False, allow_abbrev=False)
102
+ parser.add_argument("--root", default=".")
103
+ parser.add_argument("--host", default=DEFAULT_HOST)
104
+ parser.add_argument("--port", type=int, default=DEFAULT_PORT)
105
+ parser.add_argument("--token-file")
106
+ parser.add_argument("--tls-cert")
107
+ parser.add_argument("--tls-key")
108
+ parser.add_argument("--allow-origin", action="append", default=[])
109
+ parser.add_argument("--build-missing", action="store_true")
110
+ try:
111
+ parsed = parser.parse_args(args)
112
+ except _Rejected as error:
113
+ return Problem(str(error))
114
+ root = os.path.normpath(os.path.join(cwd, parsed.root))
115
+ if not os.path.isdir(root):
116
+ return Problem(f"--root is not a directory: {root}")
117
+ if not 0 <= parsed.port <= 65535:
118
+ return Problem(f"--port is not a port number: {parsed.port}")
119
+ if (parsed.tls_cert is None) != (parsed.tls_key is None):
120
+ return Problem("--tls-cert and --tls-key come together")
121
+ for origin in parsed.allow_origin:
122
+ if _ORIGIN.match(origin) is None:
123
+ return Problem(f"--allow-origin takes scheme://host[:port], not {origin}")
124
+ access = _token(parsed.token_file, env)
125
+ if isinstance(access, Problem):
126
+ return access
127
+ if isinstance(access, Open) and not is_loopback(parsed.host):
128
+ return Problem(
129
+ f"listening on {parsed.host} needs a token: set {TOKEN_VARIABLE} or pass --token-file "
130
+ f"(without one the server listens on {DEFAULT_HOST} only)"
131
+ )
132
+ return Settings(
133
+ root=os.path.realpath(root),
134
+ host=parsed.host,
135
+ port=parsed.port,
136
+ access=access,
137
+ origins=frozenset(parsed.allow_origin),
138
+ tls=None if parsed.tls_cert is None else Tls(parsed.tls_cert, parsed.tls_key),
139
+ build_missing=parsed.build_missing,
140
+ )
@@ -0,0 +1,208 @@
1
+ """The Streamable HTTP transport of MCP as pure functions: one HTTP request in, one decision out.
2
+
3
+ `decide` says whether a request is refused, and with which status, or forwarded
4
+ to the MCP server as one JSON-RPC message; `reply_status` gives the HTTP status
5
+ of the server's reply. Nothing here reads a socket, a file or the environment;
6
+ the listener (listener.py) does the I/O.
7
+
8
+ Followed: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports
9
+ and https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http
10
+ (one endpoint, POST only, no session, no stream opened by the server).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import hmac
15
+ import json
16
+ import re
17
+ from collections.abc import Mapping
18
+ from dataclasses import dataclass
19
+ from typing import Any, Optional, Union
20
+
21
+ ENDPOINT = "/mcp"
22
+ MAX_BODY_BYTES = 4 * 1024 * 1024
23
+
24
+ PARSE_ERROR = -32700
25
+ INVALID_REQUEST = -32600
26
+ METHOD_NOT_FOUND = -32601
27
+ INTERNAL_ERROR = -32603
28
+ HEADER_MISMATCH = -32020
29
+ UNSUPPORTED_PROTOCOL_VERSION = -32022
30
+
31
+ # The methods of revision 2026-07-28 whose target is repeated in the Mcp-Name header.
32
+ NAMED_METHODS = frozenset({"tools/call", "resources/read", "prompts/get"})
33
+ _LOOPBACK_ORIGIN = re.compile(r"^https?://(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$", re.IGNORECASE)
34
+ _STATUS_400 = frozenset({PARSE_ERROR, INVALID_REQUEST, HEADER_MISMATCH, UNSUPPORTED_PROTOCOL_VERSION})
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Open:
39
+ """No credential is asked: the listener is bound to this machine only."""
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Token:
44
+ """Every request must carry `Authorization: Bearer <value>`."""
45
+
46
+ value: str
47
+
48
+
49
+ Access = Union[Open, Token]
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Policy:
54
+ access: Access
55
+ origins: frozenset[str] # origins allowed besides the loopback ones
56
+ versions: tuple[str, ...] # every protocol revision the server speaks
57
+ modern_versions: tuple[str, ...] # the revisions with per-request _meta
58
+ meta_version: str # the _meta key of the protocol version
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class Request:
63
+ method: str
64
+ path: str
65
+ headers: Mapping[str, str] # names in lower case
66
+ body: bytes
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class Refuse:
71
+ status: int
72
+ headers: tuple[tuple[str, str], ...]
73
+ body: bytes
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Admit:
78
+ """The request line and the headers are acceptable; the body is not looked at yet."""
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Forward:
83
+ line: str # the JSON-RPC message for the MCP server
84
+ method: str # its method, "" for a message without one
85
+ modern: bool # a request of a revision with per-request _meta
86
+
87
+
88
+ def error_body(code: int, message: str, data: Any = None) -> bytes:
89
+ error: dict[str, Any] = {"code": code, "message": message}
90
+ if data is not None:
91
+ error["data"] = data
92
+ return json.dumps({"jsonrpc": "2.0", "id": None, "error": error}, separators=(",", ":")).encode("ascii")
93
+
94
+
95
+ def _refuse(status: int, message: str, code: int = INVALID_REQUEST, headers: tuple[tuple[str, str], ...] = (), data: Any = None) -> Refuse:
96
+ return Refuse(status, headers, error_body(code, message, data))
97
+
98
+
99
+ def _origin_allowed(policy: Policy, origin: str) -> bool:
100
+ return origin in policy.origins or _LOOPBACK_ORIGIN.match(origin) is not None
101
+
102
+
103
+ def _authorized(access: Access, header: str) -> bool:
104
+ if isinstance(access, Open):
105
+ return True
106
+ scheme, _, credential = header.partition(" ")
107
+ if scheme.lower() != "bearer":
108
+ return False
109
+ return hmac.compare_digest(credential.strip().encode("utf-8"), access.value.encode("utf-8"))
110
+
111
+
112
+ def admit(policy: Policy, request: Request) -> Union[Refuse, Admit]:
113
+ """What the request line and the headers alone decide; the listener asks this before it reads a body."""
114
+ if request.path.split("?", 1)[0] != ENDPOINT:
115
+ return _refuse(404, f"Not found: the MCP endpoint is {ENDPOINT}")
116
+ origin = request.headers.get("origin")
117
+ if origin is not None and not _origin_allowed(policy, origin):
118
+ return _refuse(403, "Origin not allowed")
119
+ if not _authorized(policy.access, request.headers.get("authorization", "")):
120
+ return _refuse(401, "Unauthorized: send Authorization: Bearer <token>", headers=(("WWW-Authenticate", 'Bearer realm="wingbox"'),))
121
+ if request.method != "POST":
122
+ return _refuse(405, "Method not allowed: the MCP endpoint takes POST only", headers=(("Allow", "POST"),))
123
+ content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
124
+ if content_type != "application/json":
125
+ return _refuse(415, "Unsupported media type: send Content-Type: application/json")
126
+ accept = request.headers.get("accept")
127
+ if accept is not None and not accepts_json(accept) and not accepts_stream(accept):
128
+ return _refuse(406, "Not acceptable: accept application/json and text/event-stream")
129
+ return Admit()
130
+
131
+
132
+ def _media_types(accept: str) -> frozenset[str]:
133
+ return frozenset(part.split(";", 1)[0].strip().lower() for part in accept.split(","))
134
+
135
+
136
+ def accepts_json(accept: str) -> bool:
137
+ return bool(_media_types(accept) & {"application/json", "application/*", "*/*"})
138
+
139
+
140
+ def accepts_stream(accept: str) -> bool:
141
+ return "text/event-stream" in _media_types(accept)
142
+
143
+
144
+ def _declared_version(message: Mapping[str, Any], key: str) -> Optional[str]:
145
+ params = message.get("params")
146
+ meta = params.get("_meta") if isinstance(params, dict) else None
147
+ value = meta.get(key) if isinstance(meta, dict) else None
148
+ return value if isinstance(value, str) else None
149
+
150
+
151
+ def _mismatch(message: str) -> Refuse:
152
+ return _refuse(400, f"Header mismatch: {message}", code=HEADER_MISMATCH)
153
+
154
+
155
+ def decide(policy: Policy, request: Request) -> Union[Refuse, Forward]:
156
+ """Refuse the request with a status, or forward its body to the MCP server."""
157
+ admitted = admit(policy, request)
158
+ if isinstance(admitted, Refuse):
159
+ return admitted
160
+ if len(request.body) > MAX_BODY_BYTES:
161
+ return _refuse(413, f"Request body over {MAX_BODY_BYTES} bytes")
162
+ try:
163
+ text = request.body.decode("utf-8")
164
+ message = json.loads(text)
165
+ except ValueError as error: # UnicodeDecodeError and json.JSONDecodeError are both ValueError
166
+ return _refuse(400, f"Parse error: {error}", code=PARSE_ERROR)
167
+ if not isinstance(message, dict):
168
+ return _refuse(400, "Invalid Request: expected one JSON-RPC object, batches are not supported")
169
+ header = request.headers.get("mcp-protocol-version")
170
+ if header is not None and header not in policy.versions:
171
+ return _refuse(
172
+ 400,
173
+ "Unsupported protocol version",
174
+ code=UNSUPPORTED_PROTOCOL_VERSION,
175
+ data={"supported": list(policy.versions), "requested": header},
176
+ )
177
+ method = message.get("method")
178
+ method = method if isinstance(method, str) else ""
179
+ declared = _declared_version(message, policy.meta_version)
180
+ if declared is None:
181
+ if header in policy.modern_versions:
182
+ return _mismatch(f"MCP-Protocol-Version is {header} but the body carries no {policy.meta_version}")
183
+ return Forward(text, method, modern=False)
184
+ if header != declared:
185
+ return _mismatch(f"MCP-Protocol-Version must equal {policy.meta_version} of the body ({declared})")
186
+ if declared not in policy.modern_versions:
187
+ return Forward(text, method, modern=False)
188
+ if request.headers.get("mcp-method") != method:
189
+ return _mismatch(f"Mcp-Method must equal the method of the body ({method})")
190
+ if method in NAMED_METHODS:
191
+ params = message.get("params")
192
+ name = params.get("name", params.get("uri")) if isinstance(params, dict) else None
193
+ if not isinstance(name, str) or request.headers.get("mcp-name") != name:
194
+ return _mismatch("Mcp-Name must equal the name the body asks for")
195
+ return Forward(text, method, modern=True)
196
+
197
+
198
+ def reply_status(reply: Optional[Mapping[str, Any]], modern: bool) -> int:
199
+ """The HTTP status of the MCP server's reply; None is its answer to a notification."""
200
+ if reply is None:
201
+ return 202
202
+ error = reply.get("error")
203
+ code = error.get("code") if isinstance(error, dict) else None
204
+ if code in _STATUS_400:
205
+ return 400
206
+ if code == METHOD_NOT_FOUND and modern:
207
+ return 404
208
+ return 200