@neuctra/notlix-mcp 0.0.0-stage → 2.0.1
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/README.md +88 -2
- package/bin/notlix-mcp.js +87 -0
- package/package.json +38 -4
- package/src/authix.js +153 -0
- package/src/cli/prompt.js +27 -0
- package/src/cli/session.js +37 -0
- package/src/content.js +263 -0
- package/src/defaults.js +8 -0
- package/src/documents.js +133 -0
- package/src/http.js +24 -0
- package/src/index.js +8 -0
- package/src/server.js +229 -0
- package/src/shared/aiEdits.js +142 -0
- package/src/shared/contextPacks.js +133 -0
- package/src/shared/diagrams.js +451 -0
- package/src/shared/presentations.js +374 -0
- package/src/shared/records.js +32 -0
- package/src/shared/slideShapes.js +133 -0
- package/src/sharedText.js +61 -0
package/src/content.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { documentToReadable, editDocument, markdownToDocument } from "./documents.js";
|
|
2
|
+
import { editDiagram, editKnowledge, editNote, editPresentation } from "./shared/aiEdits.js";
|
|
3
|
+
import { DIAGRAM_SHAPES, boundsOf, createEdge, createNode, diagramText, normalizeDiagram } from "./shared/diagrams.js";
|
|
4
|
+
import { markdownToSlides, normalizeSlides, slidesText } from "./shared/presentations.js";
|
|
5
|
+
|
|
6
|
+
// The five content types an AI can manage, and how each is read, created and
|
|
7
|
+
// edited. Records are shaped exactly as the Notlix services write them
|
|
8
|
+
// (neuctra-notlix-client/services/*.service.js). None of these are encrypted;
|
|
9
|
+
// the vault (passwords, secure notes, API keys, files) is never touched.
|
|
10
|
+
|
|
11
|
+
export const TYPES = ["note", "knowledge", "document", "presentation", "diagram"];
|
|
12
|
+
|
|
13
|
+
export const TYPE_LABELS = {
|
|
14
|
+
note: "Notes",
|
|
15
|
+
knowledge: "Knowledge",
|
|
16
|
+
document: "Documents",
|
|
17
|
+
presentation: "Presentations",
|
|
18
|
+
diagram: "Diagrams",
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// From NOTE_CATEGORIES and DOCUMENT_CATEGORIES in the client services.
|
|
22
|
+
export const NOTE_CATEGORIES = ["general", "work", "personal", "learning", "ideas", "project", "meeting", "research", "journal"];
|
|
23
|
+
export const DOCUMENT_CATEGORIES = ["general", "work", "personal", "project", "meeting", "research"];
|
|
24
|
+
|
|
25
|
+
export const DIAGRAM_SHAPE_IDS = DIAGRAM_SHAPES.map((shape) => shape.id);
|
|
26
|
+
|
|
27
|
+
// Authix refuses saves over about 100 KB.
|
|
28
|
+
export const MAX_RECORD_BYTES = 100_000;
|
|
29
|
+
|
|
30
|
+
export class ContentError extends Error {
|
|
31
|
+
constructor(message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "ContentError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const now = () => new Date().toISOString();
|
|
38
|
+
|
|
39
|
+
// ---- Reading -----------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
function noteText(record) {
|
|
42
|
+
if (typeof record.content === "string") return record.content;
|
|
43
|
+
return (Array.isArray(record.content) ? record.content : [])
|
|
44
|
+
.map((block) => (typeof block?.content === "string" ? block.content : ""))
|
|
45
|
+
.filter(Boolean)
|
|
46
|
+
.join("\n\n");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function slidesToReadable(slides) {
|
|
50
|
+
return normalizeSlides(slides)
|
|
51
|
+
.map((slide, index) => {
|
|
52
|
+
const lines = [`<!-- slide ${index + 1} -->`];
|
|
53
|
+
for (const element of slide.elements) {
|
|
54
|
+
if (element.rows) lines.push(...element.rows.map((row) => `| ${row.join(" | ")} |`));
|
|
55
|
+
else if (typeof element.text === "string" && element.text.trim()) {
|
|
56
|
+
if (element.role === "title") lines.push(`# ${element.text}`);
|
|
57
|
+
else if (element.bullets) lines.push(...element.text.split("\n").map((line) => `- ${line}`));
|
|
58
|
+
else lines.push(element.text);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (slide.notes) lines.push(`Notes: ${slide.notes}`);
|
|
62
|
+
return lines.join("\n");
|
|
63
|
+
})
|
|
64
|
+
.join("\n\n---\n\n");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function diagramToReadable(record) {
|
|
68
|
+
const { nodes, edges } = normalizeDiagram(record);
|
|
69
|
+
const textOf = new Map(nodes.map((node) => [node.id, node.text || "(no text)"]));
|
|
70
|
+
const lines = ["Nodes:"];
|
|
71
|
+
for (const node of nodes) lines.push(`- [${node.id}] ${node.text || "(no text)"} (${node.shape})`);
|
|
72
|
+
lines.push("", "Connectors:");
|
|
73
|
+
for (const edge of edges) {
|
|
74
|
+
const label = edge.label ? `: ${edge.label}` : "";
|
|
75
|
+
lines.push(`- [${edge.from}] ${textOf.get(edge.from) ?? "?"} -> [${edge.to}] ${textOf.get(edge.to) ?? "?"}${label}`);
|
|
76
|
+
}
|
|
77
|
+
return lines.join("\n");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The item's content as text an AI can read. */
|
|
81
|
+
export function readableContent(type, record) {
|
|
82
|
+
switch (type) {
|
|
83
|
+
case "note":
|
|
84
|
+
return noteText(record);
|
|
85
|
+
case "knowledge":
|
|
86
|
+
return typeof record.content === "string" ? record.content : "";
|
|
87
|
+
case "document":
|
|
88
|
+
return documentToReadable(record.html);
|
|
89
|
+
case "presentation":
|
|
90
|
+
return slidesToReadable(record.slides);
|
|
91
|
+
case "diagram":
|
|
92
|
+
return diagramToReadable(record);
|
|
93
|
+
default:
|
|
94
|
+
return "";
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Text to search in: the title plus whatever the item says. */
|
|
99
|
+
export function searchableText(type, record) {
|
|
100
|
+
const body =
|
|
101
|
+
type === "note" ? noteText(record) : type === "knowledge" ? record.content : record.text;
|
|
102
|
+
return `${record.title || ""} ${typeof body === "string" ? body : ""}`.toLowerCase();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ---- Diagrams from a simple description -------------------------------------
|
|
106
|
+
|
|
107
|
+
const GAP_X = 220;
|
|
108
|
+
const GAP_Y = 160;
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Lays nodes out in rows, top to bottom, following the connectors. `nodes` use
|
|
112
|
+
* the AI's own keys; edges name those keys (or existing node ids). Returns the
|
|
113
|
+
* created nodes and edges, with keys mapped to real ids.
|
|
114
|
+
*/
|
|
115
|
+
function layOut(newNodes, newEdges, { existing = [], top = 0 } = {}) {
|
|
116
|
+
const keys = newNodes.map((node) => String(node.id));
|
|
117
|
+
if (new Set(keys).size !== keys.length) throw new ContentError("Each node needs its own id.");
|
|
118
|
+
|
|
119
|
+
const existingIds = new Set(existing.map((node) => node.id));
|
|
120
|
+
const isNew = new Set(keys);
|
|
121
|
+
for (const edge of newEdges) {
|
|
122
|
+
for (const end of [edge.from, edge.to]) {
|
|
123
|
+
if (!isNew.has(String(end)) && !existingIds.has(String(end))) {
|
|
124
|
+
throw new ContentError(`A connector names "${end}", which isn't a node id.`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Each new node's row is one below the deepest new node pointing at it.
|
|
130
|
+
const level = new Map(keys.map((key) => [key, 0]));
|
|
131
|
+
for (let pass = 0; pass < keys.length; pass += 1) {
|
|
132
|
+
let changed = false;
|
|
133
|
+
for (const { from, to } of newEdges) {
|
|
134
|
+
const a = String(from);
|
|
135
|
+
const b = String(to);
|
|
136
|
+
if (isNew.has(a) && isNew.has(b) && level.get(b) < level.get(a) + 1 && level.get(a) + 1 < keys.length) {
|
|
137
|
+
level.set(b, level.get(a) + 1);
|
|
138
|
+
changed = true;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (!changed) break;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const rows = [];
|
|
145
|
+
for (const node of newNodes) {
|
|
146
|
+
const row = level.get(String(node.id));
|
|
147
|
+
(rows[row] ||= []).push(node);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const ids = new Map();
|
|
151
|
+
const nodes = [];
|
|
152
|
+
rows.filter(Boolean).forEach((row, rowIndex) => {
|
|
153
|
+
row.forEach((node, index) => {
|
|
154
|
+
const x = (index - (row.length - 1) / 2) * GAP_X;
|
|
155
|
+
const created = createNode(node.shape || "rect", x, top + rowIndex * GAP_Y, { text: String(node.text || "") });
|
|
156
|
+
ids.set(String(node.id), created.id);
|
|
157
|
+
nodes.push(created);
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const edges = newEdges.map((edge) =>
|
|
162
|
+
createEdge(ids.get(String(edge.from)) ?? String(edge.from), ids.get(String(edge.to)) ?? String(edge.to), {
|
|
163
|
+
label: String(edge.label || ""),
|
|
164
|
+
}),
|
|
165
|
+
);
|
|
166
|
+
return { nodes, edges };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ---- Creating ----------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
/** The record to save for a new item. */
|
|
172
|
+
export function newRecord(type, { title, content = "", category, diagram }) {
|
|
173
|
+
const created = now();
|
|
174
|
+
const base = { title: title.trim(), isPinned: false, createdAt: created, updatedAt: created };
|
|
175
|
+
|
|
176
|
+
switch (type) {
|
|
177
|
+
case "note":
|
|
178
|
+
return {
|
|
179
|
+
...base,
|
|
180
|
+
content: content.trim() ? [{ id: `blk_${Date.now()}`, type: "text", content: content.trim() }] : [],
|
|
181
|
+
category: NOTE_CATEGORIES.includes(category) ? category : "general",
|
|
182
|
+
};
|
|
183
|
+
case "knowledge":
|
|
184
|
+
return { ...base, content };
|
|
185
|
+
case "document":
|
|
186
|
+
return {
|
|
187
|
+
...base,
|
|
188
|
+
...markdownToDocument(content),
|
|
189
|
+
category: DOCUMENT_CATEGORIES.includes(category) ? category : "general",
|
|
190
|
+
};
|
|
191
|
+
case "presentation": {
|
|
192
|
+
const slides = markdownToSlides(content || `# ${title}`);
|
|
193
|
+
return { ...base, themeId: "paper", slides, text: slidesText(slides) };
|
|
194
|
+
}
|
|
195
|
+
case "diagram": {
|
|
196
|
+
if (!diagram?.nodes?.length) throw new ContentError("A diagram needs at least one node in diagram.nodes.");
|
|
197
|
+
const { nodes, edges } = layOut(diagram.nodes, diagram.edges || []);
|
|
198
|
+
return { ...base, themeId: "paper", nodes, edges, text: diagramText({ nodes, edges }) };
|
|
199
|
+
}
|
|
200
|
+
default:
|
|
201
|
+
throw new ContentError(`Unknown type "${type}".`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---- Editing -----------------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The fields to change on an existing item. `edits` are find-and-replace pairs
|
|
209
|
+
* on its text, `append` is added at the end, `diagram` adds nodes and
|
|
210
|
+
* connectors. Returns `{ changes, missed }`; missed lists finds that didn't match.
|
|
211
|
+
*/
|
|
212
|
+
export function editRecord(type, record, { title, edits = [], append = "", diagram }) {
|
|
213
|
+
const request = { edits, append: String(append || "") };
|
|
214
|
+
let result;
|
|
215
|
+
|
|
216
|
+
switch (type) {
|
|
217
|
+
case "note":
|
|
218
|
+
result = editNote(record, request);
|
|
219
|
+
break;
|
|
220
|
+
case "knowledge":
|
|
221
|
+
result = editKnowledge(record, request);
|
|
222
|
+
break;
|
|
223
|
+
case "document":
|
|
224
|
+
result = editDocument(record, request);
|
|
225
|
+
break;
|
|
226
|
+
case "presentation":
|
|
227
|
+
result = editPresentation(record, request);
|
|
228
|
+
result.changes.text = slidesText(result.changes.slides);
|
|
229
|
+
break;
|
|
230
|
+
case "diagram": {
|
|
231
|
+
if (request.append.trim()) {
|
|
232
|
+
throw new ContentError("Diagrams can't take appended text. Use diagram.nodes and diagram.edges to add to one.");
|
|
233
|
+
}
|
|
234
|
+
result = editDiagram(record, request);
|
|
235
|
+
if (diagram?.nodes?.length || diagram?.edges?.length) {
|
|
236
|
+
const { nodes, edges } = result.changes;
|
|
237
|
+
const bounds = boundsOf(nodes);
|
|
238
|
+
const top = nodes.length ? bounds.y + bounds.h + GAP_Y : 0;
|
|
239
|
+
const added = layOut(diagram.nodes || [], diagram.edges || [], { existing: nodes, top });
|
|
240
|
+
result.changes.nodes = [...nodes, ...added.nodes];
|
|
241
|
+
result.changes.edges = [...edges, ...added.edges];
|
|
242
|
+
}
|
|
243
|
+
result.changes.text = diagramText(result.changes);
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
default:
|
|
247
|
+
throw new ContentError(`Unknown type "${type}".`);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (title !== undefined) result.changes.title = title.trim();
|
|
251
|
+
result.changes.updatedAt = now();
|
|
252
|
+
return result;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Throws when a record is too big for Authix to accept. */
|
|
256
|
+
export function checkSize(record) {
|
|
257
|
+
const bytes = new TextEncoder().encode(JSON.stringify(record)).length;
|
|
258
|
+
if (bytes > MAX_RECORD_BYTES) {
|
|
259
|
+
throw new ContentError(
|
|
260
|
+
`That's too big for one Notlix item (${Math.round(bytes / 1000)} KB, the limit is about 100 KB). Split it into smaller items.`,
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
}
|
package/src/defaults.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Written by scripts/sync.mjs from the website's public settings.
|
|
2
|
+
|
|
3
|
+
export default {
|
|
4
|
+
"authixUrl": "https://server.authix.neuctra.com/api",
|
|
5
|
+
"publishableKey": "pk_live_d992acbc_94a61ccb2354550f205674733b5e77bb7e3e51774d4544fd",
|
|
6
|
+
"appId": "7870561b328f8fb3a5beec64fbb81443",
|
|
7
|
+
"origin": "https://notlix.neuctra.com"
|
|
8
|
+
};
|
package/src/documents.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { Marked } from "marked";
|
|
2
|
+
import { parseHTML } from "linkedom";
|
|
3
|
+
|
|
4
|
+
// Documents are stored as HTML for the Notlix document editor. The website
|
|
5
|
+
// converts AI markdown in the browser (cms-core + DOMPurify); there is no DOM
|
|
6
|
+
// here, so this builds the HTML itself and never lets raw HTML through: tags an
|
|
7
|
+
// AI writes are shown as text, and only http(s) and mailto links are kept.
|
|
8
|
+
|
|
9
|
+
const escapeHtml = (text) =>
|
|
10
|
+
String(text).replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]);
|
|
11
|
+
|
|
12
|
+
const SAFE_URL = /^(https?:|mailto:)/i;
|
|
13
|
+
|
|
14
|
+
const marked = new Marked({
|
|
15
|
+
gfm: true,
|
|
16
|
+
renderer: {
|
|
17
|
+
html({ text }) {
|
|
18
|
+
return escapeHtml(text);
|
|
19
|
+
},
|
|
20
|
+
link({ href, title, tokens }) {
|
|
21
|
+
const label = this.parser.parseInline(tokens);
|
|
22
|
+
if (!SAFE_URL.test(String(href).trim())) return label;
|
|
23
|
+
const titleAttr = title ? ` title="${escapeHtml(title)}"` : "";
|
|
24
|
+
return `<a href="${escapeHtml(href)}"${titleAttr} target="_blank" rel="noopener noreferrer">${label}</a>`;
|
|
25
|
+
},
|
|
26
|
+
image({ href, text }) {
|
|
27
|
+
if (!/^https?:/i.test(String(href).trim())) return escapeHtml(text || "");
|
|
28
|
+
return `<img src="${escapeHtml(href)}" alt="${escapeHtml(text || "")}">`;
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
function bodyOf(html) {
|
|
34
|
+
return parseHTML(`<!doctype html><html><body>${html}</body></html>`).document.body;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Plain text of some HTML, for card previews and search. */
|
|
38
|
+
export function htmlToText(html) {
|
|
39
|
+
return bodyOf(String(html || "")).textContent || "";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `{ html, text }` for a document, from markdown. */
|
|
43
|
+
export function markdownToDocument(markdown) {
|
|
44
|
+
const html = marked.parse(String(markdown || ""), { async: false });
|
|
45
|
+
return { html, text: htmlToText(html) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const BLOCKS = new Set(["P", "DIV", "SECTION", "ARTICLE", "HEADER", "FOOTER", "FIGURE", "FIGCAPTION", "UL", "OL", "TABLE", "HR"]);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A readable, markdown-like view of a document for an AI. Headings get #,
|
|
52
|
+
* list items get -, tables become rows of |. Bold and links are left as plain
|
|
53
|
+
* words, which is also how a find must be written to match.
|
|
54
|
+
*/
|
|
55
|
+
export function documentToReadable(html) {
|
|
56
|
+
const out = [];
|
|
57
|
+
const walk = (node, listIndex = null) => {
|
|
58
|
+
if (node.nodeType === 3) {
|
|
59
|
+
out.push(node.nodeValue.replace(/\s+/g, " "));
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (node.nodeType !== 1) return;
|
|
63
|
+
const tag = node.tagName;
|
|
64
|
+
const children = (index) => node.childNodes.forEach((child) => walk(child, index));
|
|
65
|
+
|
|
66
|
+
if (/^H[1-6]$/.test(tag)) {
|
|
67
|
+
out.push(`\n\n${"#".repeat(Number(tag[1]))} `);
|
|
68
|
+
children();
|
|
69
|
+
out.push("\n\n");
|
|
70
|
+
} else if (tag === "BR") out.push("\n");
|
|
71
|
+
else if (tag === "LI") {
|
|
72
|
+
out.push(listIndex === null ? "\n- " : `\n${listIndex}. `);
|
|
73
|
+
children();
|
|
74
|
+
} else if (tag === "OL") {
|
|
75
|
+
out.push("\n");
|
|
76
|
+
let index = 0;
|
|
77
|
+
node.childNodes.forEach((child) => walk(child, child.tagName === "LI" ? (index += 1) : null));
|
|
78
|
+
out.push("\n");
|
|
79
|
+
} else if (tag === "PRE") out.push(`\n\n\`\`\`\n${node.textContent}\n\`\`\`\n\n`);
|
|
80
|
+
else if (tag === "BLOCKQUOTE") out.push(`\n\n> ${node.textContent.trim().replace(/\n+/g, "\n> ")}\n\n`);
|
|
81
|
+
else if (tag === "TR") {
|
|
82
|
+
out.push("\n|");
|
|
83
|
+
node.childNodes.forEach((cell) => {
|
|
84
|
+
if (cell.nodeType === 1) out.push(` ${cell.textContent.trim()} |`);
|
|
85
|
+
});
|
|
86
|
+
} else if (tag === "IMG") out.push(`[image${node.getAttribute("alt") ? `: ${node.getAttribute("alt")}` : ""}]`);
|
|
87
|
+
else if (tag === "HR") out.push("\n\n---\n\n");
|
|
88
|
+
else if (BLOCKS.has(tag)) {
|
|
89
|
+
out.push("\n\n");
|
|
90
|
+
children();
|
|
91
|
+
out.push("\n\n");
|
|
92
|
+
} else children();
|
|
93
|
+
};
|
|
94
|
+
bodyOf(String(html || "")).childNodes.forEach((node) => walk(node));
|
|
95
|
+
return out
|
|
96
|
+
.join("")
|
|
97
|
+
.replace(/[ \t]+\n/g, "\n")
|
|
98
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
99
|
+
.trim();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const replaceAll = (text, find, replace) => text.split(find).join(replace);
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Applies find-and-replace edits to a document's text nodes only, so edits
|
|
106
|
+
* can't add markup, and appends markdown at the end. Returns
|
|
107
|
+
* `{ changes: { html, text }, missed }`, like the website's editDocument.
|
|
108
|
+
*/
|
|
109
|
+
export function editDocument(record, { edits = [], append = "" }) {
|
|
110
|
+
const body = bodyOf(String(record.html || ""));
|
|
111
|
+
const textNodes = [];
|
|
112
|
+
const collect = (node) => {
|
|
113
|
+
if (node.nodeType === 3) textNodes.push(node);
|
|
114
|
+
node.childNodes?.forEach(collect);
|
|
115
|
+
};
|
|
116
|
+
collect(body);
|
|
117
|
+
|
|
118
|
+
const missed = [];
|
|
119
|
+
for (const { find, replace } of edits) {
|
|
120
|
+
let found = false;
|
|
121
|
+
for (const node of textNodes) {
|
|
122
|
+
if (node.nodeValue.includes(find)) {
|
|
123
|
+
node.nodeValue = replaceAll(node.nodeValue, find, replace);
|
|
124
|
+
found = true;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (!found) missed.push(find);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let html = body.innerHTML;
|
|
131
|
+
if (String(append).trim()) html += markdownToDocument(append).html;
|
|
132
|
+
return { changes: { html, text: htmlToText(html) }, missed };
|
|
133
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
2
|
+
|
|
3
|
+
import { createNotlixServer } from "./server.js";
|
|
4
|
+
|
|
5
|
+
// Remote MCP over Streamable HTTP with web-standard Request/Response, for
|
|
6
|
+
// Cloudflare Workers (neuctra-notlix-mcp-http). Signing the user in is the
|
|
7
|
+
// caller's job: pass an AuthixClient that already holds their session.
|
|
8
|
+
|
|
9
|
+
/** Answers one MCP request. Stateless: a new server and transport each time. */
|
|
10
|
+
export async function handleMcpRequest(request, { authix }) {
|
|
11
|
+
const server = createNotlixServer(authix);
|
|
12
|
+
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
13
|
+
sessionIdGenerator: undefined,
|
|
14
|
+
enableJsonResponse: true,
|
|
15
|
+
});
|
|
16
|
+
await server.connect(transport);
|
|
17
|
+
try {
|
|
18
|
+
return await transport.handleRequest(request);
|
|
19
|
+
} finally {
|
|
20
|
+
// JSON responses are complete once returned.
|
|
21
|
+
transport.close();
|
|
22
|
+
server.close();
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Works in Node and on Cloudflare Workers. The sign-in commands and session
|
|
2
|
+
// file are Node-only and live in src/cli/.
|
|
3
|
+
|
|
4
|
+
export { AuthixClient, AuthixError, SESSION_COOKIE, authixConfig } from "./authix.js";
|
|
5
|
+
export { ContentError, TYPES, TYPE_LABELS } from "./content.js";
|
|
6
|
+
export { markdownToDocument, documentToReadable } from "./documents.js";
|
|
7
|
+
export { VERSION, createNotlixServer } from "./server.js";
|
|
8
|
+
export { SHARE_TOKEN, sharedItemText } from "./sharedText.js";
|
package/src/server.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
import { AuthixError } from "./authix.js";
|
|
5
|
+
import {
|
|
6
|
+
ContentError,
|
|
7
|
+
DIAGRAM_SHAPE_IDS,
|
|
8
|
+
DOCUMENT_CATEGORIES,
|
|
9
|
+
NOTE_CATEGORIES,
|
|
10
|
+
TYPES,
|
|
11
|
+
TYPE_LABELS,
|
|
12
|
+
checkSize,
|
|
13
|
+
editRecord,
|
|
14
|
+
newRecord,
|
|
15
|
+
readableContent,
|
|
16
|
+
searchableText,
|
|
17
|
+
} from "./content.js";
|
|
18
|
+
|
|
19
|
+
// The Notlix MCP tools. Used by the local stdio command (bin/notlix-mcp.js) and
|
|
20
|
+
// the remote Worker (neuctra-notlix-mcp-http). Every call acts as the signed-in
|
|
21
|
+
// user through Authix. Nothing can be deleted, and the vault is out of reach.
|
|
22
|
+
|
|
23
|
+
export const VERSION = "2.0.0";
|
|
24
|
+
|
|
25
|
+
const type = z.enum(TYPES).describe('"note", "knowledge", "document", "presentation" or "diagram".');
|
|
26
|
+
const id = z.string().trim().min(1).max(100).describe("The item's id, from list_notlix_items.");
|
|
27
|
+
const title = z.string().trim().min(1).max(200);
|
|
28
|
+
|
|
29
|
+
const diagramNode = z.object({
|
|
30
|
+
id: z.string().trim().min(1).max(60).describe("Your own key for this node, used by connectors."),
|
|
31
|
+
text: z.string().max(500).describe("The text in the box."),
|
|
32
|
+
shape: z.enum(DIAGRAM_SHAPE_IDS).optional().describe(`Default "rect". Flowchart: rect, terminator, diamond, parallelogram, documentShape, subroutine, hexagon. Others: roundRect, ellipse, triangle, note, text, cylinder (database), cloud, container.`),
|
|
33
|
+
});
|
|
34
|
+
const diagramEdge = z.object({
|
|
35
|
+
from: z.string().trim().min(1).max(60).describe("A node key, or an existing node id when editing."),
|
|
36
|
+
to: z.string().trim().min(1).max(60),
|
|
37
|
+
label: z.string().max(200).optional(),
|
|
38
|
+
});
|
|
39
|
+
const diagramInput = z
|
|
40
|
+
.object({
|
|
41
|
+
nodes: z.array(diagramNode).max(150).default([]),
|
|
42
|
+
edges: z.array(diagramEdge).max(300).default([]),
|
|
43
|
+
})
|
|
44
|
+
.describe("Diagrams only: boxes and the connectors between them. They're laid out top to bottom for you.");
|
|
45
|
+
|
|
46
|
+
const FORMATS = `Formats by type:
|
|
47
|
+
- note: plain text.
|
|
48
|
+
- knowledge: markdown. [[Title]] links to another Knowledge item.
|
|
49
|
+
- document: markdown, turned into a formatted document. Raw HTML is shown as text.
|
|
50
|
+
- presentation: markdown with --- on its own line between slides. Start each slide with a # title, then short - bullets (about six per slide), and end a slide with a line starting Notes: for speaker notes. Images aren't supported.
|
|
51
|
+
- diagram: no content; use diagram.nodes and diagram.edges.`;
|
|
52
|
+
|
|
53
|
+
const ok = (text) => ({ content: [{ type: "text", text }] });
|
|
54
|
+
const refuse = (text) => ({ isError: true, content: [{ type: "text", text }] });
|
|
55
|
+
|
|
56
|
+
/** Turns expected failures into tool errors the AI can pass on. */
|
|
57
|
+
const guarded = (handler) => async (args) => {
|
|
58
|
+
try {
|
|
59
|
+
return await handler(args);
|
|
60
|
+
} catch (err) {
|
|
61
|
+
if (err instanceof AuthixError || err instanceof ContentError) return refuse(err.message);
|
|
62
|
+
throw err;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const day = (value) => (value ? String(value).slice(0, 10) : "unknown");
|
|
67
|
+
const shorten = (text, max) => (text.length > max ? `${text.slice(0, max).trimEnd()}…` : text);
|
|
68
|
+
|
|
69
|
+
/** An MCP server for one signed-in user. `authix` is an AuthixClient with a session. */
|
|
70
|
+
export function createNotlixServer(authix) {
|
|
71
|
+
const server = new McpServer({ name: "neuctra-notlix", version: VERSION });
|
|
72
|
+
|
|
73
|
+
async function findItem(itemType, itemId) {
|
|
74
|
+
const record = (await authix.list(itemType)).find((item) => item.id === itemId);
|
|
75
|
+
if (!record) {
|
|
76
|
+
throw new ContentError(`No ${itemType} with id ${itemId} in ${TYPE_LABELS[itemType]}. Use list_notlix_items to find it.`);
|
|
77
|
+
}
|
|
78
|
+
return record;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
server.registerTool(
|
|
82
|
+
"list_notlix_items",
|
|
83
|
+
{
|
|
84
|
+
title: "List Notlix items",
|
|
85
|
+
description:
|
|
86
|
+
"List or search the user's Notes, Knowledge, Documents, Presentations and Diagrams in Neuctra Notlix. Returns ids, titles and dates, newest first. Use read_notlix_item to read one. The vault (passwords, secure notes, API keys, files) isn't available.",
|
|
87
|
+
inputSchema: {
|
|
88
|
+
type: type.optional().describe("Only this type. Leave out for all five."),
|
|
89
|
+
query: z.string().trim().max(200).optional().describe("Words that must all appear in the title or text."),
|
|
90
|
+
limit: z.number().int().min(1).max(200).default(50),
|
|
91
|
+
},
|
|
92
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
93
|
+
},
|
|
94
|
+
guarded(async ({ type: only, query, limit }) => {
|
|
95
|
+
const types = only ? [only] : TYPES;
|
|
96
|
+
const words = (query || "").toLowerCase().split(/\s+/).filter(Boolean);
|
|
97
|
+
const found = [];
|
|
98
|
+
for (const itemType of types) {
|
|
99
|
+
for (const record of await authix.list(itemType)) {
|
|
100
|
+
const text = searchableText(itemType, record);
|
|
101
|
+
if (words.every((word) => text.includes(word))) found.push({ itemType, record });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
found.sort(
|
|
105
|
+
(a, b) =>
|
|
106
|
+
Number(Boolean(b.record.isPinned)) - Number(Boolean(a.record.isPinned)) ||
|
|
107
|
+
String(b.record.updatedAt || "").localeCompare(String(a.record.updatedAt || "")),
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
if (found.length === 0) return ok(query ? `Nothing matches "${query}".` : "No items yet.");
|
|
111
|
+
const lines = found.slice(0, limit).map(({ itemType, record }) => {
|
|
112
|
+
const pin = record.isPinned ? " (pinned)" : "";
|
|
113
|
+
return `- ${itemType} ${record.id}: "${record.title || "Untitled"}"${pin}, updated ${day(record.updatedAt)}`;
|
|
114
|
+
});
|
|
115
|
+
const more = found.length > limit ? `\n${found.length - limit} more. Narrow it with type or query.` : "";
|
|
116
|
+
return ok(`${found.length} ${found.length === 1 ? "item" : "items"}:\n${lines.join("\n")}${more}`);
|
|
117
|
+
}),
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
server.registerTool(
|
|
121
|
+
"read_notlix_item",
|
|
122
|
+
{
|
|
123
|
+
title: "Read a Notlix item",
|
|
124
|
+
description:
|
|
125
|
+
"Read one item from Neuctra Notlix in full. Documents and presentations are shown as markdown-like text: # marks headings and slide titles, - marks bullets, and --- separates slides. Diagrams list their nodes and connectors with ids.",
|
|
126
|
+
inputSchema: { type, id },
|
|
127
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
128
|
+
},
|
|
129
|
+
guarded(async ({ type: itemType, id: itemId }) => {
|
|
130
|
+
const record = await findItem(itemType, itemId);
|
|
131
|
+
const meta = [`Type: ${itemType}`, `Id: ${record.id}`, `Updated: ${day(record.updatedAt)}`];
|
|
132
|
+
if (record.category) meta.push(`Category: ${record.category}`);
|
|
133
|
+
return ok(`# ${record.title || "Untitled"}\n${meta.join(" · ")}\n\n${readableContent(itemType, record)}`);
|
|
134
|
+
}),
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
server.registerTool(
|
|
138
|
+
"create_notlix_item",
|
|
139
|
+
{
|
|
140
|
+
title: "Create a Notlix item",
|
|
141
|
+
description: `Create a new Note, Knowledge item, Document, Presentation or Diagram in the user's Neuctra Notlix account. Write a clear title and content that makes sense on its own, without this chat.
|
|
142
|
+
|
|
143
|
+
${FORMATS}
|
|
144
|
+
|
|
145
|
+
Never save passwords, API keys or other secrets: these items aren't encrypted. Secrets belong in the Notlix vault, which this can't reach.`,
|
|
146
|
+
inputSchema: {
|
|
147
|
+
type,
|
|
148
|
+
title: title.describe("Short, descriptive title."),
|
|
149
|
+
content: z.string().max(200_000).default("").describe("The body, in the format for its type."),
|
|
150
|
+
category: z
|
|
151
|
+
.string()
|
|
152
|
+
.optional()
|
|
153
|
+
.describe(`Notes: ${NOTE_CATEGORIES.join(", ")}. Documents: ${DOCUMENT_CATEGORIES.join(", ")}. Default "general".`),
|
|
154
|
+
diagram: diagramInput.optional(),
|
|
155
|
+
},
|
|
156
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
157
|
+
},
|
|
158
|
+
guarded(async (args) => {
|
|
159
|
+
if (args.type !== "diagram" && !args.content.trim()) return refuse("Give some content to save.");
|
|
160
|
+
const record = newRecord(args.type, args);
|
|
161
|
+
checkSize(record);
|
|
162
|
+
const saved = await authix.add(args.type, record);
|
|
163
|
+
const savedId = saved?.id ? ` Its id is ${saved.id}.` : "";
|
|
164
|
+
return ok(`Created "${record.title}" in ${TYPE_LABELS[args.type]}.${savedId}`);
|
|
165
|
+
}),
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
server.registerTool(
|
|
169
|
+
"edit_notlix_item",
|
|
170
|
+
{
|
|
171
|
+
title: "Edit a Notlix item",
|
|
172
|
+
description: `Change an existing item in Neuctra Notlix: rename it, fix or reword text, add content at the end, or add to a diagram. Read it first with read_notlix_item. Items can't be deleted.
|
|
173
|
+
|
|
174
|
+
- edits: each find is copied exactly from the item's current text and replaced with replace. Every occurrence is replaced, so include enough words to match only the place you mean. For documents, copy words as they read, without # or - markers, and keep each find inside one paragraph and one style (a find can't cross bold or a link). For presentations, keep each find inside one bullet, table cell or notes field; for diagrams, inside one node or connector label. replace is plain text.
|
|
175
|
+
- append: new content at the end, in the format for the type (see create_notlix_item). Presentations get new slides. Diagrams can't take append; use diagram instead.
|
|
176
|
+
- diagram: new nodes and connectors to add. Connectors can name existing node ids from read_notlix_item.
|
|
177
|
+
|
|
178
|
+
Finds that don't match are listed in the answer, and nothing else is guessed.`,
|
|
179
|
+
inputSchema: {
|
|
180
|
+
type,
|
|
181
|
+
id,
|
|
182
|
+
title: title.optional().describe("A new title."),
|
|
183
|
+
edits: z
|
|
184
|
+
.array(
|
|
185
|
+
z.object({
|
|
186
|
+
find: z.string().min(1).max(10_000).describe("Exact text currently in the item."),
|
|
187
|
+
replace: z.string().max(50_000).describe("The text to put in its place."),
|
|
188
|
+
}),
|
|
189
|
+
)
|
|
190
|
+
.max(50)
|
|
191
|
+
.optional(),
|
|
192
|
+
append: z.string().max(200_000).optional().describe("New content to add at the end."),
|
|
193
|
+
diagram: diagramInput.optional(),
|
|
194
|
+
},
|
|
195
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
196
|
+
},
|
|
197
|
+
guarded(async ({ type: itemType, id: itemId, title: newTitle, edits = [], append = "", diagram }) => {
|
|
198
|
+
const addsToDiagram = Boolean(diagram?.nodes?.length || diagram?.edges?.length);
|
|
199
|
+
if (!newTitle && edits.length === 0 && !append.trim() && !addsToDiagram) {
|
|
200
|
+
return refuse("Nothing to change. Give a title, edits, append or diagram.");
|
|
201
|
+
}
|
|
202
|
+
if (edits.some(({ find, replace }) => find === replace)) {
|
|
203
|
+
return refuse("An edit's find and replace are the same, so it wouldn't change anything.");
|
|
204
|
+
}
|
|
205
|
+
if (diagram && itemType !== "diagram") return refuse("diagram only works on diagrams.");
|
|
206
|
+
|
|
207
|
+
const record = await findItem(itemType, itemId);
|
|
208
|
+
const { changes, missed } = editRecord(itemType, record, { title: newTitle, edits, append, diagram });
|
|
209
|
+
if (missed.length === edits.length && edits.length > 0 && !newTitle && !append.trim() && !addsToDiagram) {
|
|
210
|
+
return refuse(`None of the finds matched the text of "${record.title}": ${missed.map((find) => `"${shorten(find, 60)}"`).join(", ")}. Read the item again and copy the text exactly.`);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
checkSize({ ...record, ...changes });
|
|
214
|
+
await authix.update(record.id, changes);
|
|
215
|
+
|
|
216
|
+
const done = [];
|
|
217
|
+
if (newTitle) done.push("renamed it");
|
|
218
|
+
if (edits.length > missed.length) done.push(`applied ${edits.length - missed.length} of ${edits.length} ${edits.length === 1 ? "edit" : "edits"}`);
|
|
219
|
+
if (append.trim()) done.push("added content at the end");
|
|
220
|
+
if (addsToDiagram) done.push(`added ${diagram.nodes?.length || 0} nodes and ${diagram.edges?.length || 0} connectors`);
|
|
221
|
+
const skipped = missed.length
|
|
222
|
+
? ` These finds didn't match and were skipped: ${missed.map((find) => `"${shorten(find, 60)}"`).join(", ")}.`
|
|
223
|
+
: "";
|
|
224
|
+
return ok(`Updated "${changes.title || record.title}": ${done.join(", ")}.${skipped}`);
|
|
225
|
+
}),
|
|
226
|
+
);
|
|
227
|
+
|
|
228
|
+
return server;
|
|
229
|
+
}
|