forked from balisujohn/localwriter
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathserver.py
More file actions
257 lines (213 loc) · 10.3 KB
/
Copy pathserver.py
File metadata and controls
257 lines (213 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2024 John Balis
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Generic threaded HTTP server with route dispatch.
Extracted from the MCP module so any module can register HTTP endpoints.
The server handles CORS, JSON encode/decode, and main-thread dispatch.
Route handlers are looked up from an HttpRouteRegistry instance.
"""
from plugin.framework.thread_guard import background
import json
import logging
import socketserver
from http.server import HTTPServer, BaseHTTPRequestHandler
from typing import Any, cast
from plugin.framework.url_utils import get_url_path, get_url_query_dict
from plugin.framework.errors import safe_json_loads
from plugin.framework.worker_pool import run_in_background
from plugin.mcp.cors import send_cors_headers
from plugin.mcp.http_trace import log_cors_preflight, log_http_request, log_no_route
log = logging.getLogger("writeragent.framework.http_server")
def mcp_endpoint_url(host: str, port: int, use_ssl: bool = False) -> str:
"""Full streamable-HTTP MCP URL for external clients (LM Studio, Cursor, etc.)."""
scheme = "https" if use_ssl else "http"
return f"{scheme}://{host}:{port}/mcp"
class _ThreadedHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
"""HTTP server that handles each request in its own thread."""
daemon_threads = True
class GenericRequestHandler(BaseHTTPRequestHandler):
"""HTTP request handler that dispatches to registered routes."""
route_registry = None # HttpRouteRegistry, set by HttpServer.start()
def do_GET(self):
self._dispatch("GET")
def do_POST(self):
self._dispatch("POST")
def do_DELETE(self):
self._dispatch("DELETE")
def do_OPTIONS(self):
path = get_url_path(self.path)
log_cors_preflight(self, path)
self.send_response(204)
send_cors_headers(self, preflight=True)
self.end_headers()
def _dispatch(self, method):
path = get_url_path(self.path)
log_http_request(self, method, path)
route = self.route_registry.match(method, path) if self.route_registry else None
if route is None:
log_no_route(self, method, path)
from plugin.framework.errors import WriterAgentException, format_error_payload
err = WriterAgentException("Not found", code="NOT_FOUND", details={"path": path})
self._send_json(404, format_error_payload(err))
return
try:
if route.raw:
if route.main_thread:
from plugin.framework.queue_executor import default_executor
default_executor.execute(route.handler, self)
else:
route.handler(self)
else:
body = self._read_body()
if body is None:
return # _read_body already sent error response
query = get_url_query_dict(self.path)
if route.main_thread:
from plugin.framework.queue_executor import default_executor
result: Any = default_executor.execute(route.handler, body, self.headers, query)
status, data = cast("tuple[int, Any]", result)
else:
result = route.handler(body, self.headers, query)
status, data = cast("tuple[int, Any]", result)
self._send_json(status, data)
except Exception as e:
log.error("%s %s error: %s", method, path, e, exc_info=True)
from plugin.framework.errors import format_error_payload
self._send_json(500, format_error_payload(e))
def _read_body(self):
content_length = int(self.headers.get("Content-Length", 0))
if content_length == 0:
return {}
raw = self.rfile.read(content_length).decode("utf-8")
data = safe_json_loads(raw, default=None, strict=True)
if data is None and raw.strip():
from plugin.framework.errors import AgentParsingError, format_error_payload
log.warning("Invalid JSON body: %s", raw[:200])
err = AgentParsingError("Invalid JSON body in HTTP request", details={"raw": raw[:200]})
self._send_json(400, format_error_payload(err))
return None
return data if data is not None else {}
def _send_json(self, status, data):
self.send_response(status)
send_cors_headers(self, preflight=False)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(data, ensure_ascii=False, default=str).encode("utf-8"))
def log_message(self, format: str, *args: object) -> None:
log.info("%s - %s", self.client_address[0], format % args)
class HttpServer:
"""Generic threaded HTTP server with optional TLS."""
# Port-bind resilience. The configured port (default 8765) can be briefly held by a previous
# instance that is still shutting down, or collide with another local server that defaults to
# the same port (e.g. a code editor's preview/"viewer" server). A single bind attempt then
# raises and the MCP server never comes up — the user just sees "I have to restart to connect".
# Retry a few times so a transient holder clears on its own; on persistent failure raise with a
# CLEAR, actionable message instead of a bare OSError.
_BIND_ATTEMPTS = 5
_BIND_RETRY_DELAY = 1.0
def __init__(self, route_registry, port=8766, host="localhost", use_ssl=False, ssl_cert="", ssl_key=""):
self.route_registry = route_registry
self.port = port
self.host = host
self.use_ssl = use_ssl
self.ssl_cert = ssl_cert
self.ssl_key = ssl_key
self._server = None
self._thread = None
self._running = False
def start(self):
if self._running:
log.warning("HTTP server is already running")
return
GenericRequestHandler.route_registry = self.route_registry
self._server = self._bind_with_retry()
if self.use_ssl:
# TLS server mode requires explicit certificates.
# Local generation of certificates has been removed from ssl_helpers.
if self.ssl_cert and self.ssl_key:
cert_path, key_path = self.ssl_cert, self.ssl_key
log.info("TLS using custom certs: %s", cert_path)
import ssl
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(certfile=cert_path, keyfile=key_path)
if self._server:
self._server.socket = ssl_ctx.wrap_socket(self._server.socket, server_side=True)
else:
log.warning("use_ssl is True but no certificates provided. Disabling TLS.")
self.use_ssl = False
self._running = True
self._thread = run_in_background(self._run, daemon=True, name="http-server")
scheme = "https" if self.use_ssl else "http"
url = "%s://%s:%s" % (scheme, self.host, self.port)
log.info("HTTP server ready — %s (%d routes)", url, self.route_registry.route_count)
def _bind_with_retry(self):
"""Bind the listening socket, retrying briefly if the port is transiently in use.
Returns the bound server. Raises the last OSError (with a clear log) if the port stays
busy across all attempts — preserving start()'s "raise on failure" contract so the caller
still reports the failure, but now after retries and with an actionable message."""
import time
last_err = None
for attempt in range(1, self._BIND_ATTEMPTS + 1):
try:
return _ThreadedHTTPServer((self.host, self.port), GenericRequestHandler)
except OSError as e:
last_err = e
log.warning(
"HTTP bind %s:%s failed (%s) — attempt %d/%d",
self.host, self.port, getattr(e, "errno", e), attempt, self._BIND_ATTEMPTS,
)
if attempt < self._BIND_ATTEMPTS:
time.sleep(self._BIND_RETRY_DELAY)
log.error(
"Could not bind %s:%s after %d attempts — the port is in use by another process. "
"Close whatever is holding it, or set the MCP 'port' (or 'mcp_port') config to a free "
"port, then restart. A local preview/viewer server may default to the same port.",
self.host, self.port, self._BIND_ATTEMPTS,
)
raise last_err if last_err is not None else OSError("bind failed")
def stop(self):
if not self._running:
return
self._running = False
if self._server:
self._server.shutdown()
self._server.server_close()
log.info("HTTP server stopped")
@background
def _run(self):
try:
if self._server:
self._server.serve_forever()
except Exception as e:
if self._running:
log.error("HTTP server error: %s", type(e).__name__)
finally:
self._running = False
def is_running(self):
return self._running
def get_status(self):
scheme = "https" if self.use_ssl else "http"
base_url = "%s://%s:%s" % (scheme, self.host, self.port)
return {
"running": self._running,
"host": self.host,
"port": self.port,
"ssl": self.use_ssl,
"url": base_url,
"mcp_url": mcp_endpoint_url(self.host, self.port, self.use_ssl),
"routes": self.route_registry.route_count,
"thread_alive": (self._thread.is_alive() if self._thread else False),
}