import argparse
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
HTML = """
Local tool web app
Local tool web app
A deterministic tool baseline, without a model or API key.
"""
def run_tool(action, text):
if not isinstance(text, str) or not text.strip() or len(text) > 2000:
raise ValueError("Enter 1–2000 characters of text.")
tools = {"count_words": lambda value: {"words": len(value.split())}, "first_sentence": lambda value: {"sentence": value.strip().split(".")[0]}}
if action not in tools:
raise ValueError("Choose an allowed tool.")
return {"tool": action, "result": tools[action](text), "trace": ["validated input", action, "returned result"]}
class Handler(BaseHTTPRequestHandler):
def reply(self, status, data):
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path != "/":
return self.reply(404, {"error": "Not found"})
body = HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
if self.path != "/api/run":
return self.reply(404, {"error": "Not found"})
try:
length = int(self.headers.get("Content-Length", "0"))
if not 0 < length <= 8192:
raise ValueError("Request must be 1–8192 bytes.")
data = json.loads(self.rfile.read(length))
if not isinstance(data, dict):
raise ValueError("Send a JSON object.")
return self.reply(200, run_tool(data.get("action"), data.get("text")))
except (ValueError, TypeError, UnicodeError):
return self.reply(400, {"error": "Check the JSON, allowed tool and non-empty text (up to 2000 characters)."})
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=8766)
args = parser.parse_args()
print(f"Open http://127.0.0.1:{args.port}", flush=True)
try:
ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever()
except KeyboardInterrupt:
print("Server stopped.")