@simplexai/localmodels-linux-x64 0.1.0-dev.35 → 0.1.0-dev.37
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +124 -102
- package/kit.py +1 -0
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +9 -3
- package/modules/localmodels/bifrost_config.py +188 -0
- package/modules/localmodels/budget.py +15 -2
- package/modules/localmodels/catalog.json +235 -2
- package/modules/localmodels/catalog.py +51 -320
- package/modules/localmodels/catalog_add.py +2 -8
- package/modules/localmodels/catalog_recipes.py +321 -0
- package/modules/localmodels/cli_parser.py +4 -1
- package/modules/localmodels/console.py +5 -4
- package/modules/localmodels/contracts.py +13 -3
- package/modules/localmodels/debug_cli.py +158 -0
- package/modules/localmodels/debug_mode.py +727 -0
- package/modules/localmodels/debug_stub_server.py +192 -0
- package/modules/localmodels/decode_calibration.json +1 -1
- package/modules/localmodels/decode_calibration.py +34 -17
- package/modules/localmodels/engines-strata-0.1.59.1.json +31 -0
- package/modules/localmodels/gateway.py +21 -155
- package/modules/localmodels/gateway_accept.py +201 -0
- package/modules/localmodels/gateway_bifrost.py +19 -184
- package/modules/localmodels/gateway_cli.py +11 -4
- package/modules/localmodels/gateway_foundations.py +2 -4
- package/modules/localmodels/gateway_probe.py +0 -1
- package/modules/localmodels/gateway_server.py +2 -3
- package/modules/localmodels/gpu_specs.py +12 -0
- package/modules/localmodels/guard.py +2 -7
- package/modules/localmodels/harness.py +16 -129
- package/modules/localmodels/harness_cleanup.py +135 -0
- package/modules/localmodels/harness_gateway.py +16 -14
- package/modules/localmodels/harness_probe.py +12 -4
- package/modules/localmodels/hosts.py +25 -2
- package/modules/localmodels/http_local.py +59 -0
- package/modules/localmodels/install.py +23 -8
- package/modules/localmodels/library_gateway.py +9 -9
- package/modules/localmodels/library_jobs.py +76 -27
- package/modules/localmodels/library_serve.py +12 -1
- package/modules/localmodels/library_state.py +6 -1
- package/modules/localmodels/llm_rank.py +155 -7
- package/modules/localmodels/metal_probe.py +11 -7
- package/modules/localmodels/probe.py +108 -174
- package/modules/localmodels/process_identity.py +109 -154
- package/modules/localmodels/process_windows.py +86 -0
- package/modules/localmodels/recommend.py +32 -3
- package/modules/localmodels/recommend_cli.py +14 -6
- package/modules/localmodels/remote_ops.py +65 -0
- package/modules/localmodels/remote_ops_download.py +2 -2
- package/modules/localmodels/remote_ops_prepare.py +19 -0
- package/modules/localmodels/remote_ops_service.py +14 -2
- package/modules/localmodels/runtime_args.py +10 -3
- package/modules/localmodels/runtime_auth.py +5 -9
- package/modules/localmodels/runtime_cli.py +128 -129
- package/modules/localmodels/runtime_discovery.py +84 -0
- package/modules/localmodels/runtime_install.py +101 -0
- package/modules/localmodels/runtime_releases.py +302 -0
- package/modules/localmodels/service_stop.py +8 -108
- package/modules/localmodels/service_upgrade.py +394 -63
- package/modules/localmodels/services_cli.py +24 -14
- package/modules/localmodels/setup_inspection.py +97 -9
- package/modules/localmodels/setup_text.py +7 -0
- package/modules/localmodels/sizecalc.py +0 -1
- package/modules/localmodels/stack.py +14 -221
- package/modules/localmodels/stack_arena.py +732 -0
- package/modules/localmodels/stack_args.py +15 -9
- package/modules/localmodels/stack_auto.py +384 -3
- package/modules/localmodels/stack_aux_gpu.py +4 -3
- package/modules/localmodels/stack_capacity.py +138 -0
- package/modules/localmodels/stack_cleanup.py +9 -4
- package/modules/localmodels/stack_cli.py +286 -0
- package/modules/localmodels/stack_compose.py +76 -32
- package/modules/localmodels/stack_console.py +9 -6
- package/modules/localmodels/stack_hardware.py +96 -270
- package/modules/localmodels/stack_hardware_text.py +263 -0
- package/modules/localmodels/stack_journal.py +3 -9
- package/modules/localmodels/stack_ledger.py +48 -18
- package/modules/localmodels/stack_lifecycle.py +33 -312
- package/modules/localmodels/stack_mcp.py +729 -0
- package/modules/localmodels/stack_memory.py +0 -2
- package/modules/localmodels/stack_picks.py +73 -18
- package/modules/localmodels/stack_plan.py +23 -5
- package/modules/localmodels/stack_preflight.py +11 -19
- package/modules/localmodels/stack_remove.py +373 -0
- package/modules/localmodels/stack_route.py +101 -17
- package/modules/localmodels/stack_suite.py +16 -10
- package/modules/localmodels/stack_summary.py +14 -0
- package/modules/localmodels/stack_try.py +238 -24
- package/modules/localmodels/stack_try_client.py +53 -15
- package/modules/localmodels/stack_try_docs.py +2 -2
- package/modules/localmodels/stack_view.py +24 -171
- package/modules/localmodels/stack_view_access.py +114 -1
- package/modules/localmodels/stack_view_agent.py +3 -13
- package/modules/localmodels/stack_view_hub.py +9 -10
- package/modules/localmodels/stack_view_llm.py +1 -1
- package/modules/localmodels/stack_view_sandbox.py +2 -2
- package/modules/localmodels/stack_view_schema.py +183 -0
- package/modules/localmodels/stack_view_serve.py +7 -1
- package/modules/localmodels/stack_view_service.py +1 -2
- package/modules/localmodels/stack_view_text.py +13 -9
- package/modules/localmodels/stack_warm.py +3 -0
- package/modules/localmodels/stack_warm_store.py +517 -0
- package/modules/localmodels/tui.py +28 -4
- package/modules/localmodels/tui_dialogs.py +136 -0
- package/modules/localmodels/tui_modals.py +279 -0
- package/modules/localmodels/tui_screen.py +113 -154
- package/modules/localmodels/tui_views.py +134 -203
- package/modules/localmodels/web/index.html +510 -101
- package/modules/localmodels/web/sizecalc/app.js +363 -10
- package/modules/localmodels/web/sizecalc/page.html +27 -3
- package/modules/localmodels/web/view/fleet.html +11 -2
- package/modules/localmodels/web/view/fleet.js +191 -17
- package/modules/localmodels/web/view/i18n.js +3 -2
- package/modules/localmodels/web/view/index.html +1 -1
- package/modules/localmodels/web/view/nav.js +22 -3
- package/modules/localmodels/web/view/view.css +63 -18
- package/modules/localmodels/web/view/view.js +169 -32
- package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +120 -98
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
- /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev35.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
"""Read-only stdio MCP (JSON-RPC 2.0) server for ``localmodels stack``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import contextlib
|
|
7
|
+
import copy
|
|
8
|
+
import io
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import os
|
|
12
|
+
import stat
|
|
13
|
+
import sys
|
|
14
|
+
from collections.abc import Callable, Mapping
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, BinaryIO, TextIO, cast
|
|
17
|
+
|
|
18
|
+
from localmodels import (
|
|
19
|
+
__version__,
|
|
20
|
+
catalog,
|
|
21
|
+
cli_help,
|
|
22
|
+
deploy,
|
|
23
|
+
gguf,
|
|
24
|
+
metal,
|
|
25
|
+
stack_hardware,
|
|
26
|
+
stack_lifecycle,
|
|
27
|
+
stack_memory,
|
|
28
|
+
stack_whatif,
|
|
29
|
+
suite,
|
|
30
|
+
vision,
|
|
31
|
+
)
|
|
32
|
+
from localmodels.context_policy import AGENT
|
|
33
|
+
from localmodels.contracts import decode
|
|
34
|
+
from localmodels.memcalc import KV_TYPES, MemcalcError, parse_tokens
|
|
35
|
+
from localmodels.plan_envelope import PlanError
|
|
36
|
+
from localmodels.probe import HostFacts
|
|
37
|
+
from localmodels.stack_compose import agent_posture, choose_parts, ram_budget
|
|
38
|
+
from localmodels.stack_plan import PREFERENCES, StackError, default_options
|
|
39
|
+
|
|
40
|
+
GIB = 1 << 30
|
|
41
|
+
MAX_FRAME_BYTES = 16 << 20
|
|
42
|
+
MAX_HEADER_LINES = 64
|
|
43
|
+
MAX_FACTS_BYTES = 8 << 20
|
|
44
|
+
MAX_MEMORY_GIB = 1 << 20
|
|
45
|
+
MAX_SLOTS_INPUT = 4096
|
|
46
|
+
MAX_CONTEXT_TOKENS = 1 << 26
|
|
47
|
+
SUPPORTED_VERSIONS = ("2024-11-05", "2025-03-26")
|
|
48
|
+
DEFAULT_VERSION = "2024-11-05"
|
|
49
|
+
SERVER_INFO = {"name": "localmodels-stack-mcp", "version": __version__}
|
|
50
|
+
SUMMARY = "read-only stdio MCP server for hardware, memory, what-if and status"
|
|
51
|
+
DESCRIPTION = (
|
|
52
|
+
"Serve the stack's read-only inspection tools (stack_hardware, stack_memory, "
|
|
53
|
+
"stack_what_if and stack_status) over standard input and output as JSON-RPC 2.0 "
|
|
54
|
+
"Model Context Protocol messages. Accepts newline-delimited JSON and Content-Length "
|
|
55
|
+
"framed requests, replies in the matching framing, and never installs, starts, stops "
|
|
56
|
+
"or modifies local state."
|
|
57
|
+
)
|
|
58
|
+
EXAMPLES = [("%(prog)s", "serve read-only stack tools over stdio")]
|
|
59
|
+
ANNOTATIONS = {"readOnlyHint": True, "destructiveHint": False, "idempotentHint": True}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _num_prop(description: str) -> dict[str, Any]:
|
|
63
|
+
return {"type": "number", "exclusiveMinimum": 0, "description": description}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _str_prop(description: str) -> dict[str, Any]:
|
|
67
|
+
return {"type": "string", "minLength": 1, "description": description}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _enum_prop(choices: list[str] | tuple[str, ...], description: str) -> dict[str, Any]:
|
|
71
|
+
return {"type": "string", "enum": list(choices), "description": description}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _tool_def(
|
|
75
|
+
name: str,
|
|
76
|
+
description: str,
|
|
77
|
+
properties: dict[str, Any],
|
|
78
|
+
*,
|
|
79
|
+
required: tuple[str, ...] = (),
|
|
80
|
+
) -> dict[str, Any]:
|
|
81
|
+
schema: dict[str, Any] = {
|
|
82
|
+
"type": "object",
|
|
83
|
+
"properties": properties,
|
|
84
|
+
"additionalProperties": False,
|
|
85
|
+
}
|
|
86
|
+
if required:
|
|
87
|
+
schema["required"] = list(required)
|
|
88
|
+
return {
|
|
89
|
+
"name": name,
|
|
90
|
+
"description": description,
|
|
91
|
+
"inputSchema": schema,
|
|
92
|
+
"annotations": dict(ANNOTATIONS),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
TOOLS: tuple[dict[str, Any], ...] = (
|
|
97
|
+
_tool_def(
|
|
98
|
+
"stack_hardware",
|
|
99
|
+
"Read-only hardware inspection: GPUs, VRAM, host RAM, disk space, "
|
|
100
|
+
"tier classification, and per-card fitting LLM picks.",
|
|
101
|
+
{
|
|
102
|
+
"unified_memory_gib": _num_prop(
|
|
103
|
+
"Apple Silicon only: simulate a Mac with this many GiB of unified memory."
|
|
104
|
+
),
|
|
105
|
+
"facts_path": _str_prop("Optional path to saved host-facts JSON instead of probing."),
|
|
106
|
+
},
|
|
107
|
+
),
|
|
108
|
+
_tool_def(
|
|
109
|
+
"stack_memory",
|
|
110
|
+
"Read-only VRAM and host RAM footprint estimate for one LLM under "
|
|
111
|
+
"the stack's llama.cpp agent posture.",
|
|
112
|
+
{
|
|
113
|
+
"model": _str_prop(
|
|
114
|
+
"Catalog id, HF repo owner/name[:QUANT], or local GGUF/config path."
|
|
115
|
+
),
|
|
116
|
+
"quant": _str_prop("Optional catalog quantization variant or quant bits."),
|
|
117
|
+
"context": {
|
|
118
|
+
"type": ["integer", "string"],
|
|
119
|
+
"description": (
|
|
120
|
+
"Context length in tokens (integer) or comma-separated list "
|
|
121
|
+
"such as '64k,128k' or 'max'."
|
|
122
|
+
),
|
|
123
|
+
},
|
|
124
|
+
"slots": {
|
|
125
|
+
"type": "integer",
|
|
126
|
+
"minimum": 1,
|
|
127
|
+
"maximum": MAX_SLOTS_INPUT,
|
|
128
|
+
"description": "Concurrent request slots (-np); defaults to agent posture.",
|
|
129
|
+
},
|
|
130
|
+
"kv": _str_prop("KV cache types such as 'q8_0/q8_0', 'q8_0/q4_0', or 'f16'."),
|
|
131
|
+
"vram_gib": _num_prop("Discrete GPU VRAM budget in GiB."),
|
|
132
|
+
"ram_gib": _num_prop("Host system RAM in GiB beside a discrete GPU."),
|
|
133
|
+
"unified_gib": _num_prop(
|
|
134
|
+
"Apple Silicon unified memory in GiB (mutually exclusive with vram_gib and ram_gib)."
|
|
135
|
+
),
|
|
136
|
+
"vision": _enum_prop(
|
|
137
|
+
vision.READERS, "Image projector placement: auto, gpu, cpu, or off."
|
|
138
|
+
),
|
|
139
|
+
},
|
|
140
|
+
required=("model",),
|
|
141
|
+
),
|
|
142
|
+
_tool_def(
|
|
143
|
+
"stack_what_if",
|
|
144
|
+
"Read-only hardware upgrade comparison showing baseline LLM picks and "
|
|
145
|
+
"what additional RAM, VRAM, or unified memory unlocks.",
|
|
146
|
+
{
|
|
147
|
+
"vram_gib": _num_prop("Simulated discrete GPU VRAM in GiB."),
|
|
148
|
+
"ram_gib": _num_prop("Simulated host RAM in GiB."),
|
|
149
|
+
"unified_gib": _num_prop("Simulated Apple Silicon unified memory in GiB."),
|
|
150
|
+
"backend": _enum_prop(
|
|
151
|
+
("cuda", "metal"), "Target compute backend constraint ('cuda' or 'metal')."
|
|
152
|
+
),
|
|
153
|
+
"prefer": _enum_prop(
|
|
154
|
+
PREFERENCES, "Selection preference: smartest, concurrent, fast, or fastest."
|
|
155
|
+
),
|
|
156
|
+
"facts_path": _str_prop("Optional path to saved host-facts JSON instead of probing."),
|
|
157
|
+
},
|
|
158
|
+
),
|
|
159
|
+
_tool_def(
|
|
160
|
+
"stack_status",
|
|
161
|
+
"Read-only status of local stack deployments, owned manifest, latest "
|
|
162
|
+
"apply run, gateway wiring, and observed gateway speed.",
|
|
163
|
+
{},
|
|
164
|
+
),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
TOOL_SCHEMAS = {tool["name"]: tool["inputSchema"] for tool in TOOLS}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def add_parser(actions: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
|
|
171
|
+
"""Register ``stack mcp`` without interactive prompts or spinners."""
|
|
172
|
+
parser = actions.add_parser("mcp", help=SUMMARY)
|
|
173
|
+
cli_help.document(
|
|
174
|
+
parser,
|
|
175
|
+
DESCRIPTION,
|
|
176
|
+
examples=EXAMPLES,
|
|
177
|
+
sections=[
|
|
178
|
+
("output", "JSON-RPC 2.0 responses on stdout matching the request framing"),
|
|
179
|
+
("exit status", "0 clean EOF on stdin"),
|
|
180
|
+
],
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def cli(_args: argparse.Namespace) -> int:
|
|
185
|
+
"""CLI entrypoint for ``localmodels stack mcp``."""
|
|
186
|
+
return run_stdio()
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# ── schema & parameter validation ──────────────────────────────────────
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _is_finite_number(value: object) -> bool:
|
|
193
|
+
if isinstance(value, bool) or not isinstance(value, int | float):
|
|
194
|
+
return False
|
|
195
|
+
try:
|
|
196
|
+
return math.isfinite(float(value))
|
|
197
|
+
except OverflowError:
|
|
198
|
+
return False
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _check_type(name: str, value: object, expected: str | list[str]) -> None:
|
|
202
|
+
allowed = [expected] if isinstance(expected, str) else expected
|
|
203
|
+
checks: dict[str, Callable[[object], bool]] = {
|
|
204
|
+
"string": lambda v: isinstance(v, str),
|
|
205
|
+
"integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
|
|
206
|
+
"number": _is_finite_number,
|
|
207
|
+
}
|
|
208
|
+
if not any(checks[kind](value) for kind in allowed if kind in checks):
|
|
209
|
+
raise ValueError(f"argument {name!r} must be {' or '.join(allowed)}")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _validate_property(name: str, value: object, prop: Mapping[str, Any]) -> None:
|
|
213
|
+
if "type" in prop:
|
|
214
|
+
_check_type(name, value, prop["type"])
|
|
215
|
+
if isinstance(value, str) and "minLength" in prop:
|
|
216
|
+
if len(value) < int(prop["minLength"]) or not value.strip():
|
|
217
|
+
raise ValueError(f"argument {name!r} must be a non-empty string")
|
|
218
|
+
if isinstance(value, int | float) and not isinstance(value, bool):
|
|
219
|
+
if "minimum" in prop and value < prop["minimum"]:
|
|
220
|
+
raise ValueError(f"argument {name!r} must be >= {prop['minimum']}")
|
|
221
|
+
if "maximum" in prop and value > prop["maximum"]:
|
|
222
|
+
raise ValueError(f"argument {name!r} must be <= {prop['maximum']}")
|
|
223
|
+
if "exclusiveMinimum" in prop and value <= prop["exclusiveMinimum"]:
|
|
224
|
+
raise ValueError(f"argument {name!r} must be > {prop['exclusiveMinimum']}")
|
|
225
|
+
if "enum" in prop and value not in prop["enum"]:
|
|
226
|
+
allowed = ", ".join(str(v) for v in prop["enum"])
|
|
227
|
+
raise ValueError(f"argument {name!r} must be one of: {allowed}")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _validate_arguments(schema: Mapping[str, Any], arguments: object) -> dict[str, Any]:
|
|
231
|
+
if not isinstance(arguments, dict):
|
|
232
|
+
raise ValueError("tool arguments must be a JSON object")
|
|
233
|
+
props: Mapping[str, Any] = schema.get("properties", {})
|
|
234
|
+
for req in schema.get("required", ()):
|
|
235
|
+
if req not in arguments:
|
|
236
|
+
raise ValueError(f"missing required argument {req!r}")
|
|
237
|
+
if schema.get("additionalProperties") is False:
|
|
238
|
+
extra = sorted(k for k in arguments if k not in props)
|
|
239
|
+
if extra:
|
|
240
|
+
raise ValueError(f"unexpected argument(s): {', '.join(extra)}")
|
|
241
|
+
for key, value in arguments.items():
|
|
242
|
+
if key in props:
|
|
243
|
+
_validate_property(str(key), value, props[key])
|
|
244
|
+
return dict(arguments)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# ── read-only helpers ──────────────────────────────────────────────────
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _gib_bytes(value: object) -> int | None:
|
|
251
|
+
if value is None:
|
|
252
|
+
return None
|
|
253
|
+
if not _is_finite_number(value):
|
|
254
|
+
raise ValueError("memory size in GiB must be a finite number")
|
|
255
|
+
num = float(cast(int | float, value))
|
|
256
|
+
if not (0 < num <= MAX_MEMORY_GIB and num * GIB >= 1.0):
|
|
257
|
+
raise ValueError(f"memory size in GiB must be > 0 and <= {MAX_MEMORY_GIB}")
|
|
258
|
+
return int(round(num * GIB))
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _reject_json_constant(token: str) -> Any:
|
|
262
|
+
raise ValueError(f"Invalid JSON constant: {token}")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _read_regular_text(
|
|
266
|
+
path: Path, *, limit: int = MAX_FACTS_BYTES, label: str = "facts_path"
|
|
267
|
+
) -> str:
|
|
268
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0))
|
|
269
|
+
try:
|
|
270
|
+
st = os.fstat(fd)
|
|
271
|
+
if not stat.S_ISREG(st.st_mode):
|
|
272
|
+
raise ValueError(f"{label} must be a regular file: {path}")
|
|
273
|
+
if limit < 0:
|
|
274
|
+
return ""
|
|
275
|
+
if st.st_size > limit:
|
|
276
|
+
raise ValueError(f"{label} exceeds {limit} bytes: {path}")
|
|
277
|
+
chunks = bytearray()
|
|
278
|
+
while len(chunks) <= limit and (piece := os.read(fd, min(65536, limit + 1 - len(chunks)))):
|
|
279
|
+
chunks.extend(piece)
|
|
280
|
+
if len(chunks) > limit:
|
|
281
|
+
raise ValueError(f"{label} exceeds {limit} bytes: {path}")
|
|
282
|
+
finally:
|
|
283
|
+
os.close(fd)
|
|
284
|
+
return chunks.decode("utf-8")
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _require_regular(path: Path, label: str) -> None:
|
|
288
|
+
_read_regular_text(path, limit=-1, label=label)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _load_facts(facts_path: object) -> HostFacts:
|
|
292
|
+
if not isinstance(facts_path, str) or not facts_path.strip():
|
|
293
|
+
raise ValueError("facts_path must be a non-empty string")
|
|
294
|
+
path = Path(facts_path).expanduser()
|
|
295
|
+
raw = json.loads(_read_regular_text(path), parse_constant=_reject_json_constant)
|
|
296
|
+
json.dumps(raw, ensure_ascii=False).encode("utf-8")
|
|
297
|
+
return decode(raw, HostFacts)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _check_model_dir(directory: Path) -> None:
|
|
301
|
+
cfg = directory / "config.json"
|
|
302
|
+
if os.path.lexists(cfg):
|
|
303
|
+
_read_regular_text(cfg, label="config.json")
|
|
304
|
+
for ext in ("json", "safetensors", "gguf"):
|
|
305
|
+
for entry in sorted(directory.glob(f"*.{ext}")):
|
|
306
|
+
_require_regular(entry, ext)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _check_model_input(spec: str) -> None:
|
|
310
|
+
candidate = Path(spec).expanduser()
|
|
311
|
+
if not os.path.lexists(candidate):
|
|
312
|
+
return
|
|
313
|
+
if candidate.is_dir():
|
|
314
|
+
_check_model_dir(candidate)
|
|
315
|
+
return
|
|
316
|
+
if candidate.suffix.lower() == ".gguf":
|
|
317
|
+
_require_regular(candidate, "gguf")
|
|
318
|
+
for part in gguf.split_parts(candidate) or ():
|
|
319
|
+
if os.path.lexists(part):
|
|
320
|
+
_require_regular(part, "gguf")
|
|
321
|
+
return
|
|
322
|
+
_read_regular_text(candidate, label="model")
|
|
323
|
+
for entry in sorted(candidate.parent.glob("*.safetensors")):
|
|
324
|
+
_require_regular(entry, "safetensors")
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _kv_types(text: str) -> tuple[str, str]:
|
|
328
|
+
names = [part.strip().lower() for part in text.replace(",", "/").split("/")]
|
|
329
|
+
if len(names) == 1:
|
|
330
|
+
names *= 2
|
|
331
|
+
if len(names) != 2 or any(name not in KV_TYPES for name in names):
|
|
332
|
+
raise MemcalcError(f"kv {text!r}: use one of {', '.join(KV_TYPES)}, or K/V")
|
|
333
|
+
return names[0], names[1]
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _default_contexts(train: int) -> list[int]:
|
|
337
|
+
picked = [c for c in stack_memory.DEFAULT_CONTEXTS if not train or c <= train]
|
|
338
|
+
return picked or [train]
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _parse_context_list(text: str, train: int) -> list[int]:
|
|
342
|
+
out: list[int] = []
|
|
343
|
+
for item in (part.strip() for part in text.split(",")):
|
|
344
|
+
if not item:
|
|
345
|
+
continue
|
|
346
|
+
if item.lower() == "max":
|
|
347
|
+
if not train:
|
|
348
|
+
raise MemcalcError("context 'max': the model declares no training context")
|
|
349
|
+
out.append(train)
|
|
350
|
+
else:
|
|
351
|
+
out.append(parse_tokens(item))
|
|
352
|
+
if not out or any(c <= 0 or c > MAX_CONTEXT_TOKENS for c in out):
|
|
353
|
+
raise MemcalcError(f"context {text!r}: give lengths between 1 and {MAX_CONTEXT_TOKENS}")
|
|
354
|
+
return out
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _contexts(value: object, train: int) -> list[int]:
|
|
358
|
+
if value is None:
|
|
359
|
+
return _default_contexts(train)
|
|
360
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
361
|
+
if value <= 0 or value > MAX_CONTEXT_TOKENS:
|
|
362
|
+
raise MemcalcError(f"context must be between 1 and {MAX_CONTEXT_TOKENS}")
|
|
363
|
+
return [value]
|
|
364
|
+
if not isinstance(value, str):
|
|
365
|
+
raise MemcalcError("context must be an integer or comma-separated string")
|
|
366
|
+
text = value.strip()
|
|
367
|
+
return _parse_context_list(text, train) if text else _default_contexts(train)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
# ── four read-only tool handlers ───────────────────────────────────────
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _tool_hardware(args: dict[str, Any]) -> dict[str, Any]:
|
|
374
|
+
facts = _load_facts(args["facts_path"]) if "facts_path" in args else stack_whatif.read_host()
|
|
375
|
+
if "unified_memory_gib" in args:
|
|
376
|
+
assumed_bytes = _gib_bytes(args["unified_memory_gib"])
|
|
377
|
+
assert assumed_bytes is not None
|
|
378
|
+
facts = metal.assume(facts, assumed_bytes)
|
|
379
|
+
options = default_options()
|
|
380
|
+
return dict(stack_hardware.view(facts, options, agent_posture(options)))
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _tool_memory(args: dict[str, Any]) -> dict[str, Any]:
|
|
384
|
+
vram = _gib_bytes(args.get("vram_gib"))
|
|
385
|
+
ram = _gib_bytes(args.get("ram_gib"))
|
|
386
|
+
unified = _gib_bytes(args.get("unified_gib"))
|
|
387
|
+
if unified is not None and (vram is not None or ram is not None):
|
|
388
|
+
raise MemcalcError("unified_gib cannot be combined with vram_gib or ram_gib")
|
|
389
|
+
kv_raw = str(args.get("kv") or "q8_0/q8_0")
|
|
390
|
+
slots = int(args.get("slots", AGENT.slots))
|
|
391
|
+
if slots < 1:
|
|
392
|
+
raise MemcalcError("slots must be at least 1")
|
|
393
|
+
vision_mode = str(args.get("vision") or vision.DEFAULT)
|
|
394
|
+
endpoint = os.environ.get("HF_ENDPOINT", "https://huggingface.co")
|
|
395
|
+
model_spec = str(args["model"])
|
|
396
|
+
_check_model_input(model_spec)
|
|
397
|
+
subject = stack_memory.resolve(
|
|
398
|
+
model_spec,
|
|
399
|
+
quant=str(args["quant"]) if "quant" in args else None,
|
|
400
|
+
endpoint=endpoint,
|
|
401
|
+
)
|
|
402
|
+
posture = stack_memory.Posture(kv_types=_kv_types(kv_raw), slots=slots, vision=vision_mode)
|
|
403
|
+
machine = stack_memory.Machine(vram=vram, ram=ram, unified=unified)
|
|
404
|
+
contexts = _contexts(args.get("context"), subject.profile.n_ctx_train)
|
|
405
|
+
return stack_memory.report(subject, posture, machine, contexts)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _preferred_choice(facts: HostFacts, prefer: str) -> dict[str, Any] | None:
|
|
409
|
+
options = default_options()
|
|
410
|
+
options["prefer"] = prefer
|
|
411
|
+
options["offline"] = True
|
|
412
|
+
priced, _ = metal.pressured(metal.reclaimed(facts) if metal.supported(facts) else facts)
|
|
413
|
+
try:
|
|
414
|
+
parts, _ = choose_parts(
|
|
415
|
+
priced,
|
|
416
|
+
options,
|
|
417
|
+
resolver=deploy.catalog_pins,
|
|
418
|
+
listening=lambda _: False,
|
|
419
|
+
previous=lambda *_: None,
|
|
420
|
+
existing=lambda _: [],
|
|
421
|
+
owned_ram=lambda: 0,
|
|
422
|
+
)
|
|
423
|
+
ram_budget(parts)
|
|
424
|
+
except (StackError, PlanError):
|
|
425
|
+
return None
|
|
426
|
+
llm = parts["llm"]
|
|
427
|
+
launch = llm["launch"]
|
|
428
|
+
llm_id = llm["model"]["id"]
|
|
429
|
+
gpus = decode(llm["placement"].get("gpus") or [], list[dict[str, object]])
|
|
430
|
+
card = decode(gpus[0]["index"], int) if gpus else 0
|
|
431
|
+
entry = next((e for e in catalog.load_catalog_file() if e.id == llm_id), None)
|
|
432
|
+
recipe = next((r for r in suite.recipes("llm") if r["id"] == llm_id), None)
|
|
433
|
+
engine = entry.runtime if entry else recipe["runtime"] if recipe else "llama.cpp"
|
|
434
|
+
quality = entry.quality if entry else recipe["quality"]["score"] if recipe else 0
|
|
435
|
+
return {
|
|
436
|
+
"id": llm_id,
|
|
437
|
+
"quant": llm["model"]["quant"],
|
|
438
|
+
"quality": quality,
|
|
439
|
+
"role": prefer,
|
|
440
|
+
"card": card,
|
|
441
|
+
"engine": engine,
|
|
442
|
+
"context": int(str(launch["window"])),
|
|
443
|
+
"slots": int(str(launch.get("slots", 1))),
|
|
444
|
+
"kv_types": decode(launch.get("kv_types") or [], list[str]),
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _tool_what_if(args: dict[str, Any]) -> dict[str, Any]:
|
|
449
|
+
backend = args.get("backend")
|
|
450
|
+
vram = _gib_bytes(args.get("vram_gib"))
|
|
451
|
+
ram = _gib_bytes(args.get("ram_gib"))
|
|
452
|
+
unified = _gib_bytes(args.get("unified_gib"))
|
|
453
|
+
if backend == "metal" and (vram is not None or ram is not None):
|
|
454
|
+
raise StackError("backend 'metal' cannot be combined with vram_gib or ram_gib")
|
|
455
|
+
if backend == "cuda" and unified is not None:
|
|
456
|
+
raise StackError("backend 'cuda' cannot be combined with unified_gib")
|
|
457
|
+
facts = _load_facts(args["facts_path"]) if "facts_path" in args else None
|
|
458
|
+
machine = stack_memory.Machine(vram=vram, ram=ram, unified=unified)
|
|
459
|
+
seen = stack_whatif.starting_facts(machine, facts)
|
|
460
|
+
if backend == "metal" and not metal.supported(seen):
|
|
461
|
+
raise StackError("backend 'metal' requires Apple Silicon facts or unified_gib")
|
|
462
|
+
if backend == "cuda" and metal.supported(seen):
|
|
463
|
+
raise StackError("backend 'cuda' cannot be used with Apple Silicon facts")
|
|
464
|
+
typed_report = stack_whatif.report(seen)
|
|
465
|
+
report_doc: dict[str, Any] = copy.deepcopy(dict(typed_report))
|
|
466
|
+
if prefer := args.get("prefer"):
|
|
467
|
+
prefer_str = str(prefer)
|
|
468
|
+
report_doc["prefer"] = prefer_str
|
|
469
|
+
picked = typed_report["baseline"]["choices"].get(prefer_str)
|
|
470
|
+
report_doc["preferred"] = (
|
|
471
|
+
copy.deepcopy(picked) if picked is not None else _preferred_choice(seen, prefer_str)
|
|
472
|
+
)
|
|
473
|
+
return report_doc
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _tool_status(_args: dict[str, Any]) -> dict[str, Any]:
|
|
477
|
+
captured: list[str] = []
|
|
478
|
+
stack_lifecycle.status(out=captured.append, as_json=True)
|
|
479
|
+
if not captured:
|
|
480
|
+
raise StackError("stack status produced no JSON output")
|
|
481
|
+
loaded = json.loads(captured[0])
|
|
482
|
+
if not isinstance(loaded, dict):
|
|
483
|
+
raise StackError("stack status returned unexpected JSON shape")
|
|
484
|
+
return loaded
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
_HANDLERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
|
|
488
|
+
"stack_hardware": _tool_hardware,
|
|
489
|
+
"stack_memory": _tool_memory,
|
|
490
|
+
"stack_what_if": _tool_what_if,
|
|
491
|
+
"stack_status": _tool_status,
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
# ── JSON-RPC 2.0 & MCP dispatch ────────────────────────────────────────
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _rpc_ok(rid: object, result: dict[str, Any]) -> dict[str, Any]:
|
|
499
|
+
return {"jsonrpc": "2.0", "id": rid, "result": result}
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _rpc_err(rid: object, code: int, message: str) -> dict[str, Any]:
|
|
503
|
+
return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _valid_id(value: object) -> bool:
|
|
507
|
+
return (
|
|
508
|
+
value is None
|
|
509
|
+
or isinstance(value, str)
|
|
510
|
+
or (isinstance(value, int) and not isinstance(value, bool))
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _tool_error(message: str) -> dict[str, Any]:
|
|
515
|
+
return {"content": [{"type": "text", "text": message}], "isError": True}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _encode_reply(reply: object) -> bytes:
|
|
519
|
+
try:
|
|
520
|
+
return json.dumps(reply, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
521
|
+
except UnicodeEncodeError:
|
|
522
|
+
return json.dumps(reply, ensure_ascii=True, separators=(",", ":")).encode("utf-8")
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _dump_payload(payload: dict[str, Any]) -> str:
|
|
526
|
+
rendered = json.dumps(payload, ensure_ascii=False)
|
|
527
|
+
try:
|
|
528
|
+
rendered.encode("utf-8")
|
|
529
|
+
return rendered
|
|
530
|
+
except UnicodeEncodeError:
|
|
531
|
+
return json.dumps(payload, ensure_ascii=True)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _call_tool(name: str, arguments: object) -> dict[str, Any]:
|
|
535
|
+
schema = TOOL_SCHEMAS.get(name)
|
|
536
|
+
handler = _HANDLERS.get(name)
|
|
537
|
+
if schema is None or handler is None:
|
|
538
|
+
return _tool_error(f"Unknown tool: {name}")
|
|
539
|
+
try:
|
|
540
|
+
validated = _validate_arguments(schema, arguments)
|
|
541
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
|
542
|
+
payload = handler(validated)
|
|
543
|
+
rendered = _dump_payload(payload)
|
|
544
|
+
except BrokenPipeError:
|
|
545
|
+
raise
|
|
546
|
+
except Exception as exc:
|
|
547
|
+
return _tool_error(str(exc).strip() or type(exc).__name__)
|
|
548
|
+
return {
|
|
549
|
+
"content": [{"type": "text", "text": rendered}],
|
|
550
|
+
"structuredContent": payload,
|
|
551
|
+
"isError": False,
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _handle_request(method: str, rid: object, params: dict[str, Any]) -> dict[str, Any]:
|
|
556
|
+
if method == "initialize":
|
|
557
|
+
requested = params.get("protocolVersion")
|
|
558
|
+
if requested is not None and not isinstance(requested, str):
|
|
559
|
+
return _rpc_err(rid, -32602, "Invalid params: protocolVersion must be a string")
|
|
560
|
+
version = requested if requested in SUPPORTED_VERSIONS else DEFAULT_VERSION
|
|
561
|
+
return _rpc_ok(
|
|
562
|
+
rid,
|
|
563
|
+
{
|
|
564
|
+
"protocolVersion": version,
|
|
565
|
+
"capabilities": {"tools": {}},
|
|
566
|
+
"serverInfo": dict(SERVER_INFO),
|
|
567
|
+
},
|
|
568
|
+
)
|
|
569
|
+
if method == "ping":
|
|
570
|
+
return _rpc_ok(rid, {})
|
|
571
|
+
if method == "tools/list":
|
|
572
|
+
return _rpc_ok(rid, {"tools": [dict(tool) for tool in TOOLS]})
|
|
573
|
+
if method == "tools/call":
|
|
574
|
+
name = params.get("name")
|
|
575
|
+
if not isinstance(name, str) or not name.strip():
|
|
576
|
+
return _rpc_err(rid, -32602, "Invalid params: tool name must be a non-empty string")
|
|
577
|
+
arguments = params["arguments"] if "arguments" in params else {}
|
|
578
|
+
return _rpc_ok(rid, _call_tool(name, arguments))
|
|
579
|
+
return _rpc_err(rid, -32601, f"Method not found: {method}")
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def handle_message(message: object) -> dict[str, Any] | list[dict[str, Any]] | None:
|
|
583
|
+
"""Process one decoded JSON-RPC 2.0 message or batch; return None for notifications."""
|
|
584
|
+
if isinstance(message, list):
|
|
585
|
+
if not message:
|
|
586
|
+
return _rpc_err(None, -32600, "Invalid Request: empty batch")
|
|
587
|
+
replies = [r for item in message if isinstance((r := _handle_single(item)), dict)]
|
|
588
|
+
return replies or None
|
|
589
|
+
return _handle_single(message)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _handle_single(message: object) -> dict[str, Any] | None:
|
|
593
|
+
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
|
|
594
|
+
return _rpc_err(None, -32600, "Invalid Request")
|
|
595
|
+
has_id = "id" in message
|
|
596
|
+
raw_id = message.get("id")
|
|
597
|
+
rid = raw_id if _valid_id(raw_id) else None
|
|
598
|
+
method = message.get("method")
|
|
599
|
+
if "method" not in message and ("result" in message or "error" in message):
|
|
600
|
+
return None
|
|
601
|
+
if not isinstance(method, str) or not method:
|
|
602
|
+
return _rpc_err(rid, -32600, "Invalid Request")
|
|
603
|
+
if has_id and not _valid_id(raw_id):
|
|
604
|
+
return _rpc_err(None, -32600, "Invalid Request: invalid id")
|
|
605
|
+
if not has_id:
|
|
606
|
+
return None
|
|
607
|
+
raw_params = message.get("params")
|
|
608
|
+
if raw_params is not None and not isinstance(raw_params, dict):
|
|
609
|
+
return _rpc_err(rid, -32602, "Invalid params: params must be an object")
|
|
610
|
+
if method == "tools/call" and not isinstance(raw_params, dict):
|
|
611
|
+
return _rpc_err(rid, -32602, "Invalid params: tools/call requires a params object")
|
|
612
|
+
return _handle_request(method, rid, cast(dict[str, Any], raw_params or {}))
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
# ── stdio framing loop ─────────────────────────────────────────────────
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def _binary_reader(stdin: BinaryIO | TextIO | None) -> BinaryIO:
|
|
619
|
+
stream = sys.stdin if stdin is None else stdin
|
|
620
|
+
buf = getattr(stream, "buffer", None)
|
|
621
|
+
if buf is not None:
|
|
622
|
+
return cast(BinaryIO, buf)
|
|
623
|
+
if isinstance(stream, io.TextIOBase):
|
|
624
|
+
return io.BytesIO(stream.read().encode("utf-8"))
|
|
625
|
+
return cast(BinaryIO, stream)
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _write_frame(stdout: BinaryIO | TextIO, data: bytes, *, framed: bool) -> None:
|
|
629
|
+
raw = f"Content-Length: {len(data)}\r\n\r\n".encode("ascii") + data if framed else data + b"\n"
|
|
630
|
+
buf = getattr(stdout, "buffer", None)
|
|
631
|
+
target: Any = buf if buf is not None else stdout
|
|
632
|
+
target.write(raw.decode("utf-8") if buf is None and isinstance(stdout, io.TextIOBase) else raw)
|
|
633
|
+
target.flush()
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def _parse_content_length(headers: list[bytes]) -> int | None:
|
|
637
|
+
lengths: list[int] = []
|
|
638
|
+
for header in headers:
|
|
639
|
+
name, sep, value = header.decode("latin-1").partition(":")
|
|
640
|
+
if not sep:
|
|
641
|
+
return None
|
|
642
|
+
if name.strip().lower() == "content-length":
|
|
643
|
+
digits = value.strip()
|
|
644
|
+
if not digits or not digits.isascii() or not digits.isdigit() or len(digits) > 10:
|
|
645
|
+
return None
|
|
646
|
+
if (length := int(digits)) > MAX_FRAME_BYTES:
|
|
647
|
+
return None
|
|
648
|
+
lengths.append(length)
|
|
649
|
+
return lengths[0] if len(lengths) == 1 else None
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def _drain_line(reader: BinaryIO) -> None:
|
|
653
|
+
while True:
|
|
654
|
+
chunk = reader.readline(8192)
|
|
655
|
+
if not chunk or chunk.endswith(b"\n"):
|
|
656
|
+
return
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _drain_headers(reader: BinaryIO) -> None:
|
|
660
|
+
while nxt := reader.readline(8192):
|
|
661
|
+
if not nxt.endswith(b"\n"):
|
|
662
|
+
_drain_line(reader)
|
|
663
|
+
elif not nxt.strip():
|
|
664
|
+
return
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _read_framed_body(reader: BinaryIO, first_line: bytes) -> tuple[bytes, bool, str | None]:
|
|
668
|
+
headers = [first_line]
|
|
669
|
+
while True:
|
|
670
|
+
nxt = reader.readline(8192)
|
|
671
|
+
if not nxt or not nxt.strip():
|
|
672
|
+
break
|
|
673
|
+
if not nxt.endswith(b"\n") or len(headers) >= MAX_HEADER_LINES:
|
|
674
|
+
if not nxt.endswith(b"\n"):
|
|
675
|
+
_drain_line(reader)
|
|
676
|
+
_drain_headers(reader)
|
|
677
|
+
return b"", True, "Invalid Content-Length header"
|
|
678
|
+
headers.append(nxt)
|
|
679
|
+
length = _parse_content_length(headers)
|
|
680
|
+
if length is None:
|
|
681
|
+
return b"", True, "Invalid Content-Length header"
|
|
682
|
+
chunks = bytearray()
|
|
683
|
+
while len(chunks) < length:
|
|
684
|
+
piece = reader.read(length - len(chunks))
|
|
685
|
+
if not piece:
|
|
686
|
+
return bytes(chunks), True, "Truncated Content-Length body"
|
|
687
|
+
chunks.extend(piece)
|
|
688
|
+
return bytes(chunks), True, None
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _read_frame(reader: BinaryIO) -> tuple[bytes | None, bool, str | None]:
|
|
692
|
+
while True:
|
|
693
|
+
line = reader.readline(MAX_FRAME_BYTES + 1)
|
|
694
|
+
if not line:
|
|
695
|
+
return None, False, None
|
|
696
|
+
if len(line) > MAX_FRAME_BYTES and not line.endswith(b"\n"):
|
|
697
|
+
_drain_line(reader)
|
|
698
|
+
return b"", False, "Message exceeds maximum frame size"
|
|
699
|
+
if line.strip():
|
|
700
|
+
break
|
|
701
|
+
lower = line.lstrip().lower()
|
|
702
|
+
if lower.startswith((b"content-length:", b"content-type:")):
|
|
703
|
+
return _read_framed_body(reader, line)
|
|
704
|
+
return line.rstrip(b"\r\n"), False, None
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def run_stdio(
|
|
708
|
+
stdin: BinaryIO | TextIO | None = None,
|
|
709
|
+
stdout: BinaryIO | TextIO | None = None,
|
|
710
|
+
) -> int:
|
|
711
|
+
"""Serve read-only MCP requests on stdio until EOF."""
|
|
712
|
+
reader = _binary_reader(stdin)
|
|
713
|
+
writer: BinaryIO | TextIO = sys.stdout if stdout is None else stdout
|
|
714
|
+
while True:
|
|
715
|
+
raw, framed, framing_error = _read_frame(reader)
|
|
716
|
+
if raw is None:
|
|
717
|
+
return 0
|
|
718
|
+
if framing_error is not None:
|
|
719
|
+
reply: object = _rpc_err(None, -32700, f"Parse error: {framing_error}")
|
|
720
|
+
else:
|
|
721
|
+
try:
|
|
722
|
+
decoded = json.loads(raw.decode("utf-8"), parse_constant=_reject_json_constant)
|
|
723
|
+
json.dumps(decoded, ensure_ascii=False).encode("utf-8")
|
|
724
|
+
except (UnicodeDecodeError, ValueError, RecursionError):
|
|
725
|
+
reply = _rpc_err(None, -32700, "Parse error")
|
|
726
|
+
else:
|
|
727
|
+
reply = handle_message(decoded)
|
|
728
|
+
if reply is not None:
|
|
729
|
+
_write_frame(writer, _encode_reply(reply), framed=framed)
|