@blenau/mcp 0.1.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Ganemo
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ Blenau MCP (@blenau/mcp)
2
+ Copyright 2026 Ganemo
3
+
4
+ This product is developed and maintained by Ganemo (https://blenau.com).
5
+
6
+ Licensed under the Apache License, Version 2.0. See the LICENSE file for the
7
+ full terms.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # @blenau/mcp
2
+
3
+ The Blenau MCP server + CLI. Connects agents (Claude Code, Cursor, Claude
4
+ Desktop, …) to the **Blenau knowledge brain** over **stdio**, with credentials
5
+ in the **OS keychain** — never a token in a config file or in a URL.
6
+
7
+ This replaces the legacy SSE endpoint (`https://api.blenau.com/mcp/sse?token=…`),
8
+ which forced clients to store a bearer token in plaintext. Same tools, same
9
+ input/output shapes — different, safe auth.
10
+
11
+ > **This config contains NO secrets.** Credentials live in the OS keychain
12
+ > (device flow) or are injected at runtime as `BLENAU_AGENT_TOKEN` (service
13
+ > mode), never in client config files.
14
+
15
+ ## Installation
16
+
17
+ ```sh
18
+ npm install -g @blenau/mcp # or just use npx (below)
19
+ ```
20
+
21
+ ## Interactive setup (humans)
22
+
23
+ 1. Register the server with your MCP client. For Claude Code:
24
+
25
+ ```jsonc
26
+ // ~/.claude.json (or via `claude mcp add`)
27
+ "mcpServers": {
28
+ "blenau": { "type": "stdio", "command": "npx", "args": ["-y", "@blenau/mcp"] }
29
+ }
30
+ ```
31
+ Cursor (`~/.cursor/mcp.json`) and Claude Desktop use the same shape.
32
+
33
+ 2. Log in once (device flow against Prysm:ID):
34
+
35
+ ```sh
36
+ npx -y @blenau/mcp login
37
+ ```
38
+ Open the printed URL, approve, done. The **refresh token** is stored in your
39
+ OS keychain (`service: blenau-mcp`). `blenau whoami` shows who you are;
40
+ `blenau logout` revokes and clears it.
41
+
42
+ ## Autonomous setup (agents / CI / cron)
43
+
44
+ For unattended use, run in **service mode** with a native Blenau agent token
45
+ (`blenau_tk_`-style). The token is used directly as the `Authorization: Bearer`
46
+ header — it encodes kind + scope server-side, so there is no key exchange or
47
+ keychain. Keep it in a secret manager and inject at launch:
48
+
49
+ ```sh
50
+ # Recommended for Ganemo agents (Secrevo):
51
+ secrevo run --secret BLENAU_AGENT_TOKEN -- npx -y @blenau/mcp
52
+ ```
53
+
54
+ When `BLENAU_AGENT_TOKEN` is set the server uses service mode automatically;
55
+ `login`/`logout` are rejected.
56
+
57
+ ## Security model
58
+
59
+ - **Device flow (RFC 8628)** for humans: a public OAuth client (no secret), the
60
+ refresh token in the OS keychain (Windows Credential Manager / macOS Keychain
61
+ / libsecret), access tokens only in memory, refreshed (with rotation) before
62
+ expiry.
63
+ - **Native Blenau token** for agents: `BLENAU_AGENT_TOKEN` is used directly as
64
+ the bearer; scope is encoded server-side, so no key exchange or signing.
65
+ - Tokens are validated by `api.blenau.com` against Prysm:ID's JWKS (RS256, iss,
66
+ aud). The token value is **never** logged — debug output carries only a
67
+ truncated sha256.
68
+ - This package never reads `~/.aws`, `~/.ssh`, `*.env`, or other clients' MCP
69
+ config.
70
+
71
+ ## Migration from the SSE endpoint
72
+
73
+ The old `…/mcp/sse?token=…` URL still works for now but is deprecated. Switch
74
+ your client config to the stdio snippet above and run `blenau login` (or set
75
+ `BLENAU_AGENT_TOKEN`). The SSE endpoint will be sunset on a later,
76
+ separately-announced timeline.
77
+
78
+ ## Configuration (env)
79
+
80
+ | Var | Purpose |
81
+ | --- | --- |
82
+ | `BLENAU_AGENT_TOKEN` | native Blenau agent token → service mode (used directly as bearer) |
83
+ | `BLENAU_API_BASE_URL` | override the API base (default `https://api.blenau.com`) |
84
+ | `BLENAU_OIDC_ISSUER` / `BLENAU_OIDC_CLIENT_ID` | override OIDC issuer / public client |
85
+ | `LOG_LEVEL=debug` | safe debug logs (never the token value) |
86
+
87
+ ## Tools
88
+
89
+ 18 tools mirroring the Blenau API: `list_repos`, `search_knowledge`,
90
+ `get_document`, `get_document_structure`, `get_section`, `ingest_document`,
91
+ `crystallize_session`, `smart_crystallize`, `create_asset_upload`,
92
+ `upload_asset`, `list_assets`, `verify_asset`, `delete_asset`, `list_documents`,
93
+ `edit_section`, `audit_links`, `suggest_crosslinks`, `get_audit_log`.
package/dist/index.js ADDED
@@ -0,0 +1,534 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { decodeJwt as decodeJwt2 } from "jose";
5
+
6
+ // src/auth/device.ts
7
+ import open from "open";
8
+ import { decodeJwt } from "jose";
9
+
10
+ // src/config.ts
11
+ var OAUTH = {
12
+ issuer: process.env.BLENAU_OIDC_ISSUER ?? "https://blenau.auth.prysmid.com",
13
+ clientId: process.env.BLENAU_OIDC_CLIENT_ID ?? "375546511070593027",
14
+ // offline_access is required to receive a refresh_token in the device flow.
15
+ scope: "openid profile email offline_access"
16
+ };
17
+ var API_BASE = (process.env.BLENAU_API_BASE_URL ?? "https://api.blenau.com").replace(/\/+$/, "");
18
+ var KEYCHAIN_SERVICE = "blenau-mcp";
19
+ var KEYCHAIN_ACCOUNT = "default";
20
+
21
+ // src/auth/discovery.ts
22
+ var cached;
23
+ var fetchedAt = 0;
24
+ var TTL_MS = 60 * 60 * 1e3;
25
+ async function getDiscovery(force = false) {
26
+ const now = Date.now();
27
+ if (!force && cached && now - fetchedAt < TTL_MS) return cached;
28
+ const url = `${OAUTH.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`;
29
+ const resp = await fetch(url, { headers: { Accept: "application/json" } });
30
+ if (!resp.ok) {
31
+ throw new Error(`OIDC discovery failed: ${resp.status} ${resp.statusText}`);
32
+ }
33
+ cached = await resp.json();
34
+ fetchedAt = now;
35
+ return cached;
36
+ }
37
+
38
+ // src/auth/keychain.ts
39
+ var keytarPromise;
40
+ async function keytar() {
41
+ if (!keytarPromise) keytarPromise = import("keytar").then((m) => m.default ?? m);
42
+ return keytarPromise;
43
+ }
44
+ async function getRefreshToken() {
45
+ const kt = await keytar();
46
+ return kt.getPassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);
47
+ }
48
+ async function setRefreshToken(token) {
49
+ const kt = await keytar();
50
+ await kt.setPassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT, token);
51
+ }
52
+ async function deleteRefreshToken() {
53
+ const kt = await keytar();
54
+ return kt.deletePassword(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);
55
+ }
56
+
57
+ // src/auth/util.ts
58
+ import { createHash } from "crypto";
59
+ function sha256_16(secret) {
60
+ return createHash("sha256").update(secret).digest("hex").slice(0, 16);
61
+ }
62
+ function debug(msg) {
63
+ if (process.env.LOG_LEVEL === "debug" || process.env.DEBUG) {
64
+ process.stderr.write(`[blenau-mcp][debug] ${msg}
65
+ `);
66
+ }
67
+ }
68
+
69
+ // src/auth/device.ts
70
+ var mem = null;
71
+ async function tokenRequest(params) {
72
+ const d = await getDiscovery();
73
+ const resp = await fetch(d.token_endpoint, {
74
+ method: "POST",
75
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
76
+ body: new URLSearchParams(params).toString()
77
+ });
78
+ const body = await resp.json().catch(() => ({}));
79
+ if (!resp.ok) {
80
+ const err = new Error(String(body.error ?? `token_endpoint ${resp.status}`));
81
+ err.oauthError = body.error;
82
+ throw err;
83
+ }
84
+ return body;
85
+ }
86
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
87
+ async function login() {
88
+ const d = await getDiscovery();
89
+ const startResp = await fetch(d.device_authorization_endpoint, {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
92
+ body: new URLSearchParams({ client_id: OAUTH.clientId, scope: OAUTH.scope }).toString()
93
+ });
94
+ if (!startResp.ok) {
95
+ throw new Error(`device_authorization failed: ${startResp.status} ${startResp.statusText}`);
96
+ }
97
+ const start = await startResp.json();
98
+ const verify = start.verification_uri_complete ?? start.verification_uri;
99
+ process.stderr.write(
100
+ `
101
+ Visit: ${start.verification_uri}
102
+ Enter code: ${start.user_code}
103
+
104
+ ` + (start.verification_uri_complete ? `(Or open ${start.verification_uri_complete} for one-click approval)
105
+
106
+ ` : "") + `Waiting for approval...
107
+ `
108
+ );
109
+ try {
110
+ await open(verify);
111
+ } catch {
112
+ }
113
+ let interval = (start.interval ?? 5) * 1e3;
114
+ const deadline = Date.now() + start.expires_in * 1e3;
115
+ for (; ; ) {
116
+ if (Date.now() > deadline) throw new Error("Device code expired before approval. Run `blenau login` again.");
117
+ await sleep(interval);
118
+ let tok;
119
+ try {
120
+ tok = await tokenRequest({
121
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
122
+ device_code: start.device_code,
123
+ client_id: OAUTH.clientId
124
+ });
125
+ } catch (e) {
126
+ const oauth = e.oauthError;
127
+ if (oauth === "authorization_pending") continue;
128
+ if (oauth === "slow_down") {
129
+ interval += 5e3;
130
+ continue;
131
+ }
132
+ throw e;
133
+ }
134
+ if (!tok.refresh_token) {
135
+ throw new Error("No refresh_token returned \u2014 was `offline_access` granted to the client?");
136
+ }
137
+ await setRefreshToken(tok.refresh_token);
138
+ mem = { accessToken: tok.access_token, expiresAt: Date.now() + tok.expires_in * 1e3 };
139
+ let who = "";
140
+ if (tok.id_token) {
141
+ try {
142
+ const claims = decodeJwt(tok.id_token);
143
+ who = claims.email ?? claims.sub ?? "";
144
+ } catch {
145
+ }
146
+ }
147
+ process.stderr.write(`Logged in${who ? ` as ${who}` : ""}.
148
+ `);
149
+ return;
150
+ }
151
+ }
152
+ async function logout() {
153
+ const rt = await getRefreshToken();
154
+ if (rt) {
155
+ try {
156
+ const d = await getDiscovery();
157
+ if (d.revocation_endpoint) {
158
+ await fetch(d.revocation_endpoint, {
159
+ method: "POST",
160
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
161
+ body: new URLSearchParams({
162
+ token: rt,
163
+ token_type_hint: "refresh_token",
164
+ client_id: OAUTH.clientId
165
+ }).toString()
166
+ });
167
+ }
168
+ } catch {
169
+ }
170
+ }
171
+ await deleteRefreshToken();
172
+ mem = null;
173
+ process.stderr.write("Logged out.\n");
174
+ }
175
+ async function getDeviceAccessToken() {
176
+ if (mem && Date.now() < mem.expiresAt - 6e4) return mem.accessToken;
177
+ const rt = await getRefreshToken();
178
+ if (!rt) throw new Error("Not logged in. Run `blenau login` first.");
179
+ let tok;
180
+ try {
181
+ tok = await tokenRequest({
182
+ grant_type: "refresh_token",
183
+ refresh_token: rt,
184
+ client_id: OAUTH.clientId
185
+ });
186
+ } catch (e) {
187
+ if (e.oauthError === "invalid_grant") {
188
+ await deleteRefreshToken();
189
+ mem = null;
190
+ throw new Error("Refresh token expired or revoked. Run `blenau login` again.");
191
+ }
192
+ throw e;
193
+ }
194
+ if (tok.refresh_token && tok.refresh_token !== rt) {
195
+ await setRefreshToken(tok.refresh_token);
196
+ }
197
+ mem = { accessToken: tok.access_token, expiresAt: Date.now() + tok.expires_in * 1e3 };
198
+ debug(`device access token refreshed, sha256-16=${sha256_16(tok.access_token)}`);
199
+ return tok.access_token;
200
+ }
201
+
202
+ // src/auth/service.ts
203
+ var AGENT_TOKEN_ENV = "BLENAU_AGENT_TOKEN";
204
+ async function getServiceAccessToken() {
205
+ const token = process.env[AGENT_TOKEN_ENV];
206
+ if (!token) {
207
+ throw new Error(`Service mode requires ${AGENT_TOKEN_ENV}.`);
208
+ }
209
+ return token;
210
+ }
211
+
212
+ // src/auth/mode.ts
213
+ function detectMode() {
214
+ return process.env[AGENT_TOKEN_ENV] ? "service" : "device";
215
+ }
216
+ async function getAccessToken() {
217
+ return detectMode() === "service" ? getServiceAccessToken() : getDeviceAccessToken();
218
+ }
219
+
220
+ // src/server.ts
221
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
222
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
223
+ import { z } from "zod";
224
+
225
+ // src/client.ts
226
+ async function apiRequest(method, path, opts = {}) {
227
+ let token;
228
+ try {
229
+ token = await getAccessToken();
230
+ } catch (e) {
231
+ return { error: `auth_error: ${e.message}` };
232
+ }
233
+ const url = new URL(`${API_BASE}${path}`);
234
+ if (opts.params) {
235
+ for (const [k, v] of Object.entries(opts.params)) {
236
+ if (v !== void 0 && v !== null) url.searchParams.set(k, String(v));
237
+ }
238
+ }
239
+ const headers = {
240
+ Accept: "application/json",
241
+ Authorization: `Bearer ${token}`
242
+ };
243
+ if (opts.json !== void 0) headers["Content-Type"] = "application/json";
244
+ let resp;
245
+ try {
246
+ resp = await fetch(url, {
247
+ method,
248
+ headers,
249
+ body: opts.json !== void 0 ? JSON.stringify(opts.json) : void 0
250
+ });
251
+ } catch (e) {
252
+ return { error: `http_error: ${e.name}: ${e.message}` };
253
+ }
254
+ if (resp.status >= 400) {
255
+ const text3 = await resp.text();
256
+ try {
257
+ const body = JSON.parse(text3);
258
+ if (body && typeof body === "object" && ("error" in body || "detail" in body)) {
259
+ return { ...body, error: body.error ?? body.detail ?? "api_error", status_code: resp.status };
260
+ }
261
+ return { error: "api_error", status_code: resp.status, body };
262
+ } catch {
263
+ return { error: "api_error", status_code: resp.status, body: text3 };
264
+ }
265
+ }
266
+ if (resp.status === 204) return {};
267
+ const text2 = await resp.text();
268
+ if (!text2) return {};
269
+ try {
270
+ return JSON.parse(text2);
271
+ } catch {
272
+ return { error: "invalid_json", body: text2 };
273
+ }
274
+ }
275
+
276
+ // src/server.ts
277
+ var INSTRUCTIONS = `You are connected to a Blenau knowledge brain \u2014 a structured, versioned, provenance-tracked knowledge base shared across agents and humans.
278
+
279
+ GOLDEN RULE \u2014 search FIRST, write LATER.
280
+ Before calling ingest_document or crystallize_session, ALWAYS run search_knowledge with the topic(s) of the content you plan to write. The brain already holds docs on many subjects; creating a new file when one exists fragments the knowledge and degrades future searches.
281
+
282
+ Routing: a workspace can have several connected GitHub repos, each with a path_prefix. Call list_repos() BEFORE writing to a specific repo and prefix your path accordingly. Edits use optimistic locking: fetch get_section right before edit_section and pass expected_version. For images/binaries prefer create_asset_upload (stream bytes via curl) over upload_asset (base64, tiny icons only). Always cite external material via the sources argument.`;
283
+ var sourceSchema = z.array(
284
+ z.object({
285
+ type: z.string(),
286
+ ref: z.string(),
287
+ title: z.string().optional(),
288
+ retrieved_at: z.string().optional()
289
+ })
290
+ ).optional();
291
+ function text(result) {
292
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
293
+ }
294
+ function buildServer() {
295
+ const server = new McpServer(
296
+ { name: "Blenau", version: "0.1.0" },
297
+ { instructions: INSTRUCTIONS }
298
+ );
299
+ server.tool(
300
+ "list_repos",
301
+ "List all GitHub repos connected to this workspace. Returns each repo with id, repo (org/name), label, path_prefix, installation_id, doc_count, created_at. Call this BEFORE writing (ingest_document, crystallize_session, smart_crystallize) when you intend to land content in a specific repo \u2014 your path must start with that repo's path_prefix. Read-only.",
302
+ {},
303
+ async () => text(await apiRequest("GET", "/github/repos"))
304
+ );
305
+ server.tool(
306
+ "search_knowledge",
307
+ "Search the knowledge base semantically. Returns ranked results with relevance scores.",
308
+ { query: z.string(), top_k: z.number().int().default(10) },
309
+ async ({ query, top_k }) => text(await apiRequest("POST", "/knowledge/search", { json: { query, top_k } }))
310
+ );
311
+ server.tool(
312
+ "get_document",
313
+ "Get a document by its path, including all sections.",
314
+ { path: z.string() },
315
+ async ({ path }) => text(await apiRequest("GET", `/knowledge/documents/by-path/${path}`))
316
+ );
317
+ server.tool(
318
+ "get_document_structure",
319
+ "Get the outline (headings tree) of a document without full content.",
320
+ { path: z.string() },
321
+ async ({ path }) => text(await apiRequest("GET", `/knowledge/structure/${path}`))
322
+ );
323
+ server.tool(
324
+ "get_section",
325
+ "Get a specific section by path and heading. Returns content + version hash for editing.",
326
+ { path: z.string(), heading: z.string() },
327
+ async ({ path, heading }) => text(await apiRequest("GET", `/knowledge/section/${path}`, { params: { heading } }))
328
+ );
329
+ server.tool(
330
+ "ingest_document",
331
+ "Ingest a document into the knowledge base. Runs full pipeline (parse, chunk, embed, index). Routing: path matches a connected repo by longest path_prefix; call list_repos() first to discover prefixes. auto_link=True rewrites bare textual mentions of known document paths into markdown links. sources: list of {type, ref, title?, retrieved_at?} describing external material; appended as a `## Fuentes` section and stored in provenance.",
332
+ {
333
+ path: z.string(),
334
+ title: z.string(),
335
+ content: z.string(),
336
+ source_type: z.string().default("manual"),
337
+ auto_link: z.boolean().default(false),
338
+ sources: sourceSchema
339
+ },
340
+ async ({ path, title, content, source_type, auto_link, sources }) => text(
341
+ await apiRequest("POST", "/knowledge/ingest-enhanced", {
342
+ json: { path, title, content, source_type, auto_link, sources: sources ?? null }
343
+ })
344
+ )
345
+ );
346
+ server.tool(
347
+ "crystallize_session",
348
+ "Crystallize knowledge from an agent session into a single structured document. DEPRECATED for multi-topic sessions \u2014 prefer smart_crystallize. output_path is the folder under which the file is created (default docs/crystallized); prefix it with the target repo's path_prefix in multi-repo workspaces. sources: same shape as ingest_document.sources.",
349
+ {
350
+ session_context: z.string(),
351
+ title: z.string().default("Crystallized Knowledge"),
352
+ output_path: z.string().default("docs/crystallized"),
353
+ sources: sourceSchema
354
+ },
355
+ async ({ session_context, title, output_path, sources }) => text(
356
+ await apiRequest("POST", "/knowledge/crystallize-enhanced", {
357
+ json: { session_context, title, output_path, sources: sources ?? null }
358
+ })
359
+ )
360
+ );
361
+ server.tool(
362
+ "create_asset_upload",
363
+ 'PREFERRED way to attach an image / PDF / binary to a doc. Returns a short-lived upload_url; transfer the LOCAL file with one curl command so bytes never pass through you (e.g. `curl -F file=@/path/img.webp "<upload_url>"`; add -F insert_heading / -F insert_position to embed). Asset names are predictable (assets/<filename>); a content hash is appended only on a real collision. Embedding is idempotent. Size limit 1 MB \u2014 compress locally first if larger. Params: doc_path (routes the commit), filename, content_type (optional MIME).',
364
+ { doc_path: z.string(), filename: z.string(), content_type: z.string().default("") },
365
+ async ({ doc_path, filename, content_type }) => text(
366
+ await apiRequest("POST", "/assets/upload-url", {
367
+ params: { doc_path, filename, content_type }
368
+ })
369
+ )
370
+ );
371
+ server.tool(
372
+ "list_assets",
373
+ "List the image references in a doc and whether each resolves in GitHub. Returns { doc_path, doc_id, assets: [...] }. resolves:false means the markdown points at a path that isn't committed (the usual broken-image cause).",
374
+ { doc_path: z.string() },
375
+ async ({ doc_path }) => text(await apiRequest("GET", "/assets/list", { params: { doc_path } }))
376
+ );
377
+ server.tool(
378
+ "verify_asset",
379
+ "Check that ONE asset reference resolves (exists in GitHub \u2192 will render). relative_path is the path exactly as written in the markdown (e.g. assets/diagram.webp). Returns { resolves, asset_path, raw_url }.",
380
+ { doc_path: z.string(), relative_path: z.string() },
381
+ async ({ doc_path, relative_path }) => text(await apiRequest("GET", "/assets/resolve", { params: { doc_path, relative_path } }))
382
+ );
383
+ server.tool(
384
+ "delete_asset",
385
+ "Delete an asset FILE from the repo. Does NOT rewrite document references \u2014 if the doc still links it, remove that markdown separately via edit_section. relative_path is the path as written in the markdown. Returns { deleted, asset_path }.",
386
+ { doc_path: z.string(), relative_path: z.string() },
387
+ async ({ doc_path, relative_path }) => text(await apiRequest("DELETE", "/assets/file", { params: { doc_path, relative_path } }))
388
+ );
389
+ server.tool(
390
+ "upload_asset",
391
+ "LEGACY base64 upload \u2014 TINY assets only (<= 64 KB, e.g. a small SVG icon). For photos/screenshots or anything larger, use create_asset_upload instead. Commits the asset under an assets/ subdirectory of the doc's repo and returns a markdown snippet with a RELATIVE path. Params: doc_path, filename, content_base64 (data-URL prefix accepted), alt_text.",
392
+ {
393
+ doc_path: z.string(),
394
+ filename: z.string(),
395
+ content_base64: z.string(),
396
+ alt_text: z.string().default("")
397
+ },
398
+ async ({ doc_path, filename, content_base64, alt_text }) => text(
399
+ await apiRequest("POST", "/assets/upload", {
400
+ json: { doc_path, filename, content_base64, alt_text }
401
+ })
402
+ )
403
+ );
404
+ server.tool(
405
+ "smart_crystallize",
406
+ "Intelligently crystallize a session into the brain. Splits the session into topical blocks, searches existing docs per topic, and routes each block to edit/append/create. Opens ONE PR PER AFFECTED REPO if repos are connected. Prefer this over crystallize_session whenever the session spans multiple subjects. Call list_repos() first to nudge create paths toward the right path_prefix.",
407
+ { session_context: z.string(), repo_hint: z.string().optional() },
408
+ async ({ session_context, repo_hint }) => text(
409
+ await apiRequest("POST", "/knowledge/smart-crystallize", {
410
+ json: { session_context, repo_hint: repo_hint ?? null }
411
+ })
412
+ )
413
+ );
414
+ server.tool(
415
+ "list_documents",
416
+ "List all documents in the knowledge base with their status.",
417
+ {},
418
+ async () => text(await apiRequest("GET", "/knowledge/documents"))
419
+ );
420
+ server.tool(
421
+ "edit_section",
422
+ "Edit a section with optimistic locking. Pass the version from get_section to prevent conflicts.",
423
+ {
424
+ path: z.string(),
425
+ heading: z.string(),
426
+ new_content: z.string(),
427
+ expected_version: z.string()
428
+ },
429
+ async ({ path, heading, new_content, expected_version }) => text(
430
+ await apiRequest("POST", "/knowledge/edit-section", {
431
+ json: { path, heading, new_content, expected_version }
432
+ })
433
+ )
434
+ );
435
+ server.tool(
436
+ "audit_links",
437
+ "Audit the knowledge base for orphan documents, one-way links, pairs of documents with high semantic similarity that are not linked in markdown, documents missing source citations, and recurring concepts that lack their own dedicated doc. Returns orphan_documents, one_way_only, similar_but_unlinked, missing_sources, data_gaps. Read-only.",
438
+ {},
439
+ async () => text(await apiRequest("GET", "/github/audit-links"))
440
+ );
441
+ server.tool(
442
+ "suggest_crosslinks",
443
+ "Suggest markdown cross-links to add in a specific document. Returns the top 5 semantically-similar sections from other documents that aren't currently linked from this doc, with ready-to-paste markdown snippets. Read-only.",
444
+ { path: z.string() },
445
+ async ({ path }) => {
446
+ const doc = await apiRequest("GET", `/knowledge/documents/by-path/${path}`);
447
+ if (!doc || typeof doc !== "object" || "error" in doc) return text(doc ?? { error: "lookup_failed" });
448
+ const docId = doc.id ?? doc.document_id;
449
+ if (!docId) return text({ error: `Document not found: ${path}` });
450
+ const out = await apiRequest("GET", `/github/suggest-crosslinks/${docId}`);
451
+ if (out && typeof out === "object" && "suggestions" in out && !("document_path" in out)) {
452
+ out.document_path = path;
453
+ }
454
+ return text(out);
455
+ }
456
+ );
457
+ server.tool(
458
+ "get_audit_log",
459
+ "Get the audit log for this workspace. Shows who did what and when.",
460
+ { limit: z.number().int().default(50), event_type: z.string().optional() },
461
+ async ({ limit, event_type }) => text(
462
+ await apiRequest("GET", "/knowledge/audit-log", {
463
+ params: { limit, ...event_type ? { event_type } : {} }
464
+ })
465
+ )
466
+ );
467
+ return server;
468
+ }
469
+ async function runStdioServer() {
470
+ const server = buildServer();
471
+ const transport = new StdioServerTransport();
472
+ await server.connect(transport);
473
+ }
474
+
475
+ // src/index.ts
476
+ var VERSION = "0.1.0";
477
+ function rejectInService(action) {
478
+ if (detectMode() === "service") {
479
+ process.stderr.write(
480
+ `Service mode active (BLENAU_AGENT_TOKEN set). Interactive ${action} not applicable.
481
+ `
482
+ );
483
+ process.exit(1);
484
+ }
485
+ }
486
+ async function main() {
487
+ const cmd = process.argv[2];
488
+ switch (cmd) {
489
+ case void 0:
490
+ case "serve":
491
+ await runStdioServer();
492
+ return;
493
+ case "login":
494
+ rejectInService("login");
495
+ await login();
496
+ return;
497
+ case "logout":
498
+ rejectInService("logout");
499
+ await logout();
500
+ return;
501
+ case "whoami": {
502
+ const token = await getAccessToken();
503
+ const c = decodeJwt2(token);
504
+ const out = {
505
+ mode: detectMode(),
506
+ sub: c.sub,
507
+ email: c.email,
508
+ tenant_id: c.tenant_id,
509
+ workspace_id: c.workspace_id,
510
+ identity_type: c.identity_type
511
+ };
512
+ process.stdout.write(`${JSON.stringify(out, null, 2)}
513
+ `);
514
+ return;
515
+ }
516
+ case "--version":
517
+ case "-v":
518
+ process.stdout.write(`${VERSION}
519
+ `);
520
+ return;
521
+ default:
522
+ process.stderr.write(
523
+ `Unknown command: ${cmd}
524
+ Usage: blenau [serve|login|logout|whoami|--version]
525
+ `
526
+ );
527
+ process.exit(1);
528
+ }
529
+ }
530
+ main().catch((e) => {
531
+ process.stderr.write(`${e.message ?? String(e)}
532
+ `);
533
+ process.exit(1);
534
+ });
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@blenau/mcp",
3
+ "version": "0.1.0",
4
+ "description": "Blenau MCP server + CLI. Connects agents (Claude Code, Cursor, …) to the Blenau knowledge brain over stdio, with credentials in the OS keychain — never a token in a config file or URL.",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/getblenau/mcp.git"
9
+ },
10
+ "homepage": "https://github.com/getblenau/mcp#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/getblenau/mcp/issues"
13
+ },
14
+ "author": "Blenau (Ganemo)",
15
+ "bin": {
16
+ "blenau": "dist/index.js"
17
+ },
18
+ "main": "dist/index.js",
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE",
23
+ "NOTICE"
24
+ ],
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "scripts": {
29
+ "build": "tsup",
30
+ "dev": "tsx src/index.ts",
31
+ "typecheck": "tsc --noEmit",
32
+ "test": "vitest run",
33
+ "prepublishOnly": "npm run build"
34
+ },
35
+ "dependencies": {
36
+ "@modelcontextprotocol/sdk": "^1.0.4",
37
+ "jose": "^5.9.6",
38
+ "keytar": "^7.9.0",
39
+ "open": "^10.1.0",
40
+ "zod": "^3.23.8"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^20.14.0",
44
+ "tsup": "^8.3.5",
45
+ "tsx": "^4.19.2",
46
+ "typescript": "^5.6.3",
47
+ "vitest": "^2.1.8"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "license": "Apache-2.0",
53
+ "private": false
54
+ }