@n6k.io/serve 0.2.0 → 0.2.3
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 +21 -3
- package/package.json +6 -4
- package/src/assets.ts +0 -1
- package/src/bundle.ts +3 -3
- package/src/cli.ts +53 -16
- package/src/component-docs.ts +63 -0
- package/src/css.ts +1 -1
- package/src/data-args.test.ts +27 -5
- package/src/data-args.ts +28 -5
- package/src/mcp-instructions.ts +22 -0
- package/src/mcp.test.ts +227 -0
- package/src/mcp.ts +268 -0
- package/src/mdx-components.tsx +14 -5
- package/src/pages-site.ts +6 -14
- package/src/pages.ts +1 -1
- package/src/root.tsx +20 -21
- package/src/server.ts +6 -65
- package/src/sql/console.mdx +1 -0
- package/src/sql/editor.mdx +1 -0
- package/src/virtual-modules.d.ts +2 -2
package/README.md
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
# @n6k.io/serve
|
|
2
2
|
|
|
3
|
-
Serve
|
|
3
|
+
Serve `.mdx` pages in the browser with live data from
|
|
4
4
|
[n6kd](https://github.com/n6k-io/n6kd) or pykit `n6k database`.
|
|
5
5
|
|
|
6
6
|
```sh
|
|
7
7
|
n6k-serve page.mdx # no data
|
|
8
8
|
n6k-serve page.mdx --data ws://localhost:8080/ws # attached as `db`
|
|
9
9
|
n6k-serve page.mdx --data nyc=ws://localhost:8080/ws --data sales=ws://localhost:7823/ws
|
|
10
|
+
n6k-serve page.mdx --data nyc=ws://<token>@localhost:8080/ws # token sent to the server
|
|
10
11
|
n6k-serve page.mdx --port 3000 # default 3000
|
|
11
12
|
```
|
|
12
13
|
|
|
14
|
+
A token in `--data` is removed from the URL and sent as the connection token.
|
|
15
|
+
Frontmatter `attach:` URLs may not carry one.
|
|
16
|
+
|
|
13
17
|
Or in the page's frontmatter (`--data` wins for the same alias):
|
|
14
18
|
|
|
15
19
|
```yaml
|
|
@@ -23,5 +27,19 @@ attach:
|
|
|
23
27
|
The alias is the catalog name on the server: `nyc=ws://…` attaches the
|
|
24
28
|
server's `nyc` catalog as `nyc`. A bare URL attaches the server's `db` catalog.
|
|
25
29
|
|
|
26
|
-
Every `@n6k.io/ui` component is available in the page without an
|
|
27
|
-
|
|
30
|
+
Every `@n6k.io/ui` component and control is available in the page without an
|
|
31
|
+
import. Controls are declared with directives, e.g.
|
|
32
|
+
`::Slider[n]{label="N" min=1 max=10 default=5}`, and read as `{n}`. The page
|
|
33
|
+
reloads when the file is saved.
|
|
34
|
+
|
|
35
|
+
## MCP
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
claude mcp add n6k-serve -- bunx @n6k.io/serve --mcp
|
|
39
|
+
claude mcp add n6k-serve -- bunx @n6k.io/serve --mcp --port 4000
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`--mcp` serves pages at `/<page>/` and is driven over stdio by one MCP client.
|
|
43
|
+
It takes `--port`, `--host` and `--origin`, not `--data` or `--pages`. Data
|
|
44
|
+
sources and pages are set with MCP tools (see `tools/list`); frontmatter
|
|
45
|
+
`attach:` is ignored. The process exits when stdin closes.
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n6k.io/serve",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"private": false,
|
|
5
|
-
"description": "Serve
|
|
5
|
+
"description": "Serve .mdx pages with live data from n6kd or pykit",
|
|
6
6
|
"repository": "https://github.com/n6k-io/js-serve",
|
|
7
7
|
"license": "MIT",
|
|
8
8
|
"type": "module",
|
|
@@ -24,10 +24,11 @@
|
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"@duckdb/duckdb-wasm": "1.33.1-dev114.0",
|
|
27
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
27
28
|
"@n6k.io/build": "^0.5.1",
|
|
28
29
|
"@n6k.io/db": "^0.13.1",
|
|
29
30
|
"@n6k.io/runtime": "^0.1.2",
|
|
30
|
-
"@n6k.io/ui": "^0.10.
|
|
31
|
+
"@n6k.io/ui": "^0.10.6",
|
|
31
32
|
"@tailwindcss/cli": "^4.3.3",
|
|
32
33
|
"@tailwindcss/typography": "^0.5.20",
|
|
33
34
|
"@tanstack/react-query": "^5.104.1",
|
|
@@ -37,7 +38,8 @@
|
|
|
37
38
|
"react-dom": "^19.3.0",
|
|
38
39
|
"shadcn": "^4.21.4",
|
|
39
40
|
"tailwindcss": "^4.3.3",
|
|
40
|
-
"tw-animate-css": "^1.4.0"
|
|
41
|
+
"tw-animate-css": "^1.4.0",
|
|
42
|
+
"zod": "^4"
|
|
41
43
|
},
|
|
42
44
|
"devDependencies": {
|
|
43
45
|
"@eslint/js": "^10.0.1",
|
package/src/assets.ts
CHANGED
|
@@ -30,7 +30,6 @@ function mime(file: string): string {
|
|
|
30
30
|
return N6K_WASM_MIME[path.extname(file)] ?? "application/octet-stream";
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
// duckdb runtime, n6k driver workers, n6k duckdb extensions and fontsource fonts; undefined if `pathname` is none of them.
|
|
34
33
|
export async function serveAsset(
|
|
35
34
|
pathname: string,
|
|
36
35
|
): Promise<Response | undefined> {
|
package/src/bundle.ts
CHANGED
|
@@ -16,9 +16,9 @@ import {
|
|
|
16
16
|
export type Bundle = Map<string, string>;
|
|
17
17
|
|
|
18
18
|
export type RootProps = {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
data: Record<string, string>;
|
|
20
|
+
tokens: Record<string, string>;
|
|
21
|
+
bare?: boolean;
|
|
22
22
|
};
|
|
23
23
|
|
|
24
24
|
export async function bundlePage(
|
package/src/cli.ts
CHANGED
|
@@ -3,7 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { existsSync, readFileSync } from "node:fs";
|
|
4
4
|
import { parseArgs } from "node:util";
|
|
5
5
|
import { parseAttachUrls } from "@n6k.io/build/pipeline";
|
|
6
|
-
import { DataArgError, resolveData } from "./data-args";
|
|
6
|
+
import { DataArgError, resolveData, type DataSource } from "./data-args";
|
|
7
7
|
import { bundlePage } from "./bundle";
|
|
8
8
|
import { buildCss } from "./css";
|
|
9
9
|
import { hasWasmExtensions } from "./assets";
|
|
@@ -18,9 +18,14 @@ import {
|
|
|
18
18
|
type Site,
|
|
19
19
|
} from "./server";
|
|
20
20
|
import { watchFile } from "./watch";
|
|
21
|
+
import { McpSite, startMcp } from "./mcp";
|
|
22
|
+
import { SRC_DIR } from "./paths";
|
|
23
|
+
import pkg from "../package.json";
|
|
21
24
|
|
|
22
25
|
const USAGE = `usage: n6k-serve <page.mdx> [--data [alias=]ws://…]... [options]
|
|
23
26
|
n6k-serve --pages <pages.yml> [options]
|
|
27
|
+
n6k-serve sql [--console] [--data [alias=]ws://…]... [options]
|
|
28
|
+
n6k-serve --mcp [options]
|
|
24
29
|
options: [--port 3000] [--host 127.0.0.1] [--origin <origin>]...`;
|
|
25
30
|
|
|
26
31
|
function fail(message: string): never {
|
|
@@ -33,6 +38,8 @@ const { values, positionals } = parseArgs({
|
|
|
33
38
|
options: {
|
|
34
39
|
data: { type: "string", multiple: true, default: [] },
|
|
35
40
|
pages: { type: "string" },
|
|
41
|
+
mcp: { type: "boolean", default: false },
|
|
42
|
+
console: { type: "boolean", default: false },
|
|
36
43
|
port: { type: "string", default: "3000" },
|
|
37
44
|
host: { type: "string", default: "127.0.0.1" },
|
|
38
45
|
origin: { type: "string", multiple: true, default: [] },
|
|
@@ -53,7 +60,24 @@ const options: ServeOptions = {
|
|
|
53
60
|
origins: values.origin,
|
|
54
61
|
};
|
|
55
62
|
|
|
56
|
-
if (values.
|
|
63
|
+
if (values.console && positionals[0] !== "sql") fail(USAGE);
|
|
64
|
+
|
|
65
|
+
if (positionals[0] === "sql") {
|
|
66
|
+
if (positionals.length !== 1 || values.mcp || values.pages !== undefined)
|
|
67
|
+
fail(USAGE);
|
|
68
|
+
await servePage(
|
|
69
|
+
path.join(SRC_DIR, "sql", values.console ? "console.mdx" : "editor.mdx"),
|
|
70
|
+
true,
|
|
71
|
+
);
|
|
72
|
+
} else if (values.mcp) {
|
|
73
|
+
if (
|
|
74
|
+
positionals.length > 0 ||
|
|
75
|
+
values.pages !== undefined ||
|
|
76
|
+
values.data.length > 0
|
|
77
|
+
)
|
|
78
|
+
fail(USAGE);
|
|
79
|
+
serveMcp();
|
|
80
|
+
} else if (values.pages === undefined) {
|
|
57
81
|
if (positionals.length !== 1) fail(USAGE);
|
|
58
82
|
await servePage(positionals[0]);
|
|
59
83
|
} else {
|
|
@@ -61,31 +85,38 @@ if (values.pages === undefined) {
|
|
|
61
85
|
servePages(values.pages);
|
|
62
86
|
}
|
|
63
87
|
|
|
64
|
-
async function servePage(arg: string): Promise<void> {
|
|
88
|
+
async function servePage(arg: string, bare = false): Promise<void> {
|
|
65
89
|
const mdxPath = path.resolve(arg);
|
|
66
90
|
if (!mdxPath.endsWith(".mdx")) fail(`${arg}: not an .mdx file`);
|
|
67
91
|
if (!existsSync(mdxPath)) fail(`${arg}: no such file`);
|
|
68
92
|
const dataFlags = values.data;
|
|
69
93
|
|
|
70
|
-
const resolveDataFor = (): Record<string,
|
|
94
|
+
const resolveDataFor = (): Record<string, DataSource> =>
|
|
71
95
|
resolveData(parseAttachUrls(readFileSync(mdxPath, "utf8")), dataFlags);
|
|
72
96
|
|
|
73
|
-
const build = async (
|
|
97
|
+
const build = async (
|
|
98
|
+
sources: Record<string, DataSource>,
|
|
99
|
+
): Promise<PageState> => {
|
|
100
|
+
const entries = Object.entries(sources);
|
|
74
101
|
const [bundle, css] = await Promise.all([
|
|
75
|
-
bundlePage(mdxPath, {
|
|
102
|
+
bundlePage(mdxPath, {
|
|
103
|
+
data: Object.fromEntries(entries.map(([a, s]) => [a, s.url])),
|
|
104
|
+
tokens: Object.fromEntries(entries.map(([a, s]) => [a, s.token])),
|
|
105
|
+
bare,
|
|
106
|
+
}),
|
|
76
107
|
buildCss(mdxPath),
|
|
77
108
|
]);
|
|
78
109
|
return { bundle, css };
|
|
79
110
|
};
|
|
80
111
|
|
|
81
|
-
let data: Record<string,
|
|
112
|
+
let data: Record<string, DataSource>;
|
|
82
113
|
try {
|
|
83
114
|
data = resolveDataFor();
|
|
84
115
|
} catch (err) {
|
|
85
116
|
if (err instanceof DataArgError) fail(err.message);
|
|
86
117
|
throw err;
|
|
87
118
|
}
|
|
88
|
-
let state = await build(
|
|
119
|
+
let state = await build(data);
|
|
89
120
|
const page: ServedPage = {
|
|
90
121
|
title: path.basename(mdxPath),
|
|
91
122
|
key: "",
|
|
@@ -94,22 +125,21 @@ async function servePage(arg: string): Promise<void> {
|
|
|
94
125
|
const site: Site = {
|
|
95
126
|
resolve: (pathname) => ({ kind: "page", page, rest: pathname }),
|
|
96
127
|
page: (key) => (key === "" ? page : undefined),
|
|
97
|
-
upstream: (alias) => data[alias],
|
|
98
128
|
};
|
|
99
129
|
const server = startServer(site, options);
|
|
100
130
|
|
|
101
|
-
console.
|
|
102
|
-
for (const [alias, url] of Object.entries(data)) {
|
|
103
|
-
console.
|
|
131
|
+
console.error(`n6k-serve ${server.url}`);
|
|
132
|
+
for (const [alias, { url }] of Object.entries(data)) {
|
|
133
|
+
console.error(` ${alias} → ${url}`);
|
|
104
134
|
}
|
|
105
135
|
|
|
106
136
|
watchFile(mdxPath, async () => {
|
|
107
137
|
try {
|
|
108
138
|
const nextData = resolveDataFor();
|
|
109
|
-
state = await build(
|
|
139
|
+
state = await build(nextData);
|
|
110
140
|
data = nextData;
|
|
111
141
|
reloadPage(server, "");
|
|
112
|
-
console.
|
|
142
|
+
console.error(`rebuilt ${path.basename(mdxPath)}`);
|
|
113
143
|
} catch (err) {
|
|
114
144
|
console.error(err instanceof Error ? err.message : String(err));
|
|
115
145
|
}
|
|
@@ -131,14 +161,21 @@ function servePages(arg: string): void {
|
|
|
131
161
|
const site = new PagesSite((key) => reloadPage(server, key));
|
|
132
162
|
site.update(config);
|
|
133
163
|
const server = startServer(site, options);
|
|
134
|
-
console.
|
|
164
|
+
console.error(`n6k-serve ${server.url}`);
|
|
135
165
|
|
|
136
166
|
watchFile(file, () => {
|
|
137
167
|
try {
|
|
138
168
|
site.update(load());
|
|
139
|
-
console.
|
|
169
|
+
console.error(`reloaded ${path.basename(file)}`);
|
|
140
170
|
} catch (err) {
|
|
141
171
|
console.error(err instanceof Error ? err.message : String(err));
|
|
142
172
|
}
|
|
143
173
|
});
|
|
144
174
|
}
|
|
175
|
+
|
|
176
|
+
function serveMcp(): void {
|
|
177
|
+
const site = new McpSite((key) => reloadPage(server, key));
|
|
178
|
+
const server = startServer(site, options);
|
|
179
|
+
console.error(`n6k-serve ${server.url}`);
|
|
180
|
+
startMcp(site, server, pkg.version, () => process.exit(0));
|
|
181
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import docs from "@n6k.io/ui/docs.json";
|
|
2
|
+
|
|
3
|
+
type Prop = { type: string; required: boolean; description: string };
|
|
4
|
+
type Doc = { description: string; file: string; props: Record<string, Prop> };
|
|
5
|
+
|
|
6
|
+
export type ComponentDoc = {
|
|
7
|
+
name: string;
|
|
8
|
+
kind: "component" | "control";
|
|
9
|
+
description: string;
|
|
10
|
+
props: Record<string, Prop>;
|
|
11
|
+
usage?: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type ComponentSummary = Pick<ComponentDoc, "name" | "kind"> & {
|
|
15
|
+
summary: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function entries(
|
|
19
|
+
kind: ComponentDoc["kind"],
|
|
20
|
+
group: Record<string, Doc>,
|
|
21
|
+
): ComponentDoc[] {
|
|
22
|
+
return Object.entries(group).map(([name, { description, props }]) => ({
|
|
23
|
+
name,
|
|
24
|
+
kind,
|
|
25
|
+
description,
|
|
26
|
+
props,
|
|
27
|
+
...(kind === "control" && {
|
|
28
|
+
usage: `::${name}[var]{…props}, or :::${name}[var]{…props} children ::: to supply children; declares state \`var\`, read as {var}`,
|
|
29
|
+
}),
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const ALL: ComponentDoc[] = [
|
|
34
|
+
...entries("component", docs.components),
|
|
35
|
+
...entries("control", docs.controls),
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
export function searchComponents(query = ""): ComponentSummary[] {
|
|
39
|
+
const q = query.toLowerCase();
|
|
40
|
+
return ALL.filter(
|
|
41
|
+
(d) =>
|
|
42
|
+
d.name.toLowerCase().includes(q) ||
|
|
43
|
+
d.description.toLowerCase().includes(q),
|
|
44
|
+
).map(({ name, kind, description }) => ({
|
|
45
|
+
name,
|
|
46
|
+
kind,
|
|
47
|
+
summary: description.split("\n", 1)[0],
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export class UnknownComponentError extends Error {}
|
|
52
|
+
|
|
53
|
+
export function describeComponent(name: string): ComponentDoc {
|
|
54
|
+
const found = ALL.find((d) => d.name === name);
|
|
55
|
+
if (found) return found;
|
|
56
|
+
const q = name.toLowerCase();
|
|
57
|
+
const near = ALL.filter(
|
|
58
|
+
(d) => d.name.toLowerCase().includes(q) || q.includes(d.name.toLowerCase()),
|
|
59
|
+
).map((d) => d.name);
|
|
60
|
+
throw new UnknownComponentError(
|
|
61
|
+
`no component ${name}${near.length > 0 ? `; did you mean ${near.join(", ")}` : ""}`,
|
|
62
|
+
);
|
|
63
|
+
}
|
package/src/css.ts
CHANGED
|
@@ -14,7 +14,7 @@ export async function buildCss(mdxPath: string): Promise<string> {
|
|
|
14
14
|
const base = readFileSync(path.join(SRC_DIR, "globals.css"), "utf8");
|
|
15
15
|
await Bun.write(
|
|
16
16
|
input,
|
|
17
|
-
`${base}\n@source ${JSON.stringify(path.dirname(mdxPath))};\n`,
|
|
17
|
+
`${base}\n@source ${JSON.stringify(SRC_DIR)};\n@source ${JSON.stringify(path.dirname(mdxPath))};\n`,
|
|
18
18
|
);
|
|
19
19
|
const proc = Bun.spawn([TAILWIND, "-i", input, "-o", output], {
|
|
20
20
|
stdout: "ignore",
|
package/src/data-args.test.ts
CHANGED
|
@@ -4,27 +4,30 @@ import { DataArgError, resolveData } from "./data-args";
|
|
|
4
4
|
describe("resolveData", () => {
|
|
5
5
|
test("bare URL attaches as db", () => {
|
|
6
6
|
expect(resolveData({}, ["ws://h:7823/ws"])).toEqual({
|
|
7
|
-
db: "ws://h:7823/ws",
|
|
7
|
+
db: { url: "ws://h:7823/ws", token: "" },
|
|
8
8
|
});
|
|
9
9
|
});
|
|
10
10
|
|
|
11
11
|
test("name=URL attaches as name", () => {
|
|
12
12
|
expect(resolveData({}, ["nyc=wss://h/ws", "sales=ws://h2/ws"])).toEqual({
|
|
13
|
-
nyc: "wss://h/ws",
|
|
14
|
-
sales: "ws://h2/ws",
|
|
13
|
+
nyc: { url: "wss://h/ws", token: "" },
|
|
14
|
+
sales: { url: "ws://h2/ws", token: "" },
|
|
15
15
|
});
|
|
16
16
|
});
|
|
17
17
|
|
|
18
18
|
test("a URL whose query contains = is still a bare URL", () => {
|
|
19
19
|
expect(resolveData({}, ["ws://h/ws?a=b"])).toEqual({
|
|
20
|
-
db: "ws://h/ws?a=b",
|
|
20
|
+
db: { url: "ws://h/ws?a=b", token: "" },
|
|
21
21
|
});
|
|
22
22
|
});
|
|
23
23
|
|
|
24
24
|
test("--data overrides frontmatter for the same alias", () => {
|
|
25
25
|
expect(
|
|
26
26
|
resolveData({ nyc: "ws://a/ws", other: "ws://o/ws" }, ["nyc=ws://b/ws"]),
|
|
27
|
-
).toEqual({
|
|
27
|
+
).toEqual({
|
|
28
|
+
nyc: { url: "ws://b/ws", token: "" },
|
|
29
|
+
other: { url: "ws://o/ws", token: "" },
|
|
30
|
+
});
|
|
28
31
|
});
|
|
29
32
|
|
|
30
33
|
test("bad alias is rejected", () => {
|
|
@@ -36,4 +39,23 @@ describe("resolveData", () => {
|
|
|
36
39
|
expect(() => resolveData({}, ["http://h/ws"])).toThrow(DataArgError);
|
|
37
40
|
expect(() => resolveData({}, ["db=localhost:7823"])).toThrow(DataArgError);
|
|
38
41
|
});
|
|
42
|
+
|
|
43
|
+
test("--data token rides userinfo and is stripped from the URL", () => {
|
|
44
|
+
expect(resolveData({}, ["nyc=ws://s%40cret@h:1/ws"])).toEqual({
|
|
45
|
+
nyc: { url: "ws://h:1/ws", token: "s@cret" },
|
|
46
|
+
});
|
|
47
|
+
expect(resolveData({}, ["ws://tok@h/ws"])).toEqual({
|
|
48
|
+
db: { url: "ws://h/ws", token: "tok" },
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test("user:password is rejected", () => {
|
|
53
|
+
expect(() => resolveData({}, ["ws://u:p@h/ws"])).toThrow(DataArgError);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("frontmatter credentials are rejected", () => {
|
|
57
|
+
expect(() => resolveData({ nyc: "ws://tok@h/ws" }, [])).toThrow(
|
|
58
|
+
DataArgError,
|
|
59
|
+
);
|
|
60
|
+
});
|
|
39
61
|
});
|
package/src/data-args.ts
CHANGED
|
@@ -3,6 +3,8 @@ const DEFAULT_ALIAS = "db";
|
|
|
3
3
|
|
|
4
4
|
export class DataArgError extends Error {}
|
|
5
5
|
|
|
6
|
+
export type DataSource = { url: string; token: string };
|
|
7
|
+
|
|
6
8
|
function checked(alias: string, url: string, source: string): [string, string] {
|
|
7
9
|
if (!ALIAS.test(alias)) {
|
|
8
10
|
throw new DataArgError(
|
|
@@ -26,19 +28,40 @@ function parseFlag(flag: string): [string, string] {
|
|
|
26
28
|
return checked(flag.slice(0, eq), flag.slice(eq + 1), "--data");
|
|
27
29
|
}
|
|
28
30
|
|
|
29
|
-
|
|
31
|
+
function splitToken(raw: string, source: string): DataSource {
|
|
32
|
+
if (!URL.canParse(raw)) {
|
|
33
|
+
throw new DataArgError(`${source}: ${JSON.stringify(raw)} is not a URL`);
|
|
34
|
+
}
|
|
35
|
+
const url = new URL(raw);
|
|
36
|
+
if (!url.username && !url.password) return { url: raw, token: "" };
|
|
37
|
+
if (source !== "--data") {
|
|
38
|
+
throw new DataArgError(
|
|
39
|
+
`${source}: credentials in ${JSON.stringify(url.host)} are only accepted from --data`,
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
if (url.password) {
|
|
43
|
+
throw new DataArgError(
|
|
44
|
+
`${source}: use ws://<token>@host, not user:password`,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
const token = decodeURIComponent(url.username);
|
|
48
|
+
url.username = "";
|
|
49
|
+
return { url: url.href, token };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Alias → source. The alias is also the server catalog name the client attaches.
|
|
30
53
|
export function resolveData(
|
|
31
54
|
frontmatterUrls: Record<string, string>,
|
|
32
55
|
dataFlags: string[],
|
|
33
|
-
): Record<string,
|
|
34
|
-
const out: Record<string,
|
|
56
|
+
): Record<string, DataSource> {
|
|
57
|
+
const out: Record<string, DataSource> = {};
|
|
35
58
|
for (const [alias, url] of Object.entries(frontmatterUrls)) {
|
|
36
59
|
const [a, u] = checked(alias, url, "attach:");
|
|
37
|
-
out[a] = u;
|
|
60
|
+
out[a] = splitToken(u, "attach:");
|
|
38
61
|
}
|
|
39
62
|
for (const flag of dataFlags) {
|
|
40
63
|
const [a, u] = parseFlag(flag);
|
|
41
|
-
out[a] = u;
|
|
64
|
+
out[a] = splitToken(u, "--data");
|
|
42
65
|
}
|
|
43
66
|
return out;
|
|
44
67
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const INSTRUCTIONS = `n6k-serve renders MDX pages in the browser with live data.
|
|
2
|
+
|
|
3
|
+
Pages
|
|
4
|
+
- set_page takes an absolute .mdx path or inline mdx and returns the page URL, or the build error.
|
|
5
|
+
- Every @n6k.io/ui component and control is in scope without imports. Find them with search_components and read props with describe_component.
|
|
6
|
+
|
|
7
|
+
Data
|
|
8
|
+
- set_data(alias, url, token) attaches the gateway's catalog named \`alias\`. Queries run in DuckDB (wasm) in the browser; reference tables as \`alias.table\`.
|
|
9
|
+
- Components read data via props such as \`data\` (a relation), \`value\` (a measure expression, e.g. \`sum(amount)\`) or \`query\` (full SQL).
|
|
10
|
+
- set_data and remove_data rebuild and reload every page.
|
|
11
|
+
|
|
12
|
+
Controls
|
|
13
|
+
- Leaf form declares state and renders the control:
|
|
14
|
+
::Slider[sims]{label="Simulations" min=1000 max=500000 default=100000}
|
|
15
|
+
::Select[category]{label="Category" options="Hardware,Software,Services" empty="All"}
|
|
16
|
+
- Container form supplies its own markup:
|
|
17
|
+
:::Select[month]{default="2020-09"}
|
|
18
|
+
<SelectTrigger><SelectValue /></SelectTrigger>
|
|
19
|
+
<SelectContent><SelectItem value="2020-09">Sep 2020</SelectItem></SelectContent>
|
|
20
|
+
:::
|
|
21
|
+
- The bracketed name is a variable usable in expressions, e.g. filters={{ category }} or query={\`SELECT … LIMIT \${sims}\`}.
|
|
22
|
+
- Attributes are strings coerced to numbers/booleans; \`options\` and \`default\` split on commas; an option "value:label" sets a separate label.`;
|
package/src/mcp.test.ts
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { afterEach, expect, test } from "bun:test";
|
|
5
|
+
|
|
6
|
+
const CLI = path.join(import.meta.dir, "cli.ts");
|
|
7
|
+
|
|
8
|
+
type Reply = {
|
|
9
|
+
id: number;
|
|
10
|
+
result?: {
|
|
11
|
+
content?: { text: string }[];
|
|
12
|
+
isError?: boolean;
|
|
13
|
+
tools?: { name: string }[];
|
|
14
|
+
instructions?: string;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function spawnMcp(args: string[] = []) {
|
|
19
|
+
const proc = Bun.spawn(["bun", CLI, "--mcp", "--port", "0", ...args], {
|
|
20
|
+
stdin: "pipe",
|
|
21
|
+
stdout: "pipe",
|
|
22
|
+
stderr: "pipe",
|
|
23
|
+
});
|
|
24
|
+
const lines: string[] = [];
|
|
25
|
+
const waiting = new Map<number, (reply: Reply) => void>();
|
|
26
|
+
let nextId = 1;
|
|
27
|
+
|
|
28
|
+
void (async () => {
|
|
29
|
+
const decoder = new TextDecoder();
|
|
30
|
+
let buf = "";
|
|
31
|
+
for await (const chunk of proc.stdout) {
|
|
32
|
+
buf += decoder.decode(chunk);
|
|
33
|
+
let nl: number;
|
|
34
|
+
while ((nl = buf.indexOf("\n")) !== -1) {
|
|
35
|
+
const line = buf.slice(0, nl);
|
|
36
|
+
buf = buf.slice(nl + 1);
|
|
37
|
+
lines.push(line);
|
|
38
|
+
const msg = JSON.parse(line) as Reply;
|
|
39
|
+
waiting.get(msg.id)?.(msg);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
})();
|
|
43
|
+
|
|
44
|
+
const send = (msg: object) => {
|
|
45
|
+
void proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\n");
|
|
46
|
+
void proc.stdin.flush();
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const request = (method: string, params: object): Promise<Reply> => {
|
|
50
|
+
const id = nextId++;
|
|
51
|
+
const reply = new Promise<Reply>((resolve) => waiting.set(id, resolve));
|
|
52
|
+
send({ id, method, params });
|
|
53
|
+
return reply;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const call = async (name: string, args: object = {}) => {
|
|
57
|
+
const reply = await request("tools/call", { name, arguments: args });
|
|
58
|
+
return {
|
|
59
|
+
text: reply.result?.content?.[0]?.text ?? "",
|
|
60
|
+
isError: reply.result?.isError === true,
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const init = async () => {
|
|
65
|
+
const reply = await request("initialize", {
|
|
66
|
+
protocolVersion: "2025-06-18",
|
|
67
|
+
capabilities: {},
|
|
68
|
+
clientInfo: { name: "test", version: "0" },
|
|
69
|
+
});
|
|
70
|
+
send({ method: "notifications/initialized" });
|
|
71
|
+
return reply;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
return { proc, lines, request, call, init };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let cleanup: (() => void)[] = [];
|
|
78
|
+
afterEach(() => {
|
|
79
|
+
for (const fn of cleanup) fn();
|
|
80
|
+
cleanup = [];
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
function tempDir(): string {
|
|
84
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), "n6k-serve-test-"));
|
|
85
|
+
cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
|
|
86
|
+
return dir;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function status(url: string | URL): Promise<number> {
|
|
90
|
+
const res = await fetch(url);
|
|
91
|
+
return res.status;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function body(url: string | URL): Promise<string> {
|
|
95
|
+
const res = await fetch(url);
|
|
96
|
+
return res.text();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
test("mcp serves inline and path pages", async () => {
|
|
100
|
+
const mcp = spawnMcp();
|
|
101
|
+
cleanup.push(() => mcp.proc.kill());
|
|
102
|
+
await mcp.init();
|
|
103
|
+
const failed = async (name: string, args: object) => {
|
|
104
|
+
const reply = await mcp.call(name, args);
|
|
105
|
+
return reply.isError;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const tools = await mcp.request("tools/list", {});
|
|
109
|
+
expect(tools.result?.tools?.map((t) => t.name).toSorted()).toEqual([
|
|
110
|
+
"describe_component",
|
|
111
|
+
"list_pages",
|
|
112
|
+
"remove_data",
|
|
113
|
+
"remove_page",
|
|
114
|
+
"search_components",
|
|
115
|
+
"set_data",
|
|
116
|
+
"set_page",
|
|
117
|
+
]);
|
|
118
|
+
|
|
119
|
+
const set = await mcp.call("set_page", { page: "p", mdx: "# one" });
|
|
120
|
+
expect(set.isError).toBe(false);
|
|
121
|
+
const url = set.text;
|
|
122
|
+
expect(url).toMatch(/^http:\/\/.*\/p\/$/);
|
|
123
|
+
expect(await status(url)).toBe(200);
|
|
124
|
+
const js = new URL("index.js", url);
|
|
125
|
+
expect(await body(js)).toContain("one");
|
|
126
|
+
|
|
127
|
+
await mcp.call("set_page", { page: "p", mdx: "# two" });
|
|
128
|
+
expect(await body(js)).toContain("two");
|
|
129
|
+
|
|
130
|
+
const broken = await mcp.call("set_page", { page: "bad", mdx: "<Nope" });
|
|
131
|
+
expect(broken.isError).toBe(true);
|
|
132
|
+
expect(broken.text).not.toBe("");
|
|
133
|
+
|
|
134
|
+
expect(
|
|
135
|
+
await failed("set_page", { page: "x", mdx: "# x", path: "/x.mdx" }),
|
|
136
|
+
).toBe(true);
|
|
137
|
+
expect(await failed("set_page", { page: "x", path: "rel.mdx" })).toBe(true);
|
|
138
|
+
expect(await failed("set_page", { page: "a/b", mdx: "# x" })).toBe(true);
|
|
139
|
+
|
|
140
|
+
const file = path.join(tempDir(), "f.mdx");
|
|
141
|
+
writeFileSync(file, "# from file");
|
|
142
|
+
expect(await mcp.call("set_page", { page: "f", path: file })).toEqual({
|
|
143
|
+
text: url.replace(/p\/$/, "f/"),
|
|
144
|
+
isError: false,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
const listed = await mcp.call("list_pages");
|
|
148
|
+
const pages = JSON.parse(listed.text) as { page: string }[];
|
|
149
|
+
expect(pages.map((p) => p.page).toSorted()).toEqual(["bad", "f", "p"]);
|
|
150
|
+
|
|
151
|
+
expect(await body(js)).not.toContain("tok-secret");
|
|
152
|
+
expect(
|
|
153
|
+
await failed("set_data", { alias: "1x", url: "ws://x", token: "t" }),
|
|
154
|
+
).toBe(true);
|
|
155
|
+
expect(
|
|
156
|
+
await failed("set_data", { alias: "db", url: "http://x", token: "t" }),
|
|
157
|
+
).toBe(true);
|
|
158
|
+
expect(
|
|
159
|
+
await failed("set_data", {
|
|
160
|
+
alias: "db",
|
|
161
|
+
url: "ws://127.0.0.1:1/ws",
|
|
162
|
+
token: "tok-secret",
|
|
163
|
+
}),
|
|
164
|
+
).toBe(false);
|
|
165
|
+
expect(await body(js)).toContain("tok-secret");
|
|
166
|
+
expect(await body(js)).toContain("ws://127.0.0.1:1/ws");
|
|
167
|
+
expect(await failed("remove_data", { alias: "db" })).toBe(false);
|
|
168
|
+
expect(await body(js)).not.toContain("tok-secret");
|
|
169
|
+
expect(await body(js)).not.toContain("ws://127.0.0.1:1/ws");
|
|
170
|
+
expect(await failed("remove_data", { alias: "db" })).toBe(true);
|
|
171
|
+
|
|
172
|
+
expect(await failed("remove_page", { page: "p" })).toBe(false);
|
|
173
|
+
expect(await status(url)).toBe(404);
|
|
174
|
+
expect(await failed("remove_page", { page: "p" })).toBe(true);
|
|
175
|
+
|
|
176
|
+
for (const line of mcp.lines) expect(() => JSON.parse(line)).not.toThrow();
|
|
177
|
+
|
|
178
|
+
mcp.proc.stdin.end();
|
|
179
|
+
expect(await mcp.proc.exited).toBe(0);
|
|
180
|
+
}, 60_000);
|
|
181
|
+
|
|
182
|
+
test("mcp documents components and renders controls", async () => {
|
|
183
|
+
const mcp = spawnMcp();
|
|
184
|
+
cleanup.push(() => mcp.proc.kill());
|
|
185
|
+
const init = await mcp.init();
|
|
186
|
+
expect(init.result?.instructions).toContain("::Slider");
|
|
187
|
+
|
|
188
|
+
const search = async (query?: string) => {
|
|
189
|
+
const reply = await mcp.call("search_components", { query });
|
|
190
|
+
return JSON.parse(reply.text) as { name: string; kind: string }[];
|
|
191
|
+
};
|
|
192
|
+
expect(await search()).toHaveLength(52);
|
|
193
|
+
const charts = await search("chart");
|
|
194
|
+
expect(charts.map((c) => c.name)).toContain("BarChart");
|
|
195
|
+
|
|
196
|
+
const slider = await mcp.call("describe_component", { name: "Slider" });
|
|
197
|
+
const doc = JSON.parse(slider.text) as {
|
|
198
|
+
kind: string;
|
|
199
|
+
props: Record<string, unknown>;
|
|
200
|
+
};
|
|
201
|
+
expect(doc.kind).toBe("control");
|
|
202
|
+
expect(Object.keys(doc.props)).toEqual(
|
|
203
|
+
expect.arrayContaining(["min", "max"]),
|
|
204
|
+
);
|
|
205
|
+
const unknown = await mcp.call("describe_component", { name: "Bar" });
|
|
206
|
+
expect(unknown.isError).toBe(true);
|
|
207
|
+
expect(unknown.text).toContain("BarChart");
|
|
208
|
+
|
|
209
|
+
const leaf = await mcp.call("set_page", {
|
|
210
|
+
page: "leaf",
|
|
211
|
+
mdx: '::Slider[n]{label="N" min=1 max=10 default=5}\n\nValue {n}\n',
|
|
212
|
+
});
|
|
213
|
+
expect(leaf.isError).toBe(false);
|
|
214
|
+
expect(await body(new URL("index.js", leaf.text))).toContain("Controls");
|
|
215
|
+
|
|
216
|
+
const container = await mcp.call("set_page", {
|
|
217
|
+
page: "container",
|
|
218
|
+
mdx: [
|
|
219
|
+
':::Select[month]{default="a"}',
|
|
220
|
+
"<SelectTrigger><SelectValue /></SelectTrigger>",
|
|
221
|
+
'<SelectContent><SelectItem value="a">A</SelectItem></SelectContent>',
|
|
222
|
+
":::",
|
|
223
|
+
"",
|
|
224
|
+
].join("\n"),
|
|
225
|
+
});
|
|
226
|
+
expect(container.isError).toBe(false);
|
|
227
|
+
}, 60_000);
|
package/src/mcp.ts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { McpServer } from "@modelcontextprotocol/server";
|
|
5
|
+
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { bundlePage } from "./bundle";
|
|
8
|
+
import { buildCss } from "./css";
|
|
9
|
+
import { describeComponent, searchComponents } from "./component-docs";
|
|
10
|
+
import { ALIAS, type DataSource } from "./data-args";
|
|
11
|
+
import { INSTRUCTIONS } from "./mcp-instructions";
|
|
12
|
+
import { PagesError, name } from "./pages";
|
|
13
|
+
import type { PageState, ServedPage, Server, Site } from "./server";
|
|
14
|
+
import { watchFile } from "./watch";
|
|
15
|
+
|
|
16
|
+
type Entry = {
|
|
17
|
+
file: string;
|
|
18
|
+
served: ServedPage;
|
|
19
|
+
cached?: Promise<PageState>;
|
|
20
|
+
unwatch: () => void;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function listing(pages: string[]): string {
|
|
24
|
+
const items = pages.map(
|
|
25
|
+
(page) => `<li><a href="/${page}/">${Bun.escapeHTML(page)}</a></li>`,
|
|
26
|
+
);
|
|
27
|
+
return `<!doctype html>
|
|
28
|
+
<html lang="en">
|
|
29
|
+
<head><meta charset="utf-8" /><title>n6k-serve</title></head>
|
|
30
|
+
<body><ul>${items.join("")}</ul></body>
|
|
31
|
+
</html>`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class McpSite implements Site {
|
|
35
|
+
private readonly entries = new Map<string, Entry>();
|
|
36
|
+
private readonly data = new Map<string, DataSource>();
|
|
37
|
+
|
|
38
|
+
constructor(private readonly onChange: (key: string) => void) {}
|
|
39
|
+
|
|
40
|
+
resolve: Site["resolve"] = (pathname) => {
|
|
41
|
+
if (pathname === "/")
|
|
42
|
+
return { kind: "html", body: listing([...this.entries.keys()]) };
|
|
43
|
+
const [, page, ...rest] = pathname.split("/");
|
|
44
|
+
const entry = this.entries.get(page);
|
|
45
|
+
if (!entry) return;
|
|
46
|
+
if (rest.length === 0) return { kind: "redirect", to: `${pathname}/` };
|
|
47
|
+
return { kind: "page", page: entry.served, rest: `/${rest.join("/")}` };
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
page: Site["page"] = (key) => this.entries.get(key)?.served;
|
|
51
|
+
|
|
52
|
+
setData(alias: string, source: DataSource): void {
|
|
53
|
+
this.data.set(alias, source);
|
|
54
|
+
this.rebuildAll();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
removeData(alias: string): void {
|
|
58
|
+
if (!this.data.delete(alias)) throw new PagesError(`no data ${alias}`);
|
|
59
|
+
this.rebuildAll();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private rebuildAll(): void {
|
|
63
|
+
for (const [page, entry] of this.entries) {
|
|
64
|
+
entry.cached = undefined;
|
|
65
|
+
this.onChange(page);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
list(): { page: string; file: string }[] {
|
|
70
|
+
return [...this.entries].map(([page, { file }]) => ({ page, file }));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
set(page: string, file: string): ServedPage {
|
|
74
|
+
const existing = this.entries.get(page);
|
|
75
|
+
if (existing?.file === file) {
|
|
76
|
+
existing.cached = undefined;
|
|
77
|
+
this.onChange(page);
|
|
78
|
+
return existing.served;
|
|
79
|
+
}
|
|
80
|
+
existing?.unwatch();
|
|
81
|
+
const entry: Entry = {
|
|
82
|
+
file,
|
|
83
|
+
served: {
|
|
84
|
+
title: path.basename(file),
|
|
85
|
+
key: page,
|
|
86
|
+
state: () => {
|
|
87
|
+
if (entry.cached) return entry.cached;
|
|
88
|
+
const built = this.build(file);
|
|
89
|
+
entry.cached = built;
|
|
90
|
+
built.catch(() => {
|
|
91
|
+
if (entry.cached === built) entry.cached = undefined;
|
|
92
|
+
});
|
|
93
|
+
return built;
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
unwatch: watchFile(file, () => {
|
|
97
|
+
entry.cached = undefined;
|
|
98
|
+
this.onChange(page);
|
|
99
|
+
console.error(`changed ${page}`);
|
|
100
|
+
}),
|
|
101
|
+
};
|
|
102
|
+
this.entries.set(page, entry);
|
|
103
|
+
if (existing) this.onChange(page);
|
|
104
|
+
return entry.served;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
remove(page: string): void {
|
|
108
|
+
const entry = this.entries.get(page);
|
|
109
|
+
if (!entry) throw new PagesError(`no page ${page}`);
|
|
110
|
+
entry.unwatch();
|
|
111
|
+
this.entries.delete(page);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private async build(file: string): Promise<PageState> {
|
|
115
|
+
const [bundle, css] = await Promise.all([
|
|
116
|
+
bundlePage(file, {
|
|
117
|
+
data: Object.fromEntries(
|
|
118
|
+
[...this.data].map(([alias, { url }]) => [alias, url]),
|
|
119
|
+
),
|
|
120
|
+
tokens: Object.fromEntries(
|
|
121
|
+
[...this.data].map(([alias, { token }]) => [alias, token]),
|
|
122
|
+
),
|
|
123
|
+
}),
|
|
124
|
+
buildCss(file),
|
|
125
|
+
]);
|
|
126
|
+
return { bundle, css };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function text(value: unknown) {
|
|
131
|
+
return {
|
|
132
|
+
content: [
|
|
133
|
+
{
|
|
134
|
+
type: "text" as const,
|
|
135
|
+
text: typeof value === "string" ? value : JSON.stringify(value),
|
|
136
|
+
},
|
|
137
|
+
],
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function startMcp(
|
|
142
|
+
site: McpSite,
|
|
143
|
+
server: Server,
|
|
144
|
+
version: string,
|
|
145
|
+
onClose: () => void,
|
|
146
|
+
): void {
|
|
147
|
+
const inlineDir = mkdtempSync(path.join(os.tmpdir(), "n6k-serve-"));
|
|
148
|
+
const urlOf = (page: string) => new URL(`${page}/`, server.url).href;
|
|
149
|
+
const mcp = new McpServer(
|
|
150
|
+
{ name: "n6k-serve", version },
|
|
151
|
+
{ capabilities: { tools: {} }, instructions: INSTRUCTIONS },
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
mcp.registerTool(
|
|
155
|
+
"search_components",
|
|
156
|
+
{
|
|
157
|
+
description:
|
|
158
|
+
"Search components and controls by name or description; omit query to list all.",
|
|
159
|
+
inputSchema: z.object({ query: z.string().optional() }),
|
|
160
|
+
},
|
|
161
|
+
({ query }) => text(searchComponents(query)),
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
mcp.registerTool(
|
|
165
|
+
"describe_component",
|
|
166
|
+
{
|
|
167
|
+
description: "Props and description of one component or control.",
|
|
168
|
+
inputSchema: z.object({ name: z.string() }),
|
|
169
|
+
},
|
|
170
|
+
({ name: component }) => text(describeComponent(component)),
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
mcp.registerTool(
|
|
174
|
+
"list_pages",
|
|
175
|
+
{ description: "List served pages with their URLs." },
|
|
176
|
+
() => text(site.list().map((p) => ({ ...p, url: urlOf(p.page) }))),
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
mcp.registerTool(
|
|
180
|
+
"set_page",
|
|
181
|
+
{
|
|
182
|
+
description:
|
|
183
|
+
"Serve a page from an absolute .mdx path or inline mdx content (exactly one), build it, and return its URL or the build error.",
|
|
184
|
+
inputSchema: z.object({
|
|
185
|
+
page: z.string(),
|
|
186
|
+
path: z.string().optional(),
|
|
187
|
+
mdx: z.string().optional(),
|
|
188
|
+
}),
|
|
189
|
+
},
|
|
190
|
+
async ({ page, path: file, mdx }) => {
|
|
191
|
+
name(page, "page");
|
|
192
|
+
if ((file === undefined) === (mdx === undefined))
|
|
193
|
+
throw new PagesError("pass exactly one of path or mdx");
|
|
194
|
+
let abs: string;
|
|
195
|
+
if (mdx === undefined) {
|
|
196
|
+
abs = file ?? "";
|
|
197
|
+
if (!path.isAbsolute(abs))
|
|
198
|
+
throw new PagesError(`${abs}: path must be absolute`);
|
|
199
|
+
if (!abs.endsWith(".mdx"))
|
|
200
|
+
throw new PagesError(`${abs}: not an .mdx file`);
|
|
201
|
+
if (!existsSync(abs)) throw new PagesError(`${abs}: no such file`);
|
|
202
|
+
} else {
|
|
203
|
+
abs = path.join(inlineDir, `${page}.mdx`);
|
|
204
|
+
await Bun.write(abs, mdx);
|
|
205
|
+
}
|
|
206
|
+
await site.set(page, abs).state();
|
|
207
|
+
return text(urlOf(page));
|
|
208
|
+
},
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
mcp.registerTool(
|
|
212
|
+
"set_data",
|
|
213
|
+
{
|
|
214
|
+
description:
|
|
215
|
+
"Attach a data source as `alias` (also the server catalog name). Rebuilds and reloads every page.",
|
|
216
|
+
inputSchema: z.object({
|
|
217
|
+
alias: z.string(),
|
|
218
|
+
url: z.string(),
|
|
219
|
+
token: z.string(),
|
|
220
|
+
}),
|
|
221
|
+
},
|
|
222
|
+
({ alias, url, token }) => {
|
|
223
|
+
if (!ALIAS.test(alias))
|
|
224
|
+
throw new PagesError(
|
|
225
|
+
`alias ${JSON.stringify(alias)} must match ${ALIAS.source}`,
|
|
226
|
+
);
|
|
227
|
+
if (!URL.canParse(url) || !/^wss?:$/.test(new URL(url).protocol))
|
|
228
|
+
throw new PagesError(
|
|
229
|
+
`${JSON.stringify(url)} is not a ws:// or wss:// URL`,
|
|
230
|
+
);
|
|
231
|
+
site.setData(alias, { url, token });
|
|
232
|
+
return text(`set data ${alias}`);
|
|
233
|
+
},
|
|
234
|
+
);
|
|
235
|
+
|
|
236
|
+
mcp.registerTool(
|
|
237
|
+
"remove_data",
|
|
238
|
+
{
|
|
239
|
+
description: "Detach a data source. Rebuilds and reloads every page.",
|
|
240
|
+
inputSchema: z.object({ alias: z.string() }),
|
|
241
|
+
},
|
|
242
|
+
({ alias }) => {
|
|
243
|
+
site.removeData(alias);
|
|
244
|
+
return text(`removed data ${alias}`);
|
|
245
|
+
},
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
mcp.registerTool(
|
|
249
|
+
"remove_page",
|
|
250
|
+
{
|
|
251
|
+
description: "Stop serving a page.",
|
|
252
|
+
inputSchema: z.object({ page: z.string() }),
|
|
253
|
+
},
|
|
254
|
+
({ page }) => {
|
|
255
|
+
site.remove(page);
|
|
256
|
+
return text(`removed ${page}`);
|
|
257
|
+
},
|
|
258
|
+
);
|
|
259
|
+
|
|
260
|
+
const transport = new StdioServerTransport();
|
|
261
|
+
// eslint-disable-next-line unicorn/prefer-add-event-listener -- Transport has no addEventListener
|
|
262
|
+
transport.onclose = () => {
|
|
263
|
+
void server.stop(true);
|
|
264
|
+
rmSync(inlineDir, { recursive: true, force: true });
|
|
265
|
+
onClose();
|
|
266
|
+
};
|
|
267
|
+
void mcp.connect(transport);
|
|
268
|
+
}
|
package/src/mdx-components.tsx
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
import type { ComponentProps } from "react";
|
|
2
2
|
import type { MDXComponents } from "mdx/types";
|
|
3
3
|
import * as n6k from "@n6k.io/ui/components";
|
|
4
|
+
import {
|
|
5
|
+
SelectContent,
|
|
6
|
+
SelectItem,
|
|
7
|
+
SelectTrigger,
|
|
8
|
+
SelectValue,
|
|
9
|
+
} from "@n6k.io/ui/components/ui/select";
|
|
4
10
|
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
// markdown elements. A tag that isn't registered here (or imported in the page)
|
|
9
|
-
// fails when the page is rendered.
|
|
11
|
+
// Passed to the build as `mdxComponents`. A tag that is neither
|
|
12
|
+
// here nor imported by the page still builds and fails at render.
|
|
13
|
+
// `Controls` is the name @n6k.io/build's remark-controls emits for `::X[…]`.
|
|
10
14
|
export function useMDXComponents(components: MDXComponents): MDXComponents {
|
|
11
15
|
return {
|
|
12
16
|
...n6k,
|
|
17
|
+
Controls: n6k.controls,
|
|
18
|
+
SelectContent,
|
|
19
|
+
SelectItem,
|
|
20
|
+
SelectTrigger,
|
|
21
|
+
SelectValue,
|
|
13
22
|
h1: (props: ComponentProps<"h1">) => (
|
|
14
23
|
<h1 className="pb-4 text-4xl font-black tracking-tight" {...props} />
|
|
15
24
|
),
|
package/src/pages-site.ts
CHANGED
|
@@ -55,24 +55,17 @@ export class PagesSite implements Site {
|
|
|
55
55
|
|
|
56
56
|
page: Site["page"] = (key) => this.entries.get(key)?.served;
|
|
57
57
|
|
|
58
|
-
upstream: Site["upstream"] = (rest) => {
|
|
59
|
-
const [app, catalog] = rest.split("/");
|
|
60
|
-
const gateway = this.config[app]?.gateway;
|
|
61
|
-
if (!gateway?.catalogs.includes(catalog)) return;
|
|
62
|
-
return gateway.url;
|
|
63
|
-
};
|
|
64
|
-
|
|
65
58
|
private add(ref: PageRef): void {
|
|
66
59
|
const key = keyOf(ref);
|
|
67
60
|
const file = this.config[ref.app].pages[ref.page];
|
|
68
|
-
const { token, catalogs } = this.config[ref.app].gateway;
|
|
61
|
+
const { url, token, catalogs } = this.config[ref.app].gateway;
|
|
69
62
|
const entry: Entry = {
|
|
70
63
|
served: {
|
|
71
64
|
title: path.basename(file),
|
|
72
65
|
key,
|
|
73
66
|
state: () => {
|
|
74
67
|
if (entry.cached) return entry.cached;
|
|
75
|
-
const built = this.build(file,
|
|
68
|
+
const built = this.build(file, url, catalogs, token);
|
|
76
69
|
entry.cached = built;
|
|
77
70
|
built.catch(() => {
|
|
78
71
|
if (entry.cached === built) entry.cached = undefined;
|
|
@@ -86,7 +79,7 @@ export class PagesSite implements Site {
|
|
|
86
79
|
entry.unwatch = watchFile(file, () => {
|
|
87
80
|
entry.cached = undefined;
|
|
88
81
|
this.onChange(key);
|
|
89
|
-
console.
|
|
82
|
+
console.error(`changed ${key}`);
|
|
90
83
|
});
|
|
91
84
|
} catch (err) {
|
|
92
85
|
console.error(
|
|
@@ -104,15 +97,14 @@ export class PagesSite implements Site {
|
|
|
104
97
|
|
|
105
98
|
private async build(
|
|
106
99
|
file: string,
|
|
107
|
-
|
|
100
|
+
url: string,
|
|
108
101
|
catalogs: string[],
|
|
109
102
|
token: string,
|
|
110
103
|
): Promise<PageState> {
|
|
111
104
|
const [bundle, css] = await Promise.all([
|
|
112
105
|
bundlePage(file, {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
token,
|
|
106
|
+
data: Object.fromEntries(catalogs.map((c) => [c, url])),
|
|
107
|
+
tokens: Object.fromEntries(catalogs.map((c) => [c, token])),
|
|
116
108
|
}),
|
|
117
109
|
buildCss(file),
|
|
118
110
|
]);
|
package/src/pages.ts
CHANGED
|
@@ -31,7 +31,7 @@ function string(value: unknown, where: string): string {
|
|
|
31
31
|
return value;
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
function name(value: string, where: string): string {
|
|
34
|
+
export function name(value: string, where: string): string {
|
|
35
35
|
if (!NAME.test(value))
|
|
36
36
|
throw new PagesError(
|
|
37
37
|
`${where}: ${JSON.stringify(value)} must match ${NAME.source}`,
|
package/src/root.tsx
CHANGED
|
@@ -4,22 +4,19 @@ import { duckdbBundle } from "virtual:n6k-duckdb-bundle";
|
|
|
4
4
|
import { N6kDuckDB, type DatabaseSpec, type SocketSpec } from "@n6k.io/db";
|
|
5
5
|
import { DuckDBProvider, QueryProvider } from "@n6k.io/ui/duckdb";
|
|
6
6
|
import { ConnectionLost, DuckDBConnectionGuard } from "@n6k.io/runtime";
|
|
7
|
+
import { Page } from "@n6k.io/ui/components";
|
|
7
8
|
|
|
8
|
-
function
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
return new WebSocket(`${scheme}://${location.host}${url}`);
|
|
13
|
-
},
|
|
14
|
-
token,
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function engine(aliases: string[], dataPath: string, token: string): N6kDuckDB {
|
|
9
|
+
function engine(
|
|
10
|
+
data: Record<string, string>,
|
|
11
|
+
tokens: Record<string, string>,
|
|
12
|
+
): N6kDuckDB {
|
|
19
13
|
const sockets: Record<string, SocketSpec> = {};
|
|
20
14
|
const databases: Record<string, DatabaseSpec> = {};
|
|
21
|
-
for (const alias of
|
|
22
|
-
sockets[alias] =
|
|
15
|
+
for (const [alias, url] of Object.entries(data)) {
|
|
16
|
+
sockets[alias] = {
|
|
17
|
+
connect: () => new WebSocket(url),
|
|
18
|
+
token: Object.hasOwn(tokens, alias) ? tokens[alias]! : "",
|
|
19
|
+
};
|
|
23
20
|
databases[alias] = { socket: alias };
|
|
24
21
|
}
|
|
25
22
|
return new N6kDuckDB({
|
|
@@ -33,20 +30,22 @@ function engine(aliases: string[], dataPath: string, token: string): N6kDuckDB {
|
|
|
33
30
|
|
|
34
31
|
export default function Root({
|
|
35
32
|
children,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
33
|
+
data = {},
|
|
34
|
+
tokens = {},
|
|
35
|
+
bare = false,
|
|
39
36
|
}: {
|
|
40
37
|
children: ReactNode;
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
38
|
+
data?: Record<string, string>;
|
|
39
|
+
tokens?: Record<string, string>;
|
|
40
|
+
bare?: boolean;
|
|
44
41
|
}) {
|
|
45
|
-
const [duckdb] = useState(() => engine(
|
|
42
|
+
const [duckdb] = useState(() => engine(data, tokens));
|
|
46
43
|
return (
|
|
47
44
|
<QueryProvider>
|
|
48
45
|
<DuckDBProvider connect={duckdb.connect} metadataFns={duckdb.metadataFns}>
|
|
49
|
-
<DuckDBConnectionGuard>
|
|
46
|
+
<DuckDBConnectionGuard>
|
|
47
|
+
{bare ? children : <Page>{children}</Page>}
|
|
48
|
+
</DuckDBConnectionGuard>
|
|
50
49
|
<ConnectionLost duckdb={duckdb} />
|
|
51
50
|
</DuckDBProvider>
|
|
52
51
|
</QueryProvider>
|
package/src/server.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { ServerWebSocket } from "bun";
|
|
2
1
|
import type { Bundle } from "./bundle";
|
|
3
2
|
import { serveAsset } from "./assets";
|
|
4
3
|
|
|
@@ -21,7 +20,6 @@ export type Resolved =
|
|
|
21
20
|
export type Site = {
|
|
22
21
|
resolve: (pathname: string) => Resolved | undefined;
|
|
23
22
|
page: (key: string) => ServedPage | undefined;
|
|
24
|
-
upstream: (path: string) => string | undefined;
|
|
25
23
|
};
|
|
26
24
|
|
|
27
25
|
export type ServeOptions = {
|
|
@@ -30,16 +28,7 @@ export type ServeOptions = {
|
|
|
30
28
|
origins: string[];
|
|
31
29
|
};
|
|
32
30
|
|
|
33
|
-
type SocketData =
|
|
34
|
-
| { kind: "reload"; key: string }
|
|
35
|
-
| {
|
|
36
|
-
kind: "data";
|
|
37
|
-
url: string;
|
|
38
|
-
upstream?: WebSocket;
|
|
39
|
-
pending: Frame[];
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
type Frame = string | Uint8Array<ArrayBuffer>;
|
|
31
|
+
type SocketData = { key: string };
|
|
43
32
|
|
|
44
33
|
const ISOLATION = {
|
|
45
34
|
"Cross-Origin-Opener-Policy": "same-origin",
|
|
@@ -47,7 +36,6 @@ const ISOLATION = {
|
|
|
47
36
|
};
|
|
48
37
|
|
|
49
38
|
const RELOAD_PREFIX = "/_n6k/reload/";
|
|
50
|
-
const DATA_PREFIX = "/_n6k/data/";
|
|
51
39
|
|
|
52
40
|
function topicFor(key: string): string {
|
|
53
41
|
return `reload:${key}`;
|
|
@@ -96,26 +84,6 @@ function contentType(file: string): string {
|
|
|
96
84
|
return "application/octet-stream";
|
|
97
85
|
}
|
|
98
86
|
|
|
99
|
-
function openUpstream(ws: ServerWebSocket<SocketData>): void {
|
|
100
|
-
const data = ws.data;
|
|
101
|
-
if (data.kind !== "data") return;
|
|
102
|
-
const upstream = new WebSocket(data.url);
|
|
103
|
-
upstream.binaryType = "arraybuffer";
|
|
104
|
-
data.upstream = upstream;
|
|
105
|
-
upstream.addEventListener("open", () => {
|
|
106
|
-
for (const msg of data.pending) upstream.send(msg);
|
|
107
|
-
data.pending = [];
|
|
108
|
-
});
|
|
109
|
-
upstream.addEventListener("message", (ev) => {
|
|
110
|
-
ws.send(typeof ev.data === "string" ? ev.data : new Uint8Array(ev.data));
|
|
111
|
-
});
|
|
112
|
-
upstream.addEventListener("close", (ev) => ws.close(1000, ev.reason));
|
|
113
|
-
upstream.addEventListener("error", () => {
|
|
114
|
-
console.error(`[n6k-serve] upstream ${data.url} failed`);
|
|
115
|
-
ws.close(1011, `upstream ${data.url} failed`);
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
|
|
119
87
|
async function servePage(
|
|
120
88
|
page: ServedPage,
|
|
121
89
|
rest: string,
|
|
@@ -156,26 +124,13 @@ export function startServer(site: Site, options: ServeOptions) {
|
|
|
156
124
|
async fetch(req, server) {
|
|
157
125
|
const { pathname } = new URL(req.url);
|
|
158
126
|
|
|
159
|
-
if (
|
|
160
|
-
(pathname.startsWith(RELOAD_PREFIX) ||
|
|
161
|
-
pathname.startsWith(DATA_PREFIX)) &&
|
|
162
|
-
!originAllowed(req)
|
|
163
|
-
) {
|
|
164
|
-
return new Response("origin not allowed", { status: 403 });
|
|
165
|
-
}
|
|
166
127
|
if (pathname.startsWith(RELOAD_PREFIX)) {
|
|
128
|
+
if (!originAllowed(req))
|
|
129
|
+
return new Response("origin not allowed", { status: 403 });
|
|
167
130
|
const key = pathname.slice(RELOAD_PREFIX.length);
|
|
168
131
|
if (!site.page(key))
|
|
169
132
|
return new Response(`no page ${key}`, { status: 404 });
|
|
170
|
-
if (server.upgrade(req, { data: {
|
|
171
|
-
return new Response("upgrade required", { status: 426 });
|
|
172
|
-
}
|
|
173
|
-
if (pathname.startsWith(DATA_PREFIX)) {
|
|
174
|
-
const rest = pathname.slice(DATA_PREFIX.length);
|
|
175
|
-
const url = site.upstream(rest);
|
|
176
|
-
if (!url) return new Response(`no data ${rest}`, { status: 404 });
|
|
177
|
-
if (server.upgrade(req, { data: { kind: "data", url, pending: [] } }))
|
|
178
|
-
return;
|
|
133
|
+
if (server.upgrade(req, { data: { key } })) return;
|
|
179
134
|
return new Response("upgrade required", { status: 426 });
|
|
180
135
|
}
|
|
181
136
|
|
|
@@ -193,23 +148,9 @@ export function startServer(site: Site, options: ServeOptions) {
|
|
|
193
148
|
},
|
|
194
149
|
websocket: {
|
|
195
150
|
open(ws) {
|
|
196
|
-
|
|
197
|
-
else openUpstream(ws);
|
|
198
|
-
},
|
|
199
|
-
message(ws, msg) {
|
|
200
|
-
const data = ws.data;
|
|
201
|
-
if (data.kind !== "data") return;
|
|
202
|
-
const frame: Frame =
|
|
203
|
-
typeof msg === "string" ? msg : new Uint8Array(msg);
|
|
204
|
-
if (data.upstream?.readyState === WebSocket.OPEN) {
|
|
205
|
-
data.upstream.send(frame);
|
|
206
|
-
} else {
|
|
207
|
-
data.pending.push(frame);
|
|
208
|
-
}
|
|
209
|
-
},
|
|
210
|
-
close(ws) {
|
|
211
|
-
if (ws.data.kind === "data") ws.data.upstream?.close();
|
|
151
|
+
ws.subscribe(topicFor(ws.data.key));
|
|
212
152
|
},
|
|
153
|
+
message() {},
|
|
213
154
|
},
|
|
214
155
|
});
|
|
215
156
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<SqlConsole />
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<SqlEditor />
|
package/src/virtual-modules.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
// Provided by @n6k.io/build's
|
|
1
|
+
// Provided by @n6k.io/build's n6kWorkersPlugin.
|
|
2
2
|
declare module "virtual:n6k-workers" {
|
|
3
3
|
export const duckdbWorkerUrl: string;
|
|
4
4
|
export const wsWorkerUrl: string;
|
|
5
5
|
}
|
|
6
6
|
|
|
7
|
-
// Provided by @n6k.io/build's
|
|
7
|
+
// Provided by @n6k.io/build's n6kDuckDBPlugin.
|
|
8
8
|
declare module "virtual:n6k-duckdb-bundle" {
|
|
9
9
|
export const duckdbBundle: {
|
|
10
10
|
mainModule: string;
|