basal-engine 3.0.3__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.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/loadtest.py ADDED
@@ -0,0 +1,189 @@
1
+ """HTTP load test of a running basal server: sequential latency and throughput with concurrent clients.
2
+
3
+ basal-loadtest --url http://127.0.0.1:8000/v1/systemone --questions basal/examples/questions.jsonl
4
+ basal-loadtest --url http://127.0.0.1:8000/v1/systemone --synthetic 1500 --concurrency 16 # ~1.5k-token states
5
+ basal-loadtest --url http://127.0.0.1:8000/v1/systemone --synthetic 1500 --determinism 100
6
+
7
+ --determinism N asks N requests one at a time, then the same N again mixed with N other requests at --concurrency, and
8
+ compares the returned probabilities exactly (a server started with --deterministic must return identical answers).
9
+ """
10
+ import argparse
11
+ import asyncio
12
+ import json
13
+ import math
14
+ import statistics
15
+ import sys
16
+ import time
17
+ from pathlib import Path
18
+
19
+ import httpx
20
+
21
+ from . import synth
22
+ from .bench import DEFAULT_QUESTIONS, questions_or_exit
23
+ from .cli import add_api_key, headers, refused
24
+ from .jsonl import finite, write_json
25
+
26
+
27
+ def body(q, early_exit=None, questions=1):
28
+ """One request: the item's question, or (questions > 1) that many fixed questions over the item's state (SOAM);
29
+ past the 5 fixed ones they repeat, numbered ("... (2)"), so every question of a request has its own text."""
30
+ if questions > 1:
31
+ from .identity import QUESTIONS
32
+ from .prompt import lang_of
33
+ bank = QUESTIONS[lang_of(q["state"])]
34
+ qs = [(t if i < len(bank) else f"{t} ({i // len(bank) + 1})", o)
35
+ for i, (t, o) in ((i, bank[i % len(bank)]) for i in range(questions))]
36
+ else:
37
+ qs = [(q["question"], q["options"])]
38
+ b = {"state": q["state"], "questions": {
39
+ f"q{i}": {"type": "choice", "instructions": t, "option_keys": "hide",
40
+ "criteria": {f"option_{k + 1}": o for k, o in enumerate(opts)}} for i, (t, opts) in enumerate(qs)}}
41
+ if early_exit:
42
+ b["early_exit"] = early_exit
43
+ return b
44
+
45
+
46
+ def request_bodies(a, n):
47
+ """n request bodies: synthetic items, or the simple items of --questions (a small file reused); SystemExit when
48
+ there is none (a file of full requests only, or an empty one), which would loop for ever doubling no bodies."""
49
+ qs = synth.items(n, a.synthetic, a.seed, long_frac=a.long_frac) if a.synthetic else questions_or_exit(a.questions, n)
50
+ bodies = [body(q, a.early_exit, a.questions_per_request) for q in qs]
51
+ if not bodies and n > 0:
52
+ raise SystemExit(f"basal-loadtest: no simple items in {' '.join(map(str, a.questions))} (lines with \"state\", "
53
+ "\"question\" and \"options\"; full requests with \"questions\" are not used)")
54
+ while len(bodies) < n: # small question files are reused
55
+ bodies += bodies
56
+ return bodies
57
+
58
+
59
+ def nonnegative(s):
60
+ v = int(s)
61
+ if v < 0:
62
+ raise argparse.ArgumentTypeError(f"{s}: must be 0 or more")
63
+ return v
64
+
65
+
66
+ async def run(a):
67
+ if a.n_seq < 1:
68
+ raise SystemExit("basal-loadtest: --n-seq must be at least 1")
69
+ # warm-up, sequential and concurrent phases ask different requests (as far as the questions go), so an engine with
70
+ # a prefix cache across requests (vLLM, SGLang, llama.cpp) cannot answer a timed request from an earlier phase
71
+ n = 10 + a.n_seq + a.n_conc
72
+ bodies = request_bodies(a, n)
73
+ async with httpx.AsyncClient(timeout=300, headers=headers(getattr(a, "api_key", None))) as c:
74
+ for b in bodies[:10]: # warm-up
75
+ r = await c.post(a.url, json=b)
76
+ if refused(a.url, r.status_code, getattr(a, "api_key", None)):
77
+ raise SystemExit(f"basal-loadtest: {refused(a.url, r.status_code, a.api_key)}")
78
+ r.raise_for_status()
79
+ lat = []
80
+ for b in bodies[10: 10 + a.n_seq]:
81
+ t0 = time.perf_counter()
82
+ r = await c.post(a.url, json=b)
83
+ lat.append(time.perf_counter() - t0)
84
+ r.raise_for_status()
85
+ lat.sort()
86
+ sem = asyncio.Semaphore(a.concurrency)
87
+
88
+ async def one(b):
89
+ async with sem:
90
+ t0 = time.perf_counter()
91
+ try:
92
+ r = await c.post(a.url, json=b)
93
+ except httpx.HTTPError: # a timeout or a refused connection is an error, it does not end the run
94
+ return time.perf_counter() - t0, 0
95
+ return time.perf_counter() - t0, r.status_code
96
+
97
+ t0 = time.perf_counter()
98
+ res = await asyncio.gather(*[one(b) for b in bodies[10 + a.n_seq: n]])
99
+ wall = time.perf_counter() - t0
100
+ ok = sorted(x for x, s in res if s == 200) # p95: the nearest rank, ceil(0.95 n)-th smallest (as basal-bench)
101
+ out = dict(url=a.url, p50_ms=statistics.median(lat) * 1000, p95_ms=lat[math.ceil(0.95 * len(lat)) - 1] * 1000,
102
+ concurrency=a.concurrency, decisions_per_s=len(ok) / wall, errors=len(res) - len(ok))
103
+ out.update(sequential_p50_ms=out["p50_ms"], sequential_p95_ms=out["p95_ms"],
104
+ concurrent_p50_ms=statistics.median(ok) * 1000 if ok else None,
105
+ concurrent_p95_ms=ok[math.ceil(.95 * len(ok)) - 1] * 1000 if ok else None,
106
+ concurrent_p99_ms=ok[math.ceil(.99 * len(ok)) - 1] * 1000 if ok else None,
107
+ requests_per_s=len(ok) / wall)
108
+ if a.questions_per_request > 1: # a request is several decisions; the rates above count requests
109
+ out.update(questions_per_request=a.questions_per_request,
110
+ questions_per_s=len(ok) * a.questions_per_request / wall)
111
+ print(json.dumps({k: round(v, 2) if isinstance(v, float) else v for k, v in out.items()}))
112
+ if a.out:
113
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
114
+ write_json(a.out, finite(out), indent=1) # whole or not at all; a rate without a value: null
115
+
116
+
117
+ async def determinism(a, bodies):
118
+ """The same requests alone and under load -> identical answers, max |dp|."""
119
+ n = a.determinism
120
+ probe, other = bodies[:n], bodies[n: 2 * n]
121
+
122
+ def probs(r):
123
+ r.raise_for_status()
124
+ return [list(ans["probabilities"].values()) for ans in r.json()["answers"].values()]
125
+ async with httpx.AsyncClient(timeout=300, headers=headers(getattr(a, "api_key", None))) as c:
126
+ first = await c.post(a.url, json=probe[0])
127
+ if refused(a.url, first.status_code, getattr(a, "api_key", None)):
128
+ raise SystemExit(f"basal-loadtest: {refused(a.url, first.status_code, a.api_key)}")
129
+ alone = [probs(first)] + [probs(await c.post(a.url, json=b)) for b in probe[1:]]
130
+ sem = asyncio.Semaphore(a.concurrency)
131
+
132
+ async def one(b):
133
+ async with sem:
134
+ return await c.post(a.url, json=b)
135
+ mixed = [x for pair in zip(probe, other) for x in pair]
136
+ res = await asyncio.gather(*[one(b) for b in mixed])
137
+ loaded = [probs(r) for r in res[::2]]
138
+ gap = lambda x, y: abs(x - y) if math.isfinite(x) and math.isfinite(y) else 1.0 # noqa: E731 NaN or inf (inf - inf is NaN) is the largest possible change, not a skipped comparison
139
+ diffs = [1.0 if [len(pa) for pa in p] != [len(qa) for qa in q] else # an answer that vanished under load: the largest |dp|
140
+ max(gap(x, y) for pa, qa in zip(p, q) for x, y in zip(pa, qa)) for p, q in zip(alone, loaded)]
141
+ top = lambda ps: max(range(len(ps)), key=ps.__getitem__) # noqa: E731
142
+ flips = sum(top(pa) != top(qa) for p, q in zip(alone, loaded) for pa, qa in zip(p, q))
143
+ out = dict(url=a.url, determinism=dict(requests=n, identical=sum(d == 0.0 for d in diffs), max_abs_diff=max(diffs),
144
+ decision_flips=flips, concurrency=a.concurrency,
145
+ load_errors=sum(r.status_code != 200 for r in res[1::2])))
146
+ print(json.dumps(out))
147
+ if a.out:
148
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
149
+ write_json(a.out, finite(out), indent=1)
150
+
151
+
152
+ def main():
153
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
154
+ ap.add_argument("--url", default="http://127.0.0.1:8000/v1/systemone")
155
+ ap.add_argument("--questions", nargs="+", default=DEFAULT_QUESTIONS, help="JSONL file(s) with simple items")
156
+ ap.add_argument("--synthetic", type=int, default=None,
157
+ help="synthetic items with states of about this many tokens instead of --questions (basal.synth)")
158
+ ap.add_argument("--long-frac", dest="long_frac", type=float, default=0.0,
159
+ help="--synthetic: share of long states (3k-10k tokens)")
160
+ ap.add_argument("--seed", type=int, default=0,
161
+ help="--synthetic: the items' seed (a repeated run with another seed asks states that a server "
162
+ "with a prefix cache has not seen)")
163
+ ap.add_argument("--questions-per-request", dest="questions_per_request", type=int, default=1,
164
+ choices=range(1, 65), metavar="1-64",
165
+ help="2-64: that many fixed questions over each item's state in one request (SOAM; past 5 the "
166
+ "fixed questions repeat, numbered)")
167
+ ap.add_argument("--n-seq", dest="n_seq", type=int, default=200)
168
+ ap.add_argument("--n-conc", dest="n_conc", type=nonnegative, default=1000)
169
+ ap.add_argument("--concurrency", type=int, default=32)
170
+ ap.add_argument("--early-exit", dest="early_exit", default=None)
171
+ ap.add_argument("--determinism", type=nonnegative, default=0,
172
+ help="N: compare N answers given alone and under load (instead of the load test)")
173
+ ap.add_argument("--out", default=None)
174
+ add_api_key(ap)
175
+ a = ap.parse_args()
176
+ if a.concurrency < 1:
177
+ raise SystemExit("basal-loadtest: --concurrency must be at least 1")
178
+ if a.determinism:
179
+ n = a.determinism
180
+ bodies = request_bodies(a, 2 * n)
181
+ if len({json.dumps(b, sort_keys=True) for b in bodies[:2 * n]}) < 2 * n: # probe and mixed-in requests
182
+ print("warning: fewer than 2 x N distinct requests: the mixed pass repeats requests of the probe "
183
+ "(a weaker test; give more questions or --synthetic)", file=sys.stderr)
184
+ return asyncio.run(determinism(a, bodies))
185
+ asyncio.run(run(a))
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
basal/mcp_server.py ADDED
@@ -0,0 +1,432 @@
1
+ """MCP for agents: the typed decisions of a basal server as two tools of a Model Context Protocol server.
2
+
3
+ - `basal-serve ... --mcp on`: the server also answers MCP (streamable HTTP) at /mcp, on its own port and through the
4
+ same queue as /v1/systemone.
5
+ - `basal-mcp --url http://host:8000`: a stdio bridge to a running server, for agent hosts that start MCP servers as
6
+ local processes.
7
+
8
+ Tools: `decide` (one question) and `decide_many` (several questions over one state, every question type of the HTTP
9
+ API); with a basal-navigate tree (basal-serve --mcp-tree, basal-mcp --tree) also `navigate` (the passages that
10
+ answer a question, Navigator.search) and `read_page` (a node of the tree and the passages under it). All are
11
+ read-only. Needs the optional extra: `uv pip install "basal-engine[mcp]"`."""
12
+ import argparse
13
+ import inspect
14
+ import json
15
+ from typing import Annotated, Any, Literal
16
+
17
+ INSTALL = 'MCP needs the mcp package: uv pip install "basal-engine[mcp]"'
18
+ READ_CHILDREN = 100 # the children read_page lists (children_total: how many there are, when more)
19
+
20
+ HOW = """basal ({model}) answers typed questions about a state in one forward pass, without generating text, and \
21
+ returns calibrated probabilities. Use it for routing, yes/no checks, scores and label sets when you want a fast, \
22
+ repeatable answer with a confidence you can act on.
23
+
24
+ How to ask:
25
+ - Put every fact and rule the decision needs in `state`: the model decides only from what it reads.
26
+ - One condition per yes/no question; for several labels use type "multi".
27
+ - Describe what each option means, not only its name; offer a "cannot be determined" option when the state may not \
28
+ contain the answer.
29
+ - Ask in the language of the state (Polish or English); compute numbers and dates yourself and ask the decision on top.
30
+ - Several questions about the same state: one `decide_many` call is faster than separate calls and gives the same \
31
+ answers.
32
+
33
+ Using the answer: `confidence` is the calibrated probability of the returned answer. Below the confidence your task \
34
+ needs, check the case yourself or ask the user. 2-255 options per question (basal-1.x models: 2-10)."""
35
+
36
+ SEVERAL = """
37
+
38
+ Several models are loaded on this server: call `list_models` and pass one of them as `model` to every decision."""
39
+
40
+
41
+ NAVIGATE = """
42
+
43
+ This server also searches a document collection (basal-navigate's tree): `navigate` returns the passages that \
44
+ answer a question (or the latest turns of a conversation), best first, each with its page; `read_page` reads a page \
45
+ (or any node of the tree) and the passages under it. Pass the user's question as it is: navigate asks basal which \
46
+ topics, pages and passages hold the answer."""
47
+
48
+
49
+ def navigation(tree, settings=None):
50
+ """--mcp-tree / --tree and --mcp-navigate / --navigate: the tree file and a JSON object of basal.navigate.Navigator's
51
+ keyword arguments (levels, final, style, lang, wording, chunk, order, turns, split_at) -> (Tree, the arguments),
52
+ read and checked before anything is served; SystemExit with what is wrong."""
53
+ from .jsonl import JSONLError
54
+ from .navigate import Navigator, Tree
55
+ try:
56
+ t = Tree.load(tree)
57
+ except JSONLError as e:
58
+ raise SystemExit(f"basal: the navigate tree: {e}") from None
59
+ except (OSError, ValueError) as e: # a missing file; a node without an id or a text, a cycle
60
+ raise SystemExit(f"basal: the navigate tree {tree}: {e}") from None
61
+ try:
62
+ kw = json.loads(settings) if isinstance(settings, str) else dict(settings or {})
63
+ except ValueError as e:
64
+ raise SystemExit(f"basal: the navigate settings are not JSON: {e}") from None
65
+ if not isinstance(kw, dict) or "client" in kw or "tree" in kw:
66
+ raise SystemExit("basal: the navigate settings are a JSON object of Navigator's settings (levels, final, "
67
+ "style, lang, wording, chunk, order, turns, split_at)")
68
+ try:
69
+ Navigator(None, t, **kw)
70
+ except (TypeError, ValueError) as e: # an unknown setting, a level that is not an object
71
+ raise SystemExit(f"basal: the navigate settings: {e}") from None
72
+ return t, kw
73
+
74
+
75
+ class _Asks:
76
+ """basal.navigate.Navigator's client (request(body) -> the response), used from the worker thread a search runs in:
77
+ each request goes to `ask` on the event loop, with `model` when given. stop() cancels the request in flight and
78
+ refuses the next, so a cancelled tool call sends no more requests. A lock makes the check and the send one step: a
79
+ stop() between them would otherwise find no request to cancel and let that one out."""
80
+
81
+ def __init__(self, ask, loop, model=None):
82
+ import threading
83
+ self.ask, self.loop, self.model = ask, loop, model
84
+ self.stopped, self.pending, self.lock = threading.Event(), None, threading.Lock()
85
+
86
+ def request(self, body):
87
+ import asyncio
88
+ import concurrent.futures
89
+ if self.model is not None:
90
+ body = {**body, "model": self.model}
91
+ with self.lock: # (held for the check and the scheduling only, never while waiting for the answer)
92
+ if self.stopped.is_set():
93
+ raise concurrent.futures.CancelledError()
94
+ self.pending = pending = asyncio.run_coroutine_threadsafe(self.ask(body), self.loop)
95
+ return pending.result()
96
+
97
+ def stop(self):
98
+ with self.lock:
99
+ self.stopped.set()
100
+ if self.pending is not None:
101
+ self.pending.cancel()
102
+
103
+
104
+ def available():
105
+ """None when the mcp package imports, else the install hint (checked before a model is loaded)."""
106
+ try:
107
+ import mcp.server.mcpserver # noqa: F401
108
+ except ImportError:
109
+ return INSTALL
110
+ return None
111
+
112
+
113
+ def build(decide, model="basal", models=None, navigate=None):
114
+ """decide: async request body -> response (Server.decide, or `remote` for the bridge). models: callable for loaded
115
+ model ids, or None for one model. navigate: (Tree, Navigator's settings) of `navigation`, for the tools navigate
116
+ and read_page. -> the MCP server."""
117
+ from mcp.server.mcpserver import MCPServer
118
+ from mcp.server.mcpserver.exceptions import ToolError
119
+ from mcp.types import ToolAnnotations
120
+ from pydantic import Field # comes with mcp
121
+
122
+ State = Annotated[str | dict[str, Any], Field(description="The text (or a JSON object) the decision is based on, "
123
+ "with every fact and rule it needs.")]
124
+ Lang = Annotated[Literal["pl", "en"] | None, Field(description="The prompt language, when the state text does not "
125
+ "show it (default: Polish if the state or question "
126
+ "has Polish diacritics, else English).")]
127
+ Model = Annotated[str | None, Field(description="A loaded model id (see list_models).")]
128
+ from . import __version__
129
+
130
+ srv = MCPServer(name="basal", version=__version__,
131
+ instructions=HOW.format(model=model) + (SEVERAL if models is not None else "")
132
+ + (NAVIGATE if navigate is not None else ""),
133
+ log_level="WARNING")
134
+ ro = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
135
+
136
+ def tool(fn):
137
+ name = "decide" if fn.__name__ == "decide_one" else fn.__name__
138
+ if models is not None:
139
+ return srv.tool(name=name, annotations=ro)(fn)
140
+
141
+ async def one_model(**kwargs):
142
+ return await fn(**kwargs, model=None)
143
+
144
+ one_model.__name__, one_model.__doc__ = fn.__name__, fn.__doc__
145
+ signature = inspect.signature(fn)
146
+ one_model.__signature__ = signature.replace(
147
+ parameters=[p for p in signature.parameters.values() if p.name != "model"])
148
+ return srv.tool(name=name, annotations=ro)(one_model)
149
+
150
+ async def ask(body):
151
+ try:
152
+ return await decide(body)
153
+ except Exception as e: # noqa: BLE001
154
+ # the message of the HTTP API's error, so the agent can fix its call (an exception without one: its type)
155
+ raise ToolError(str(e) or type(e).__name__) from e
156
+
157
+ @tool
158
+ async def decide_one(
159
+ state: State,
160
+ question: Annotated[str, Field(description="The question: one condition, phrased for the state.")],
161
+ type: Annotated[Literal["choice", "noul", "score", "multi"],
162
+ Field(description="choice: one of the options; noul: probability of yes; score: an "
163
+ "ordered level; multi: every option that applies.")] = "choice",
164
+ options: Annotated[dict[str, str | None] | list[str] | None,
165
+ Field(description="choice / multi: key -> what the option means (or a list of keys); "
166
+ "score: the levels, lowest first; noul: optional {\"true\": ..., "
167
+ "\"false\": ...}.")] = None,
168
+ lang: Lang = None,
169
+ model: Model = None) -> dict[str, Any]:
170
+ """Answer one typed question about a state with calibrated probabilities. Returns the answer (choice, noul,
171
+ score or selected), its probabilities and confidence, and the model name."""
172
+ q: dict[str, Any] = {"type": type, "instructions": question}
173
+ if options is not None:
174
+ q["criteria"] = options
175
+ body: dict[str, Any] = {"state": state, "questions": {"answer": q}}
176
+ if lang:
177
+ body["lang"] = lang
178
+ if model is not None:
179
+ body["model"] = model
180
+ r = await ask(body)
181
+ return {"model": r.get("model"), **r["answers"]["answer"]}
182
+
183
+ @tool
184
+ async def decide_many(
185
+ state: State,
186
+ questions: Annotated[dict[str, dict[str, Any]],
187
+ Field(description="name -> question, as in the basal HTTP API: {\"type\": \"choice\" "
188
+ "| \"noul\" | \"score\" | \"multi\" | \"act\" | \"tool\", "
189
+ "\"instructions\": ..., \"criteria\": ...} plus the type's fields "
190
+ "(choice / noul / score: coverage, max_error; multi: threshold, "
191
+ "min, max, objective; act: costs, max_error; tool: tools, extra, "
192
+ "rank, max_error; any: option_keys).")],
193
+ lang: Lang = None,
194
+ facts: Annotated[Literal["off", "auto"] | None,
195
+ Field(description="auto: append computed calendar and money facts to a Polish "
196
+ "state.")] = None,
197
+ model: Model = None) -> dict[str, Any]:
198
+ """Answer several typed questions about one state in one pass (every question type of the basal HTTP API,
199
+ including cost-aware actions with deferral to a person, and the next tool of an agent). Returns the API
200
+ response: answers by question name, the model name and usage."""
201
+ body: dict[str, Any] = {"state": state, "questions": questions}
202
+ for k, v in (("lang", lang), ("facts", facts)):
203
+ if v:
204
+ body[k] = v
205
+ if model is not None:
206
+ body["model"] = model
207
+ return await ask(body)
208
+
209
+ if models is not None:
210
+ @srv.tool(annotations=ro)
211
+ async def list_models() -> dict[str, Any]:
212
+ """The ids of the models loaded on this server: pass one as `model` to decide and decide_many."""
213
+ return {"models": list(models())}
214
+
215
+ if navigate is not None:
216
+ add_navigate(srv, tool, ask, ro, ToolError, Field, Model, *navigate)
217
+ return srv
218
+
219
+
220
+ def add_navigate(srv, tool, ask, ro, ToolError, Field, Model, tree, settings):
221
+ """The tools navigate (basal.navigate.Navigator.search over the tree, through `ask`: the fields of a basal-navigate
222
+ --queries line and k) and read_page (a node of the tree and the passages under it; no request)."""
223
+ import asyncio
224
+
225
+ from .navigate import Navigator
226
+
227
+ def page_of(i):
228
+ while i is not None and tree.nodes[i].get("kind") != "page":
229
+ i = tree.nodes[i].get("parent")
230
+ return i
231
+
232
+ @tool
233
+ async def navigate(
234
+ query: Annotated[str | None, Field(description="The question to find passages for (or give turns).")] = None,
235
+ turns: Annotated[list[str | dict[str, str]] | None,
236
+ Field(description="A conversation instead of a query, oldest turn first: {\"role\": "
237
+ "\"user\" | \"agent\", \"text\": ...} or plain strings; its latest "
238
+ "turns are the query.")] = None,
239
+ k: Annotated[int, Field(ge=1, le=100, description="How many passages to return, best first.")] = 10,
240
+ pin: Annotated[list[str] | None,
241
+ Field(description="Node ids always kept at their level (pages already in use).")] = None,
242
+ extra: Annotated[list[str] | None,
243
+ Field(description="Passage ids added to the last stage (another retriever's).")] = None,
244
+ model: Model = None) -> dict[str, Any]:
245
+ """Find the passages of the document collection that answer a question, by navigating its tree (topics,
246
+ pages, passages) with basal's decisions. Returns the passages best first (id, score, text, its page and the
247
+ heading it is under), the server's rank requests (as basal-navigate counts them) and the latency."""
248
+ if (query is None) == (turns is None) or (query is not None and not query.strip()) or turns == []:
249
+ raise ToolError("give a query or turns, not both")
250
+ asks = _Asks(ask, asyncio.get_running_loop(), model)
251
+ nav = Navigator(asks, tree, **settings)
252
+ try: # (a request cancelled under the search ends it as asyncio.CancelledError, from to_thread)
253
+ r = await asyncio.to_thread(nav.search, query if query is not None else turns, k, pin or (), extra or ())
254
+ except asyncio.CancelledError:
255
+ asks.stop() # (the search's thread sends nothing more)
256
+ raise
257
+ except (ValueError, KeyError, TypeError) as e: # a turn without text, a split the server cannot take
258
+ raise ToolError(f"navigate: {e}") from e
259
+ hits = []
260
+ for h in r["passages"]:
261
+ x = tree.nodes[h["id"]]
262
+ hits.append({**h, "page": page_of(h["id"]), "group": tree.group(h["id"]),
263
+ **({"path": x["path"]} if x.get("path") else {})})
264
+ return {"passages": hits, "requests": sum(s["requests"] for s in r["stages"]), "latency_ms": r["latency_ms"]}
265
+
266
+ @srv.tool(annotations=ro)
267
+ async def read_page(
268
+ id: Annotated[str, Field(description="A node id: a passage's page from navigate, or any node.")],
269
+ max_chars: Annotated[int, Field(ge=100, le=1_000_000,
270
+ description="At most this much text: the node's own, and that of the "
271
+ "passages under it.")] = 20_000) -> dict[str, Any]:
272
+ """Read a page of the document collection (or any node of its tree): its kind, title, text and the heading
273
+ it is under, its first 100 children (children_total: how many, when there are more), and the passages under
274
+ it in reading order (the node's text and the passages' each up to max_chars; `truncated` says when there was
275
+ more)."""
276
+ if id not in tree.nodes:
277
+ raise ToolError(f"no node {id!r} in the tree")
278
+ x = tree.nodes[id]
279
+ kids = tree.children.get(id, [])
280
+ own = x["text"][:max_chars] # (a passage's own text is also its first passage: both within max_chars)
281
+ out = {"id": id, "kind": x.get("kind"), "title": x.get("title"), "text": own, "group": tree.group(id),
282
+ "parent": x.get("parent"), "page": page_of(id),
283
+ "children": [{"id": c, "kind": tree.nodes[c].get("kind"), "title": tree.title(c)}
284
+ for c in kids[:READ_CHILDREN]],
285
+ "children_total": len(kids) if len(kids) > READ_CHILDREN else None}
286
+ passages, left, cut = [], max_chars, False
287
+ for p in tree.iter_leaves(id): # (a generator: the walk stops with the cut)
288
+ text = tree.nodes[p]["text"]
289
+ if len(text) > left:
290
+ cut = True
291
+ if passages:
292
+ break
293
+ text = text[:left] # one passage longer than max_chars: its start
294
+ passages.append({"id": p, "text": text, **({"path": tree.nodes[p]["path"]}
295
+ if tree.nodes[p].get("path") else {})})
296
+ left -= len(text)
297
+ if cut:
298
+ break
299
+ return {**{k: v for k, v in out.items() if v is not None}, "passages": passages,
300
+ "truncated": cut or len(own) < len(x["text"])}
301
+
302
+
303
+ def http(server, host, models=None, navigate=None):
304
+ """--mcp on: the MCP tools of a running basal server -> (routes for /mcp, the session manager's lifespan).
305
+ Stateless JSON responses: every call is one request. Bound to a loopback host, Host / Origin are checked (DNS
306
+ rebinding). models, navigate: see build. A tool call whose HTTP client disconnects is cancelled, as on POST /v1/systemone:
307
+ the SDK does not watch the disconnect, but a stateless request's session, and its tool call, end with its
308
+ handler (basal/disconnect.py)."""
309
+ import inspect
310
+
311
+ from starlette.routing import Route
312
+
313
+ from .disconnect import CancelOnDisconnect
314
+ m = build(getattr(server, "serve", server.decide), getattr(server, "name", None) or "basal", models, navigate)
315
+ app = m.streamable_http_app(host=host, stateless_http=True, json_response=True)
316
+ routes = [Route(r.path, CancelOnDisconnect(r.endpoint), methods=r.methods, name=r.name) # (the ASGI app at /mcp)
317
+ if isinstance(r, Route) and not inspect.isroutine(r.endpoint) else r for r in app.routes]
318
+ return routes, m.session_manager.run
319
+
320
+
321
+ def remote(url, timeout=60.0, transport=None, model=None, api_key=None):
322
+ """decide over HTTP for the bridge: POST <url>/v1/systemone (with `model` when given, and the bearer api_key); the
323
+ server's error message on HTTP errors, and what failed when there is no answer (a timeout: --timeout)."""
324
+ import httpx
325
+
326
+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
327
+ client = httpx.AsyncClient(base_url=url.rstrip("/"), timeout=timeout, transport=transport, headers=headers)
328
+
329
+ async def decide(body):
330
+ if model is not None:
331
+ body = {"model": model, **body}
332
+ try:
333
+ r = await client.post("/v1/systemone", json=body)
334
+ except httpx.TimeoutException as e: # (str() of httpx's timeouts is empty: the agent saw no reason)
335
+ raise ValueError(f"the basal server at {url} did not answer within {timeout} s (basal-mcp --timeout; "
336
+ f"{type(e).__name__})") from None
337
+ except httpx.HTTPError as e:
338
+ raise ValueError(f"the basal server at {url}: {type(e).__name__}: {e}") from None
339
+ if r.status_code != 200:
340
+ try:
341
+ msg = r.json()["error"]
342
+ except Exception: # noqa: BLE001
343
+ msg = r.text
344
+ raise ValueError(f"basal server {r.status_code}: {msg}")
345
+ return r.json()
346
+
347
+ return decide
348
+
349
+
350
+ def model_name(url, timeout=5.0, api_key=None):
351
+ """The served model's name from GET /v1/models; "basal" when the server does not answer yet."""
352
+ import httpx
353
+
354
+ try:
355
+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
356
+ return httpx.get(url.rstrip("/") + "/v1/models", timeout=timeout, headers=headers).json()["models"][0]["name"]
357
+ except Exception: # noqa: BLE001
358
+ return "basal"
359
+
360
+
361
+ def unreadable(exc):
362
+ """The JSON-RPC error reply to a stdin line the MCP SDK could not read. The SDK only logs such a line, so the
363
+ client waited for ever for its answer. Invalid JSON is a parse error (-32700), and so is a lone surrogate
364
+ ("\\ud800"), which Python's json reads but the SDK's parser refuses; JSON that is no JSON-RPC message is an invalid
365
+ request (-32600). The reply carries the line's id when json reads one, else null."""
366
+ from mcp.shared.message import SessionMessage
367
+ from mcp.types import INVALID_REQUEST, PARSE_ERROR, ErrorData, JSONRPCError
368
+ errors = exc.errors() if callable(getattr(exc, "errors", None)) else []
369
+ line = errors[0].get("input") if errors else None
370
+ rid = None
371
+ try:
372
+ msg = json.loads(line) if isinstance(line, (str, bytes)) else line # the line, or the JSON the SDK read
373
+ rid = msg.get("id") if isinstance(msg, dict) else None
374
+ if isinstance(rid, str):
375
+ rid.encode("utf-8") # an id with a lone surrogate cannot be written back
376
+ except (ValueError, RecursionError): # not JSON (UnicodeEncodeError is a ValueError)
377
+ rid = None
378
+ if isinstance(rid, bool) or not isinstance(rid, (int, str)):
379
+ rid = None
380
+ parse = any(e.get("type") == "json_invalid" for e in errors) or not errors
381
+ code, text = (PARSE_ERROR, "Parse error: the line is not valid JSON (a lone surrogate such as \\ud800 is not "
382
+ "allowed)") if parse else (INVALID_REQUEST, "Invalid Request: not a JSON-RPC message")
383
+ return SessionMessage(JSONRPCError(jsonrpc="2.0", id=rid, error=ErrorData(code=code, message=text)))
384
+
385
+
386
+ def serve_stdio(server):
387
+ """server.run("stdio"), with an error reply (unreadable) to every stdin line the SDK cannot read."""
388
+ import anyio
389
+ from mcp.server.stdio import stdio_server
390
+
391
+ async def run():
392
+ low = server._lowlevel_server # as the SDK's own run_stdio_async (mcp 2.3)
393
+ async with stdio_server() as (read, write):
394
+ send, recv = anyio.create_memory_object_stream(0)
395
+
396
+ async def pump():
397
+ async with send:
398
+ async for item in read:
399
+ await (write.send(unreadable(item)) if isinstance(item, Exception) else send.send(item))
400
+
401
+ async with anyio.create_task_group() as tg:
402
+ tg.start_soon(pump)
403
+ await low.run(recv, write, low.create_initialization_options())
404
+
405
+ anyio.run(run)
406
+
407
+
408
+ def main(argv=None):
409
+ ap = argparse.ArgumentParser(description="basal over MCP (stdio): a bridge to a running basal server for agent "
410
+ "hosts that start MCP servers as local processes")
411
+ ap.add_argument("--url", default="http://127.0.0.1:8000", help="the basal server (basal-serve)")
412
+ ap.add_argument("--model", help="the model id to ask on a server with several models")
413
+ ap.add_argument("--api-key", default=None, help="Bearer API key")
414
+ ap.add_argument("--timeout", type=float, default=60.0, help="seconds per request")
415
+ ap.add_argument("--tree", default=None, metavar="TREE.jsonl",
416
+ help="also the tools navigate and read_page over this basal-navigate tree (basal-navigate build)")
417
+ ap.add_argument("--navigate", default=None, metavar="JSON",
418
+ help='with --tree: basal.navigate.Navigator\'s settings, e.g. \'{"levels": [{"keep": 10}], "final": '
419
+ '{"top": 20}}\' (default: those of basal-navigate search)')
420
+ a = ap.parse_args(argv)
421
+ msg = available()
422
+ if msg:
423
+ raise SystemExit(msg)
424
+ if a.navigate is not None and a.tree is None:
425
+ raise SystemExit("basal-mcp: --navigate needs --tree")
426
+ nav = navigation(a.tree, a.navigate) if a.tree else None
427
+ name = a.model or model_name(a.url, api_key=a.api_key)
428
+ serve_stdio(build(remote(a.url, a.timeout, model=a.model, api_key=a.api_key), name, navigate=nav))
429
+
430
+
431
+ if __name__ == "__main__":
432
+ main()