nimblebrain-server-sdk 0.3.0__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.
- nimblebrain_server_sdk/__init__.py +92 -0
- nimblebrain_server_sdk/annotations.py +22 -0
- nimblebrain_server_sdk/announce.py +46 -0
- nimblebrain_server_sdk/errors.py +38 -0
- nimblebrain_server_sdk/extensions/__init__.py +5 -0
- nimblebrain_server_sdk/extensions/facets.py +61 -0
- nimblebrain_server_sdk/extensions/lifecycle.py +141 -0
- nimblebrain_server_sdk/extensions/platform.py +47 -0
- nimblebrain_server_sdk/extensions/views.py +33 -0
- nimblebrain_server_sdk/host.py +294 -0
- nimblebrain_server_sdk/ids.py +104 -0
- nimblebrain_server_sdk/methods.py +33 -0
- nimblebrain_server_sdk/rows.py +61 -0
- nimblebrain_server_sdk/skills.py +521 -0
- nimblebrain_server_sdk/testing.py +142 -0
- nimblebrain_server_sdk-0.3.0.dist-info/METADATA +442 -0
- nimblebrain_server_sdk-0.3.0.dist-info/RECORD +19 -0
- nimblebrain_server_sdk-0.3.0.dist-info/WHEEL +4 -0
- nimblebrain_server_sdk-0.3.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Bundle-side wrapper for the `ai.nimblebrain/host-resources` extension.
|
|
2
|
+
|
|
3
|
+
The platform's TS implementation lives in
|
|
4
|
+
`src/host-resources/` in the NimbleBrain platform repo. This module
|
|
5
|
+
mirrors the wire shape exactly: same method names, same parameter
|
|
6
|
+
shapes, same result types (reused from `mcp.types`).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import builtins
|
|
12
|
+
from typing import Any, Literal, cast
|
|
13
|
+
|
|
14
|
+
from fastmcp import Context
|
|
15
|
+
from mcp.types import (
|
|
16
|
+
ClientCapabilities,
|
|
17
|
+
ListResourcesResult,
|
|
18
|
+
ReadResourceResult,
|
|
19
|
+
ServerRequest,
|
|
20
|
+
)
|
|
21
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
22
|
+
|
|
23
|
+
from nimblebrain_server_sdk.errors import HostCapabilityMissing
|
|
24
|
+
from nimblebrain_server_sdk.methods import (
|
|
25
|
+
HOST_RESOURCES_CAPABILITY_KEY,
|
|
26
|
+
HOST_RESOURCES_LIST_METHOD,
|
|
27
|
+
HOST_RESOURCES_READ_METHOD,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
# Request types
|
|
32
|
+
# ---------------------------------------------------------------------------
|
|
33
|
+
#
|
|
34
|
+
# `ServerSession.send_request` is typed against `ServerRequest`, a closed
|
|
35
|
+
# Pydantic `RootModel` union of the spec's known server→client request
|
|
36
|
+
# types. Custom methods like `ai.nimblebrain/resources/*` aren't in that
|
|
37
|
+
# union, so static typing won't accept us passing them directly.
|
|
38
|
+
#
|
|
39
|
+
# At runtime, `ServerSession.send_request` dumps the request
|
|
40
|
+
# (`model_dump(by_alias=True, mode="json", exclude_none=True)`) and
|
|
41
|
+
# forwards `method` and `params` onto the JSON-RPC stream raw; its
|
|
42
|
+
# result validation is wrapped in `except KeyError`, which is what an
|
|
43
|
+
# unregistered custom method hits. Any Pydantic model with the right
|
|
44
|
+
# wire shape works, so the request types below are plain `BaseModel`
|
|
45
|
+
# subclasses `cast` to `ServerRequest` at the call site.
|
|
46
|
+
#
|
|
47
|
+
# # Runtime contract dependency
|
|
48
|
+
#
|
|
49
|
+
# The `cast` is a static-type accommodation, but it *relies on* that
|
|
50
|
+
# dump-and-forward behaviour, which mcp's public surface does not
|
|
51
|
+
# guarantee. If the SDK ever validates inputs against the
|
|
52
|
+
# `ServerRequest` RootModel (or builds typed envelopes internally), the
|
|
53
|
+
# cast breaks at runtime rather than at import — neither the type
|
|
54
|
+
# checker nor an import smoke test would catch it. That is what the
|
|
55
|
+
# narrow `mcp` pin in `pyproject.toml` bounds; the rationale lives
|
|
56
|
+
# there.
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _HostResourcesReadParams(BaseModel):
|
|
60
|
+
uri: str
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _HostResourcesReadRequest(BaseModel):
|
|
64
|
+
method: Literal["ai.nimblebrain/resources/read"] = HOST_RESOURCES_READ_METHOD # type: ignore[assignment]
|
|
65
|
+
params: _HostResourcesReadParams
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _HostResourcesListFilter(BaseModel):
|
|
69
|
+
scheme: str | None = None
|
|
70
|
+
mime_type: str | None = None
|
|
71
|
+
tags: list[str] | None = None
|
|
72
|
+
|
|
73
|
+
def to_wire(self) -> dict[str, Any]:
|
|
74
|
+
"""Hand-serialize to the camelCase wire shape.
|
|
75
|
+
|
|
76
|
+
Pydantic aliasing (`Field(alias="mimeType")` + `populate_by_name`)
|
|
77
|
+
is the more idiomatic way to do this, but it would only matter
|
|
78
|
+
if callers were constructing this model directly. They aren't —
|
|
79
|
+
`_HostResourcesListFilter` is internal and `HostResources.list()`
|
|
80
|
+
builds it from kwargs, so the explicit dict-build is simpler
|
|
81
|
+
than wiring + documenting an alias roundtrip.
|
|
82
|
+
"""
|
|
83
|
+
out: dict[str, Any] = {}
|
|
84
|
+
if self.scheme is not None:
|
|
85
|
+
out["scheme"] = self.scheme
|
|
86
|
+
if self.mime_type is not None:
|
|
87
|
+
out["mimeType"] = self.mime_type
|
|
88
|
+
if self.tags is not None:
|
|
89
|
+
out["tags"] = self.tags
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class _HostResourcesListMeta(BaseModel):
|
|
94
|
+
filter: dict[str, Any] | None = None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class _HostResourcesListParams(BaseModel):
|
|
98
|
+
# Wire convention: the filter rides in `_meta.filter` because the spec
|
|
99
|
+
# `ListResourcesRequest` doesn't have a top-level `filter` field. The
|
|
100
|
+
# platform's handler unwraps from there. Pydantic forbids attribute
|
|
101
|
+
# names with a leading underscore (treated as private), so we name
|
|
102
|
+
# the field `meta` in Python and alias it to `_meta` on the wire.
|
|
103
|
+
# `populate_by_name=True` keeps both forms accepted at construction.
|
|
104
|
+
meta: _HostResourcesListMeta | None = Field(default=None, alias="_meta")
|
|
105
|
+
|
|
106
|
+
model_config = ConfigDict(populate_by_name=True)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class _HostResourcesListRequest(BaseModel):
|
|
110
|
+
method: Literal["ai.nimblebrain/resources/list"] = HOST_RESOURCES_LIST_METHOD # type: ignore[assignment]
|
|
111
|
+
params: _HostResourcesListParams
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
# HostResources — the bundle-facing API
|
|
116
|
+
# ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class HostResources:
|
|
120
|
+
"""Bundle-side handle for the host-resources extension.
|
|
121
|
+
|
|
122
|
+
Construct via the `host(ctx)` factory rather than directly — the
|
|
123
|
+
factory keeps the call site uniform across the SDK.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
def __init__(self, ctx: Context):
|
|
127
|
+
self._ctx = ctx
|
|
128
|
+
|
|
129
|
+
# -- Capability probes --------------------------------------------------
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def available(self) -> bool:
|
|
133
|
+
"""True when the host advertised host-resources with **read** enabled.
|
|
134
|
+
|
|
135
|
+
This is the common-case probe for `read()`. For `list()`, use
|
|
136
|
+
`list_available` instead — a host could advertise `list.enabled`
|
|
137
|
+
without `read.enabled` (or vice versa), and gating both methods
|
|
138
|
+
on a single flag would silently mis-route.
|
|
139
|
+
|
|
140
|
+
Reads from `ClientCapabilities.extensions["ai.nimblebrain/host-resources"]`,
|
|
141
|
+
falling back to the legacy `experimental` slot for hosts that
|
|
142
|
+
haven't migrated to the spec-blessed `extensions` field yet.
|
|
143
|
+
Returns False on any malformed shape so a buggy host can't
|
|
144
|
+
crash a bundle's availability probe.
|
|
145
|
+
"""
|
|
146
|
+
return self._method_enabled("read")
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def list_available(self) -> bool:
|
|
150
|
+
"""True when the host advertised host-resources with **list** enabled.
|
|
151
|
+
|
|
152
|
+
v1 hosts always ship `read` and `list` enabled together, so this
|
|
153
|
+
will move in lockstep with `available` in practice. The split
|
|
154
|
+
exists because the capability shape allows independent flags and
|
|
155
|
+
the SDK shouldn't bake the lockstep assumption in — a future host
|
|
156
|
+
that disables one method (e.g. read-only inventory listing) gets
|
|
157
|
+
correct behaviour for free.
|
|
158
|
+
"""
|
|
159
|
+
return self._method_enabled("list")
|
|
160
|
+
|
|
161
|
+
def _method_enabled(self, method: str) -> bool:
|
|
162
|
+
"""Per-method capability gate. Shared by `available` /
|
|
163
|
+
`list_available` and the per-call guards in `read` / `list`."""
|
|
164
|
+
cap = self._capability_block()
|
|
165
|
+
if cap is None:
|
|
166
|
+
return False
|
|
167
|
+
block = cap.get(method)
|
|
168
|
+
if not isinstance(block, dict):
|
|
169
|
+
return False
|
|
170
|
+
return bool(block.get("enabled"))
|
|
171
|
+
|
|
172
|
+
def supports_scheme(self, scheme: str) -> bool:
|
|
173
|
+
"""True when the host advertised the given URI scheme.
|
|
174
|
+
|
|
175
|
+
The host-resources capability includes a `schemes` allowlist
|
|
176
|
+
(`["files"]` in v1). Bundles check this before issuing a read
|
|
177
|
+
against an `entities://` URI etc., since the platform will
|
|
178
|
+
return `-32602 Invalid params` for any scheme outside the
|
|
179
|
+
allowlist.
|
|
180
|
+
"""
|
|
181
|
+
cap = self._capability_block()
|
|
182
|
+
if cap is None:
|
|
183
|
+
return False
|
|
184
|
+
schemes = cap.get("schemes")
|
|
185
|
+
return isinstance(schemes, list) and scheme in schemes
|
|
186
|
+
|
|
187
|
+
# -- Methods ------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
async def read(self, uri: str) -> ReadResourceResult:
|
|
190
|
+
"""Read a single workspace resource by URI.
|
|
191
|
+
|
|
192
|
+
Raises `HostCapabilityMissing` if the host hasn't advertised the
|
|
193
|
+
extension with `read.enabled` — check `available` first, or
|
|
194
|
+
catch and fall back to a structured tool error (the Level-C
|
|
195
|
+
pattern).
|
|
196
|
+
|
|
197
|
+
Raises `McpError` for wire-level errors:
|
|
198
|
+
- `-32002 Resource not found` (also: cross-workspace lookup)
|
|
199
|
+
- `-32004 Rate limited` (with `retryAfterMs` in `error.data`)
|
|
200
|
+
- `-32005 Response too large` (with `size`, `maxSize`)
|
|
201
|
+
- `-32602 Invalid params` (unsupported scheme)
|
|
202
|
+
"""
|
|
203
|
+
if not self._method_enabled("read"):
|
|
204
|
+
raise HostCapabilityMissing(HOST_RESOURCES_CAPABILITY_KEY)
|
|
205
|
+
|
|
206
|
+
request = _HostResourcesReadRequest(params=_HostResourcesReadParams(uri=uri))
|
|
207
|
+
return await self._ctx.session.send_request(
|
|
208
|
+
cast(ServerRequest, request),
|
|
209
|
+
ReadResourceResult,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
async def list(
|
|
213
|
+
self,
|
|
214
|
+
*,
|
|
215
|
+
scheme: str | None = None,
|
|
216
|
+
mime_type: str | None = None,
|
|
217
|
+
tags: builtins.list[str] | None = None,
|
|
218
|
+
) -> ListResourcesResult:
|
|
219
|
+
"""List workspace resources, optionally filtered.
|
|
220
|
+
|
|
221
|
+
Filters are AND-combined (resources must match every constraint).
|
|
222
|
+
Pagination via `cursor` is not supported in v1 — the platform
|
|
223
|
+
returns the full set in one response and rejects non-empty
|
|
224
|
+
cursors with `-32602`.
|
|
225
|
+
|
|
226
|
+
Raises `HostCapabilityMissing` if the host hasn't advertised
|
|
227
|
+
the extension with `list.enabled` — check `list_available`
|
|
228
|
+
before calling, or catch and fall back. Wire errors propagate as
|
|
229
|
+
`McpError` (see `read`).
|
|
230
|
+
"""
|
|
231
|
+
if not self._method_enabled("list"):
|
|
232
|
+
raise HostCapabilityMissing(HOST_RESOURCES_CAPABILITY_KEY)
|
|
233
|
+
|
|
234
|
+
filter_obj = _HostResourcesListFilter(scheme=scheme, mime_type=mime_type, tags=tags)
|
|
235
|
+
filter_wire = filter_obj.to_wire()
|
|
236
|
+
# Drop `meta` entirely when there's no filter so the wire-side
|
|
237
|
+
# `params` is empty (matches "list everything in this workspace"
|
|
238
|
+
# without ambiguity). `exclude_none=True` on `model_dump` handles
|
|
239
|
+
# the drop.
|
|
240
|
+
meta = _HostResourcesListMeta(filter=filter_wire) if filter_wire else None
|
|
241
|
+
params = _HostResourcesListParams(meta=meta)
|
|
242
|
+
request = _HostResourcesListRequest(params=params)
|
|
243
|
+
return await self._ctx.session.send_request(
|
|
244
|
+
cast(ServerRequest, request),
|
|
245
|
+
ListResourcesResult,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
# -- Internals ----------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
def _capability_block(self) -> dict[str, Any] | None:
|
|
251
|
+
"""Return the raw capability dict, or None if not advertised.
|
|
252
|
+
|
|
253
|
+
Probes `ClientCapabilities.extensions` first (the spec-blessed
|
|
254
|
+
location), then `experimental` (the legacy slot some hosts
|
|
255
|
+
still advertise in). Both are typed fields on `mcp`'s
|
|
256
|
+
`ClientCapabilities`. Any malformed shape reads as "not
|
|
257
|
+
advertised" so a buggy host can't crash the probe.
|
|
258
|
+
"""
|
|
259
|
+
client_params = getattr(self._ctx.session, "client_params", None)
|
|
260
|
+
if client_params is None:
|
|
261
|
+
return None
|
|
262
|
+
caps = getattr(client_params, "capabilities", None)
|
|
263
|
+
if not isinstance(caps, ClientCapabilities):
|
|
264
|
+
return None
|
|
265
|
+
|
|
266
|
+
# Prefer `extensions`, the spec-blessed slot.
|
|
267
|
+
extensions = caps.extensions
|
|
268
|
+
if isinstance(extensions, dict):
|
|
269
|
+
cap = extensions.get(HOST_RESOURCES_CAPABILITY_KEY)
|
|
270
|
+
if isinstance(cap, dict):
|
|
271
|
+
return cap
|
|
272
|
+
|
|
273
|
+
# Fall back to the legacy `experimental` slot — older platforms
|
|
274
|
+
# (or older spec versions) put vendor extensions there.
|
|
275
|
+
experimental = caps.experimental
|
|
276
|
+
if isinstance(experimental, dict):
|
|
277
|
+
cap = experimental.get(HOST_RESOURCES_CAPABILITY_KEY)
|
|
278
|
+
if isinstance(cap, dict):
|
|
279
|
+
return cap
|
|
280
|
+
|
|
281
|
+
return None
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def host(ctx: Context) -> HostResources:
|
|
285
|
+
"""Bundle-facing entry point. Wraps a FastMCP `Context` into a typed
|
|
286
|
+
handle for the host-resources extension.
|
|
287
|
+
|
|
288
|
+
Idiomatic usage:
|
|
289
|
+
|
|
290
|
+
h = host(ctx)
|
|
291
|
+
if h.available:
|
|
292
|
+
result = await h.read("files://fl_abc123")
|
|
293
|
+
"""
|
|
294
|
+
return HostResources(ctx)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""The opaque record id a server mints: ``<prefix>_<ulid>``.
|
|
2
|
+
|
|
3
|
+
A record id is a public contract, so it is
|
|
4
|
+
|
|
5
|
+
* **Opaque.** No sequence number or row id: the body is a ULID, a millisecond timestamp
|
|
6
|
+
in its high bits and randomness in its low bits, so it reveals neither row counts nor
|
|
7
|
+
another tenant's ordering.
|
|
8
|
+
* **Never recycled.** Every mint is a fresh ULID, so a stale reference never resolves to
|
|
9
|
+
a different record.
|
|
10
|
+
* **Sortable.** The leading 48 bits are the mint time, so a later id sorts lexically after
|
|
11
|
+
an earlier one. That is an ordering convenience, not a uniqueness guarantee: uniqueness
|
|
12
|
+
comes from the 80 random bits and the table's primary key.
|
|
13
|
+
|
|
14
|
+
A ULID here is 26 characters of Crockford base32 (``0-9`` and ``A-Z`` without ``I L O U``),
|
|
15
|
+
minted from ``time`` and ``os.urandom`` with no third-party dependency. Within one
|
|
16
|
+
millisecond the random part is incremented rather than redrawn, and a clock that steps
|
|
17
|
+
backwards holds at the last millisecond, so ids minted in a tight loop, from any thread,
|
|
18
|
+
keep strictly increasing. One lock guards that state for the whole process.
|
|
19
|
+
|
|
20
|
+
A server keeps its own prefixes and builds its named minters on :func:`new_prefixed_id`::
|
|
21
|
+
|
|
22
|
+
THING_PREFIX = "th"
|
|
23
|
+
|
|
24
|
+
def new_thing_id() -> str:
|
|
25
|
+
return new_prefixed_id(THING_PREFIX)
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import os
|
|
31
|
+
import threading
|
|
32
|
+
import time
|
|
33
|
+
from collections.abc import Callable
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"CROCKFORD_ALPHABET",
|
|
37
|
+
"ULID_LENGTH",
|
|
38
|
+
"new_prefixed_id",
|
|
39
|
+
"new_ulid",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
|
43
|
+
"""The ULID alphabet, in ascending ASCII order, so string order is numeric order."""
|
|
44
|
+
|
|
45
|
+
ULID_LENGTH = 26
|
|
46
|
+
"""Characters in a ULID: 10 of timestamp and 16 of randomness, 5 bits each."""
|
|
47
|
+
|
|
48
|
+
_TIME_BITS = 48
|
|
49
|
+
_TIME_MAX = (1 << _TIME_BITS) - 1
|
|
50
|
+
_RANDOM_BITS = 80
|
|
51
|
+
_RANDOM_MAX = (1 << _RANDOM_BITS) - 1
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _encode(value: int, length: int) -> str:
|
|
55
|
+
"""``value`` as a fixed-``length`` Crockford base32 string, most significant first."""
|
|
56
|
+
chars = ["0"] * length
|
|
57
|
+
for i in range(length - 1, -1, -1):
|
|
58
|
+
chars[i] = CROCKFORD_ALPHABET[value & 0x1F]
|
|
59
|
+
value >>= 5
|
|
60
|
+
return "".join(chars)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _draw() -> int:
|
|
64
|
+
return int.from_bytes(os.urandom(_RANDOM_BITS // 8), "big")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _Minter:
|
|
68
|
+
"""Monotonic ULID state behind one lock. The clock is a parameter so tests can hold it."""
|
|
69
|
+
|
|
70
|
+
def __init__(self, clock: Callable[[], float] = time.time) -> None:
|
|
71
|
+
self._clock = clock
|
|
72
|
+
self._lock = threading.Lock()
|
|
73
|
+
self._last_ms = -1
|
|
74
|
+
self._last_random = 0
|
|
75
|
+
|
|
76
|
+
def mint(self) -> str:
|
|
77
|
+
with self._lock:
|
|
78
|
+
now_ms = max(int(self._clock() * 1000), self._last_ms)
|
|
79
|
+
if now_ms == self._last_ms:
|
|
80
|
+
# The same millisecond, or a clock that stepped back: increment, never redraw,
|
|
81
|
+
# so the id still sorts after the last one. An 80-bit overflow spills into the
|
|
82
|
+
# next millisecond.
|
|
83
|
+
candidate = self._last_random + 1
|
|
84
|
+
if candidate > _RANDOM_MAX:
|
|
85
|
+
now_ms += 1
|
|
86
|
+
candidate = _draw()
|
|
87
|
+
else:
|
|
88
|
+
candidate = _draw()
|
|
89
|
+
self._last_ms = now_ms
|
|
90
|
+
self._last_random = candidate
|
|
91
|
+
return _encode(now_ms & _TIME_MAX, 10) + _encode(candidate & _RANDOM_MAX, 16)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_MINTER = _Minter()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def new_ulid() -> str:
|
|
98
|
+
"""One fresh ULID, strictly greater than every ULID minted before it in this process."""
|
|
99
|
+
return _MINTER.mint()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def new_prefixed_id(prefix: str) -> str:
|
|
103
|
+
"""``<prefix>_<ulid>``: an opaque record id whose prefix names the record's kind."""
|
|
104
|
+
return f"{prefix}_{new_ulid()}"
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Constants for the `ai.nimblebrain/host-resources` extension.
|
|
2
|
+
|
|
3
|
+
Mirrors `src/host-resources/methods.ts` and the JSON-RPC error codes in
|
|
4
|
+
`src/host-resources/resolver.ts` and `src/host-resources/rate-limit.ts`
|
|
5
|
+
in the platform repo. Pinning the values in code so bundle authors
|
|
6
|
+
matching on `McpError.error.code` don't carry magic numbers.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
HOST_RESOURCES_CAPABILITY_KEY = "ai.nimblebrain/host-resources"
|
|
10
|
+
|
|
11
|
+
HOST_RESOURCES_READ_METHOD = "ai.nimblebrain/resources/read"
|
|
12
|
+
HOST_RESOURCES_LIST_METHOD = "ai.nimblebrain/resources/list"
|
|
13
|
+
|
|
14
|
+
# MCP-spec convention for "resource not found" responses to
|
|
15
|
+
# `resources/read`. The platform deliberately surfaces the same code
|
|
16
|
+
# from `ai.nimblebrain/resources/read` so a future upstream migration
|
|
17
|
+
# is a method-name rename, not an error-code rewrite.
|
|
18
|
+
#
|
|
19
|
+
# Note: cross-workspace lookups collapse to this code too — the
|
|
20
|
+
# platform never confirms that an ID exists in a different workspace.
|
|
21
|
+
# So "not found" on the wire means either genuinely-not-found OR
|
|
22
|
+
# not-in-this-workspace; the bundle has no way to tell, by design.
|
|
23
|
+
RESOURCE_NOT_FOUND = -32002
|
|
24
|
+
|
|
25
|
+
# JSON-RPC "Invalid params." Unsupported URI scheme, malformed tags
|
|
26
|
+
# filter (non-array shape), and pagination cursors all map here.
|
|
27
|
+
INVALID_PARAMS = -32602
|
|
28
|
+
|
|
29
|
+
# Impl-defined server-error range, used for deliberate quota responses
|
|
30
|
+
# (NOT `-32603 InternalError`, which would mis-signal a quota response
|
|
31
|
+
# as a server fault).
|
|
32
|
+
RATE_LIMITED = -32004
|
|
33
|
+
RESPONSE_TOO_LARGE = -32005
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""The row a listing or a search returns: the record, bounded, with its address.
|
|
2
|
+
|
|
3
|
+
A page holds up to a few hundred rows, so one unbounded text field (a document's body, a
|
|
4
|
+
note's text, a ticket's description) multiplies into a page no agent context can hold. A row carries
|
|
5
|
+
such a field as a fixed-length preview or not at all, and its ``uri`` is the address the
|
|
6
|
+
whole record is read from. A server builds each row with :func:`listing_row`::
|
|
7
|
+
|
|
8
|
+
rows = [listing_row(dump(r), omit=("body",)) for r in page.rows]
|
|
9
|
+
rows = [listing_row(row, preview={"content": PREVIEW_CHARS}) for row in rows]
|
|
10
|
+
|
|
11
|
+
``nimblebrain_server_sdk.testing.assert_bounded_rows`` checks a page the way this module shapes it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Iterable, Mapping
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
PREVIEW_CHARS = 200
|
|
20
|
+
"""A preview's default length in characters: enough to recognise a record, not to read it."""
|
|
21
|
+
|
|
22
|
+
ELLIPSIS = "…"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def preview_text(text: str, chars: int = PREVIEW_CHARS) -> str:
|
|
26
|
+
"""``text`` cut to at most ``chars`` characters, ending in ``…`` when anything was cut."""
|
|
27
|
+
if chars < 1:
|
|
28
|
+
raise ValueError(f"a preview holds at least one character, not {chars!r}")
|
|
29
|
+
if len(text) <= chars:
|
|
30
|
+
return text
|
|
31
|
+
return text[: chars - 1].rstrip() + ELLIPSIS
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def listing_row(
|
|
35
|
+
record: Mapping[str, Any],
|
|
36
|
+
*,
|
|
37
|
+
omit: Iterable[str] = (),
|
|
38
|
+
preview: Mapping[str, int] | None = None,
|
|
39
|
+
) -> dict[str, Any]:
|
|
40
|
+
"""``record`` as a listing row: each ``omit`` field dropped, each ``preview`` field cut.
|
|
41
|
+
|
|
42
|
+
A previewed field ``f`` leaves the row and comes back as ``f_preview``, at most
|
|
43
|
+
``preview[f]`` characters (:func:`preview_text`), so a reader never mistakes a preview
|
|
44
|
+
for the field itself. A ``None`` value stays ``None``. A field the record lacks is
|
|
45
|
+
skipped, so one call serves records that carry it and records that do not. Every other
|
|
46
|
+
key, ``uri`` included, is copied unchanged; the record itself is not modified.
|
|
47
|
+
|
|
48
|
+
Raises :class:`TypeError` for a previewed value that is neither text nor ``None``, which
|
|
49
|
+
is a server bug a preview would hide.
|
|
50
|
+
"""
|
|
51
|
+
row = dict(record)
|
|
52
|
+
for field in omit:
|
|
53
|
+
row.pop(field, None)
|
|
54
|
+
for field, chars in (preview or {}).items():
|
|
55
|
+
if field not in row:
|
|
56
|
+
continue
|
|
57
|
+
value = row.pop(field)
|
|
58
|
+
if value is not None and not isinstance(value, str):
|
|
59
|
+
raise TypeError(f"{field} is previewed as text, not {type(value).__name__}")
|
|
60
|
+
row[f"{field}_preview"] = None if value is None else preview_text(value, chars)
|
|
61
|
+
return row
|