@littlebigbrain/mcp 0.2.0

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/LICENSE ADDED
@@ -0,0 +1,56 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
package/README.md ADDED
@@ -0,0 +1,369 @@
1
+ # @littlebigbrain/mcp
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server that gives an agent a small,
4
+ graph-aware tool belt over a [Little Big Brain](https://littlebigbrain.com) server. It wraps the
5
+ [`@littlebigbrain/client`](https://www.npmjs.com/package/@littlebigbrain/client) TypeScript SDK and ships two ways: a local
6
+ stdio shim (`npx @littlebigbrain/mcp`) and a hosted streamable-HTTP endpoint.
7
+
8
+ ## Local (stdio) — Claude Code, Cursor, Codex
9
+
10
+ Add to your editor's MCP config (`.mcp.json` / `mcp.json`):
11
+
12
+ ```json
13
+ {
14
+ "mcpServers": {
15
+ "lbb": {
16
+ "command": "npx",
17
+ "args": ["-y", "@littlebigbrain/mcp"],
18
+ "env": {
19
+ "LBB_BASE_URL": "https://db.eu.littlebigbrain.com",
20
+ "LBB_API_KEY": "lbb_sk_live_…"
21
+ }
22
+ }
23
+ }
24
+ }
25
+ ```
26
+
27
+ Set `LBB_GRAPH` / `LBB_BRANCH` to target a graph/branch other than `main`.
28
+ For a local server, point `LBB_BASE_URL` at `http://127.0.0.1:7400` and use the
29
+ single-mode token.
30
+
31
+ ## Hosted (streamable-HTTP, WorkOS OAuth)
32
+
33
+ The hosted endpoint at `https://mcp.littlebigbrain.com` is served by Little Big
34
+ Brain's hosted SaaS API and authenticated with **native WorkOS MCP OAuth** — there is
35
+ no static bearer key. It is an OAuth 2.1 protected resource: WorkOS AuthKit is
36
+ the authorization server. Claude-style clients can use the per-stack URL:
37
+
38
+ ```json
39
+ {
40
+ "mcpServers": {
41
+ "lbb": {
42
+ "url": "https://mcp.littlebigbrain.com/mcp/<your-stack-slug>"
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ An MCP client that supports remote auth (Claude, Cursor, …) discovers the OAuth
49
+ flow automatically: the server answers an unauthenticated request with `401` and
50
+ a `WWW-Authenticate` challenge pointing at
51
+ `/.well-known/oauth-protected-resource/mcp/<slug>`, the client runs the AuthKit
52
+ sign-in (DCR/PKCE), and presents the resulting access token. The endpoint
53
+ validates the WorkOS JWT, confirms your account owns the stack, mints a
54
+ short-lived data-plane session, and runs the tools scoped to that stack — your
55
+ machine never holds a Little Big Brain key. Add `?graph=`/`?branch=` to the URL to target a
56
+ graph/branch other than `main`.
57
+
58
+ Codex Desktop currently sends the MCP server URL as an OAuth `resource`
59
+ parameter and also appends any configured `oauth_resource`, which produces a
60
+ duplicate `resource` query that AuthKit rejects. For Codex, use the MCP origin
61
+ as the URL and pass the stack in a header; do not set `oauth_resource`:
62
+
63
+ ```json
64
+ {
65
+ "mcpServers": {
66
+ "lbb": {
67
+ "type": "http",
68
+ "url": "https://mcp.littlebigbrain.com",
69
+ "headers": {
70
+ "X-LBB-Stack": "<your-stack-slug>"
71
+ }
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ For self-hosting (single-mode `lbb-server`), `npm run start:http` serves the
78
+ same tools over streamable-HTTP (default `127.0.0.1:8080/mcp`) with a simpler
79
+ **key** bearer passed straight through — use this only behind your own auth,
80
+ not as a multi-tenant public endpoint. It binds loopback by default and
81
+ rejects non-loopback `Host`/`Origin` headers (DNS-rebinding protection); set
82
+ `LBB_MCP_HOST` to bind another interface deliberately, and
83
+ `LBB_MCP_ALLOWED_HOSTS` / `LBB_MCP_ALLOWED_ORIGINS` (comma-separated) when it
84
+ sits behind a hostname you control.
85
+
86
+ ## Embed in a Node process
87
+
88
+ The package entrypoint exposes a small, supported library API in addition to
89
+ the `lbb-mcp` executable:
90
+
91
+ - `createMcpHttpServer(options)` creates a Node `http.Server` with `/healthz`
92
+ and a key-bearer streamable-HTTP MCP route.
93
+ - `buildLbbServer(client)` creates an MCP `McpServer` bound to an existing
94
+ `LbbClient`.
95
+ - `registerLbbTools(server, client)` installs the eleven tools on an existing
96
+ MCP server.
97
+
98
+ ```ts
99
+ import {
100
+ createMcpHttpServer,
101
+ type McpHttpServerOptions,
102
+ } from "@littlebigbrain/mcp";
103
+
104
+ const options: McpHttpServerOptions = {
105
+ baseUrl: "https://db.eu.littlebigbrain.com",
106
+ mcpPath: "/mcp",
107
+ maxBodyBytes: 1_048_576,
108
+ requestTimeoutMs: 30_000,
109
+ // DNS-rebinding protection: reject other Host/Origin headers on the MCP
110
+ // route. Omit only when an edge you control already pins Host.
111
+ allowedHosts: ["127.0.0.1", "localhost", "::1", "[::1]"],
112
+ onError: () => console.error("MCP request failed"),
113
+ };
114
+
115
+ createMcpHttpServer(options).listen(8080, "127.0.0.1");
116
+ ```
117
+
118
+ Clients call `POST /mcp` with `Content-Type: application/json` and
119
+ `Authorization: Bearer <LBB_API_KEY>`; add `?graph=` / `?branch=` to override
120
+ the default scope. `clientFactory` is also available in
121
+ `McpHttpServerOptions` for dependency injection. The hosted multi-tenant OAuth
122
+ edge is intentionally not part of this library API.
123
+
124
+ ### Create an ontology (so agents can use a typed graph)
125
+
126
+ `lbb_configure` with `action: "define_ontology"` creates a **new** graph with a custom ontology, since the
127
+ ontology is fixed at graph creation. Give it entity-type and relation names (the
128
+ agent-friendly "spec" shape) and Little Big Brain fills in ids and sensible defaults:
129
+
130
+ ```jsonc
131
+ // lbb_configure
132
+ {
133
+ "action": "define_ontology",
134
+ "graph": "support",
135
+ "entity_types": [{ "name": "Customer" }, { "name": "Ticket" }],
136
+ "relations": [
137
+ { "name": "OPENED", "source": ["Customer"], "target": ["Ticket"], "reducer": "append_only" }
138
+ ]
139
+ }
140
+ ```
141
+
142
+ Then `lbb_commit` typed facts against the new graph and `lbb_inspect`
143
+ with `action: "ontology"` to confirm the vocabulary. For an existing standard ontology, pass a raw
144
+ `source` document with `format` (`turtle`, `json_ld`, `rdf_xml`, `csv`, `tsv`,
145
+ or `lbb_json`; omit or `auto` to auto-detect) instead of the structured
146
+ fields.
147
+
148
+ ## Tools
149
+
150
+ Agent-shaped task tools, not one tool per route. The previous route-shaped
151
+ surface is replaced by these eleven task tools, with no legacy aliases.
152
+
153
+ | Tool | Purpose |
154
+ | --- | --- |
155
+ | `lbb_search` | natural-language retrieval, multi-query fusion, and optional text-seeded path following |
156
+ | `lbb_ask` | grounded natural-language answers with citations |
157
+ | `lbb_decode` | name a relation from the graph's admissible vocabulary |
158
+ | `lbb_ground` | complete, resolve, or audit terms against real graph vocabulary |
159
+ | `lbb_inspect` | graph context and exact reads: guide, ontology, RDF/SHACL schema, stored rules, metadata, entity, state, history, why, traverse |
160
+ | `lbb_query` | analytical/expert reads: structured query, SPARQL text, SHACL, inference, retrieval premises, canned analysis |
161
+ | `lbb_commit` | write triplets, embeddings, or entity properties; omitted idempotency keys are content-derived for agent retries |
162
+ | `lbb_observe` | store a conversation episode and gate extracted facts on an isolation branch |
163
+ | `lbb_branch` | create and validate-then-merge graph branches |
164
+ | `lbb_configure` | define a new graph ontology, publish a previewed RDF/SHACL schema, or replace stored inference rules |
165
+ | `lbb_index` | refresh persisted BM25, vector, and adjacency indexes |
166
+
167
+ Read tools accept `detail: "compact" | "standard" | "full"` and default to
168
+ compact structured envelopes: `{summary, data, counts?, truncated?, rows_shown?, next?}`.
169
+ `detail` controls verbosity only. Query row volume is controlled by
170
+ `row_limit` plus cursor paging: tabular `lbb_query` responses include
171
+ `row_page: {returned, total, offset, limit, has_more, next_offset?}`. Whenever a
172
+ query page is partial, `summary` says `returned X of Y rows` and `next` contains
173
+ `{mode, cursor, row_limit, detail}`; pass that cursor back to continue without
174
+ hand-writing `LIMIT/OFFSET`. Cursor continuation reuses the original query/body
175
+ and pins every page to the head commit observed on page 1, so live writes between
176
+ pages cannot shift offset slicing. When the server returns a *complete* page
177
+ (`has_more: false`) whose rows are nonetheless too large to fit one MCP tool
178
+ result, the envelope caps the displayed rows and reports `rows_shown` (fewer than
179
+ `row_page.returned`) so the cap is never silent; `summary` reads
180
+ `MCP showed N of M rows` and `next` still carries a cursor that re-pages the same
181
+ result set at a smaller `row_limit`. A large result that *does* fit carries no
182
+ hard-cap warning and no `rows_shown`.
183
+ `lbb_inspect action=entity` samples its `incoming`/`outgoing`/`history` arrays to
184
+ the detail cap while `counts` holds the true totals; on a high-degree node the
185
+ response carries an `edge_sample` block (`{note, capped_totals, full_reads}`) with
186
+ runnable paged `edges`/`history` reads, so reading every edge of a supernode is
187
+ discoverable in-band rather than a workaround you have to already know.
188
+ Mode/action tools use discriminated schemas, so each selected mode or action
189
+ only accepts the fields that apply to that branch.
190
+ All server `LbbError` fields survive the MCP boundary in
191
+ `structuredContent.error` so agents can self-correct. A graph-scope 404 (the
192
+ raw `not found: tenants/…/graphs/<g>/branches/<b>/heads/current.json` object
193
+ key) is rewritten into an actionable message that lists the tenant's real
194
+ graphs — or, when the graph exists but the branch does not, its real branches —
195
+ and tells you which `graph=`/`branch=` to pass. The connection targets a default
196
+ graph/branch (often `main`) when you omit them.
197
+ When `lbb_commit` omits `idempotency_key`, MCP derives one from the graph,
198
+ branch, and payload; intentionally repeating an identical commit within the
199
+ server retention window requires an explicit different `idempotency_key`.
200
+ MCP defaults `edge_idempotency` to `append`, so new evidence on an existing edge
201
+ is recorded. Pass `edge_idempotency: "skip_unchanged"` for re-runnable
202
+ backfills; exact duplicate current edges are skipped server-side, including
203
+ evidence-only repeats.
204
+
205
+ ### Migration table
206
+
207
+ | Old tool | New tool/action or mode |
208
+ | --- | --- |
209
+ | `lbb_multi_search` | `lbb_search` with `queries` |
210
+ | `lbb_semantic_traverse` | `lbb_search` with `follow_paths: true` |
211
+ | `lbb_traverse` | `lbb_inspect` with `action: "traverse"` |
212
+ | `lbb_current_state` | `lbb_inspect` with `action: "state"` |
213
+ | `lbb_history` | `lbb_inspect` with `action: "history"` |
214
+ | `lbb_why` | `lbb_inspect` with `action: "why"` |
215
+ | `lbb_ontology_search` | `lbb_inspect` with `action: "ontology_search"` |
216
+ | `lbb_ontology_view` | `lbb_inspect` with `action: "ontology"` |
217
+ | `lbb_graph_metadata` | `lbb_inspect` with `action: "metadata"` |
218
+ | entity detail | `lbb_inspect` with `action: "entity"` |
219
+ | `lbb_query_guide` | `lbb_inspect` with `action: "guide"` |
220
+ | schema view / audit / preview | `lbb_inspect` with `action: "schema"`, `"schema_audit"`, or `"schema_preview"` |
221
+ | stored rules view | `lbb_inspect` with `action: "rules"` |
222
+ | `lbb_sparql` | `lbb_query` with `mode: "sparql"` |
223
+ | `lbb_shacl` | `lbb_query` with `mode: "shacl"` |
224
+ | `lbb_infer` | `lbb_query` with `mode: "infer"` |
225
+ | `lbb_retrieval_premises` | `lbb_query` with `mode: "retrieval_premises"` |
226
+ | `lbb_analyze` | `lbb_query` with `mode: "analyze"` |
227
+ | `lbb_define_rules` | `lbb_configure` with `action: "define_rules"` |
228
+ | `lbb_ontology_define` | `lbb_configure` with `action: "define_ontology"` |
229
+ | schema publish | `lbb_configure` with `action: "publish_schema"` |
230
+ | `lbb_index_build` | `lbb_index` |
231
+ | `lbb_json` | no MCP replacement; use `@littlebigbrain/client` or direct HTTP for raw/operator endpoints intentionally outside the agent tool belt |
232
+
233
+ ### Querying: SPARQL-subset, SHACL, inference
234
+
235
+ Three complementary surfaces sit over the object-storage permutation view:
236
+
237
+ - **`lbb_query` mode `structured`** is a SPARQL-subset SELECT/ASK over a conjunctive basic graph
238
+ pattern (`patterns`) with `filters` (typed-literal FILTER), `group_by` +
239
+ `aggregates` (COUNT/SUM/AVG/MIN/MAX), `having`, `order_by`,
240
+ and `as_of_valid_time`. A `filters`/`having` entry has the exact shape
241
+ `{ compare: { op: eq|ne|lt|le|gt|ge, left, right } }` (or `and`/`or`/`not`),
242
+ where each operand is `{ var }`, `{ property: { var, field } }`, or a typed
243
+ `{ value: { str | i64 | f64 | bool | date_time | entity } }` — e.g.
244
+ `filters: [{ compare: { op: "ge", left: { property: { var: "d", field: "amount" } }, right: { value: { f64: 1000000 } } } }]`.
245
+ A pattern `predicate` is a relation name and is case-insensitive here. GROUP BY
246
+ is not limited to entity identity — `group_keys` can key on a typed scalar
247
+ attribute (`{ property: { var, field, as } }`) or a calendar bucket of a
248
+ datetime attribute (`{ date_bucket: { var, field, granularity, as } }`), and
249
+ those same attribute fields work in `filters` and as SUM/AVG/MIN/MAX operands.
250
+ So "commits per area per month" is one server-side query, not N entity fetches
251
+ bucketed by hand:
252
+
253
+ ```json
254
+ {
255
+ "patterns": [{ "subject": { "var": "c" }, "predicate": "committed_to", "object": { "var": "repo" } }],
256
+ "group_keys": [
257
+ { "date_bucket": { "var": "c", "field": "committed_at", "granularity": "month", "as": "m" } },
258
+ { "property": { "var": "c", "field": "area", "as": "area" } }
259
+ ],
260
+ "aggregates": [{ "func": "count", "as": "n" }],
261
+ "order_by": [{ "var": "m" }]
262
+ }
263
+ ```
264
+
265
+ `area`/`committed_at` are typed entity attributes (set via `entity_properties`,
266
+ read back flat under `attributes` — there is no nested `metadata.attributes`
267
+ blob); discover the queryable field names with `lbb_inspect action=ontology`
268
+ (`property_defs`) or `action=schema`. Pass `combinators` (`union`/`optional`/`minus`/
269
+ `exists`/`not_exists`) for group-graph-pattern legs — those return `solutions`
270
+ and are a separate request shape from aggregation. In MCP, use `row_limit` and
271
+ the returned `next.cursor` for row pages; the tool applies request-level
272
+ `limit`/`offset` for you and a cursor continuation reuses the original body.
273
+ Cheap aggregate count: pair an equality `having` (`{ compare: { op: "eq",
274
+ left: { var: "n" }, right: { value: { i64: 4 } } } }`) with `row_limit: 1` and
275
+ read the number of matching groups off `row_page.total` — no need to page every
276
+ matching row.
277
+ - **`lbb_query` mode `shacl`** evaluates node shapes: `shacl_mode: select` returns focus nodes
278
+ that match, `shacl_mode: validate` returns a conformance `report`. It is the home of
279
+ **property paths** (`path_expr`: `inverse`, `sequence`, `alternative`,
280
+ `one_or_more`/`zero_or_more`/`zero_or_one`), literal constraints (`datatype`,
281
+ `minInclusive`…, `pattern`, length), `unique` cross-node keys, `closed`
282
+ nodes, and logical `and`/`or`/`not`/`xone`.
283
+ - **`lbb_query` mode `infer`** runs SHACL-AF inference rules to a bounded fixpoint and
284
+ previews the derived edges (never written). **`lbb_configure` action
285
+ `define_rules`** stores a rule set so SHACL `include_derived` can
286
+ validate/select over inferred facts.
287
+
288
+ SPARQL text (`mode: "sparql"`) addresses relations/types/properties as
289
+ `<https://littlebigbrain.com/{r,class,p}/name>`, and the local name is **always
290
+ lowercase** — an uppercase one (e.g. `<…/r/FOR_CLIENT>`) is a different,
291
+ non-existent IRI that silently matches nothing. The tool auto-lowercases those
292
+ Little Big Brain IRI local names for you (percent-escapes preserved; foreign IRIs and string
293
+ literals untouched) and reports each rewrite under `notes`, so a stray uppercase
294
+ resolves instead of returning an empty result with no error.
295
+
296
+ ### RDF schema and stored rules workflow
297
+
298
+ Agents should treat RDF/SHACL schema changes as preview-then-publish:
299
+
300
+ 1. Read current state with `lbb_inspect` `action: "schema"` and stored rules with
301
+ `action: "rules"`.
302
+ 2. Preview proposed SHACL/RDF shapes with `lbb_inspect`
303
+ `action: "schema_preview"`. Shape sources accept `auto`, `turtle`,
304
+ `n_triples`, `n_quads`, or `trig`. Ontology sources accept `auto`, `spec`,
305
+ `lbb_json`, `json_ld`, `rdf_xml`, `csv`, `tsv`, or `turtle`.
306
+
307
+ ```jsonc
308
+ // lbb_inspect
309
+ {
310
+ "action": "schema_preview",
311
+ "desired_mode": "reject",
312
+ "shapes": {
313
+ "format": "turtle",
314
+ "source": "@prefix sh: <http://www.w3.org/ns/shacl#> .\n..."
315
+ }
316
+ }
317
+ ```
318
+
319
+ The preview result includes the `preview_digest`, compatibility verdict, allowed
320
+ publish modes, audit summary, messages, and a `suggested_publish_schema` tool
321
+ call when the bundle can be activated in some mode. Publish only with the exact
322
+ source used for preview:
323
+
324
+ ```jsonc
325
+ // lbb_configure
326
+ {
327
+ "action": "publish_schema",
328
+ "preview_digest": "sha256:...",
329
+ "desired_mode": "warn",
330
+ "confirm_restrictive": true,
331
+ "shapes": {
332
+ "format": "turtle",
333
+ "source": "@prefix sh: <http://www.w3.org/ns/shacl#> .\n..."
334
+ }
335
+ }
336
+ ```
337
+
338
+ After publishing, run `lbb_inspect` `action: "schema_audit"` and read back
339
+ `action: "schema"`. For stored inference rules, preview behavior with
340
+ `lbb_query` `mode: "infer"` first, then replace the branch rule set with
341
+ `lbb_configure` `action: "define_rules"`. `define_rules` requires a `rules`
342
+ array; replacing the stored set with an empty array requires
343
+ `confirm_empty: true`.
344
+
345
+ SPARQL text `SELECT`/`ASK` is exposed through `lbb_query` `mode: "sparql"` and
346
+ returns SPARQL Results JSON inside the MCP row-page envelope. SPARQL Update,
347
+ SPARQL Protocol details, and SHACL-SPARQL/AF conformance remain a separate
348
+ compliance track; the structured SHACL/inference tools above are the
349
+ object-storage-native shape/inference surface.
350
+
351
+ Operator-only actions (index GC, compaction, storage inspection) are
352
+ intentionally left to the [`lbb` CLI](https://docs.littlebigbrain.com/sdks/cli/), not the agent
353
+ tool belt.
354
+
355
+ ## Develop
356
+
357
+ ```sh
358
+ npm install
359
+ npm run build
360
+ npm test # in-memory MCP + bounded localhost HTTP tests
361
+ npm run test:coverage
362
+ npm run pack:check # exact tarball: publint + ATTW
363
+ npm start # stdio server from the environment
364
+ ```
365
+
366
+ The self-hosted HTTP edge defaults to a 1 MiB request-body cap and 30-second
367
+ request timeout, requires JSON plus a bearer token, and redacts unexpected
368
+ internal errors. Override its path with `LBB_MCP_PATH`; the hosted multi-tenant
369
+ endpoint remains the WorkOS OAuth service described above.
@@ -0,0 +1,33 @@
1
+ import { type IncomingMessage, type Server } from "node:http";
2
+ import { LbbClient } from "@littlebigbrain/client";
3
+ export interface McpHttpServerOptions {
4
+ baseUrl?: string;
5
+ mcpPath?: string;
6
+ maxBodyBytes?: number;
7
+ requestTimeoutMs?: number;
8
+ /**
9
+ * DNS-rebinding protection for the MCP route. When set, the request `Host`
10
+ * hostname must be in the list, and a present `Origin` hostname must be in
11
+ * it too (or the exact origin in `allowedOrigins`); otherwise 403. Leave
12
+ * unset only when the server sits behind an edge that already pins Host
13
+ * (the hosted OAuth endpoint does). The `lbb-mcp-http` entrypoint defaults
14
+ * this to loopback names when bound to loopback.
15
+ */
16
+ allowedHosts?: string[];
17
+ /** Exact `Origin` values additionally allowed by the rebinding check. */
18
+ allowedOrigins?: string[];
19
+ onError?: (error: unknown) => void;
20
+ clientFactory?: (options: {
21
+ baseUrl: string;
22
+ apiKey: string;
23
+ graph?: string;
24
+ branch?: string;
25
+ }) => LbbClient;
26
+ }
27
+ export declare function bearer(req: IncomingMessage): string | undefined;
28
+ export declare function readJsonBody(req: IncomingMessage, maxBodyBytes?: number): Promise<unknown>;
29
+ /**
30
+ * Build the key-bearer streamable-HTTP MCP edge without starting a listener.
31
+ * The hosted multi-tenant OAuth endpoint remains in the SaaS API.
32
+ */
33
+ export declare function createMcpHttpServer(options?: McpHttpServerOptions): Server;
@@ -0,0 +1,181 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { createServer, } from "node:http";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import { LbbClient } from "@littlebigbrain/client";
5
+ import { buildLbbServer } from "./server.js";
6
+ const DEFAULT_MAX_BODY_BYTES = 1_048_576;
7
+ class HttpProblem extends Error {
8
+ status;
9
+ constructor(status, message) {
10
+ super(message);
11
+ this.status = status;
12
+ }
13
+ }
14
+ function sendJson(res, status, value) {
15
+ res
16
+ .writeHead(status, {
17
+ "content-type": "application/json; charset=utf-8",
18
+ "cache-control": "no-store",
19
+ })
20
+ .end(JSON.stringify(value));
21
+ }
22
+ function headerHostname(value) {
23
+ try {
24
+ // `Host` has no scheme and `Origin` does; parse each accordingly.
25
+ return new URL(value.includes("://") ? value : `http://${value}`).hostname;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ function rebindingProblem(req, allowedHosts, allowedOrigins) {
32
+ const host = req.headers.host;
33
+ const hostName = typeof host === "string" ? headerHostname(host) : undefined;
34
+ if (!hostName || !allowedHosts.includes(hostName)) {
35
+ return new HttpProblem(403, "forbidden host header");
36
+ }
37
+ const origin = req.headers.origin;
38
+ if (typeof origin === "string" && origin !== "") {
39
+ const originName = headerHostname(origin);
40
+ const originAllowed = allowedOrigins.includes(origin) ||
41
+ (originName !== undefined && allowedHosts.includes(originName));
42
+ if (!originAllowed)
43
+ return new HttpProblem(403, "forbidden origin");
44
+ }
45
+ return undefined;
46
+ }
47
+ export function bearer(req) {
48
+ const auth = req.headers.authorization;
49
+ if (typeof auth !== "string" || !auth.toLowerCase().startsWith("bearer ")) {
50
+ return undefined;
51
+ }
52
+ const token = auth.slice(7).trim();
53
+ return token || undefined;
54
+ }
55
+ export function readJsonBody(req, maxBodyBytes = DEFAULT_MAX_BODY_BYTES) {
56
+ const contentLength = Number(req.headers["content-length"] ?? 0);
57
+ if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) {
58
+ req.resume();
59
+ return Promise.reject(new HttpProblem(413, "request body too large"));
60
+ }
61
+ return new Promise((resolve, reject) => {
62
+ let bytes = 0;
63
+ let data = "";
64
+ let tooLarge = false;
65
+ req.setEncoding("utf8");
66
+ req.on("data", (chunk) => {
67
+ bytes += Buffer.byteLength(chunk);
68
+ if (bytes > maxBodyBytes) {
69
+ tooLarge = true;
70
+ data = "";
71
+ }
72
+ else if (!tooLarge) {
73
+ data += chunk;
74
+ }
75
+ });
76
+ req.on("end", () => {
77
+ if (tooLarge) {
78
+ reject(new HttpProblem(413, "request body too large"));
79
+ return;
80
+ }
81
+ if (!data) {
82
+ resolve(undefined);
83
+ return;
84
+ }
85
+ try {
86
+ resolve(JSON.parse(data));
87
+ }
88
+ catch {
89
+ reject(new HttpProblem(400, "invalid JSON request body"));
90
+ }
91
+ });
92
+ req.on("error", reject);
93
+ });
94
+ }
95
+ /**
96
+ * Build the key-bearer streamable-HTTP MCP edge without starting a listener.
97
+ * The hosted multi-tenant OAuth endpoint remains in the SaaS API.
98
+ */
99
+ export function createMcpHttpServer(options = {}) {
100
+ const baseUrl = options.baseUrl ?? "https://db.eu.littlebigbrain.com";
101
+ const mcpPath = options.mcpPath ?? "/mcp";
102
+ const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
103
+ const requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
104
+ const allowedHosts = options.allowedHosts;
105
+ const allowedOrigins = options.allowedOrigins ?? [];
106
+ if (!mcpPath.startsWith("/"))
107
+ throw new Error("mcpPath must start with /");
108
+ if (!Number.isInteger(maxBodyBytes) || maxBodyBytes <= 0) {
109
+ throw new Error("maxBodyBytes must be a positive integer");
110
+ }
111
+ return createServer({ requestTimeout: requestTimeoutMs }, async (req, res) => {
112
+ try {
113
+ const url = new URL(req.url ?? "/", "http://localhost");
114
+ if (req.method === "GET" && url.pathname === "/healthz") {
115
+ sendJson(res, 200, { ok: true });
116
+ return;
117
+ }
118
+ if (req.method !== "POST" || url.pathname !== mcpPath) {
119
+ req.resume();
120
+ sendJson(res, 404, { error: "not found" });
121
+ return;
122
+ }
123
+ if (allowedHosts && allowedHosts.length > 0) {
124
+ const problem = rebindingProblem(req, allowedHosts, allowedOrigins);
125
+ if (problem) {
126
+ req.resume();
127
+ sendJson(res, problem.status, { error: problem.message });
128
+ return;
129
+ }
130
+ }
131
+ const apiKey = bearer(req);
132
+ if (!apiKey) {
133
+ req.resume();
134
+ sendJson(res, 401, { error: "missing bearer token" });
135
+ return;
136
+ }
137
+ const contentType = req.headers["content-type"] ?? "";
138
+ if (!contentType.toLowerCase().startsWith("application/json")) {
139
+ req.resume();
140
+ sendJson(res, 415, {
141
+ error: "content-type must be application/json",
142
+ });
143
+ return;
144
+ }
145
+ const body = await readJsonBody(req, maxBodyBytes);
146
+ const clientOptions = {
147
+ baseUrl,
148
+ apiKey,
149
+ graph: url.searchParams.get("graph") ?? undefined,
150
+ branch: url.searchParams.get("branch") ?? undefined,
151
+ };
152
+ const client = options.clientFactory
153
+ ? options.clientFactory(clientOptions)
154
+ : new LbbClient(clientOptions);
155
+ const server = buildLbbServer(client);
156
+ const transport = new StreamableHTTPServerTransport({
157
+ sessionIdGenerator: undefined,
158
+ });
159
+ res.on("close", () => {
160
+ void transport.close();
161
+ void server.close();
162
+ });
163
+ await server.connect(transport);
164
+ await transport.handleRequest(req, res, body);
165
+ }
166
+ catch (error) {
167
+ options.onError?.(error);
168
+ if (!res.headersSent) {
169
+ if (error instanceof HttpProblem) {
170
+ sendJson(res, error.status, { error: error.message });
171
+ }
172
+ else {
173
+ sendJson(res, 500, { error: "internal server error" });
174
+ }
175
+ }
176
+ else if (!res.writableEnded) {
177
+ res.destroy();
178
+ }
179
+ }
180
+ });
181
+ }