astralis-mcp 0.3.0 → 0.4.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/CHANGELOG.md ADDED
@@ -0,0 +1,50 @@
1
+ # Changelog
2
+
3
+ All notable changes to `astralis-mcp`. Under 0.x, a minor version may contain
4
+ breaking changes; a patch never does.
5
+
6
+ ## 0.4.1 (2026-11-21)
7
+
8
+ Uses astralis-cli 0.6.0, so `validate_code` reads astralis-ui 0.10.0's version 4 system spec.
9
+
10
+ ## 0.4.0 (2026-11-19)
11
+
12
+ Requires Node `^22.18` or `>=24.11`.
13
+
14
+ ### Added
15
+
16
+ - **`validate_code`** checks Astralis code an agent wrote against the design
17
+ system and returns machine-readable errors with valid alternatives, so the
18
+ agent can fix its code and check again. It uses the project's installed
19
+ astralis-ui, or the docs site's `system-spec.json` when there is no
20
+ project. Validation runs locally; the server never calls a model.
21
+
22
+ ### Changed
23
+
24
+ - When the docs site cannot be reached, tools return an error, never
25
+ "unknown" or an empty success.
26
+ - Responses are capped in size, `search_docs` searches one fetched corpus,
27
+ and the remote spec is refreshed instead of cached forever.
28
+ - Tools are registered with read-only hints.
29
+
30
+ ## 0.3.0 (2026-08-08)
31
+
32
+ ### Added
33
+
34
+ - **`list_blocks`** and **`get_block`**, so an agent asked for a pricing
35
+ section can use the block that exists. `get_block` returns the block's
36
+ source as fenced code, ready to write to disk.
37
+
38
+ ## 0.2.0 (2026-07-24)
39
+
40
+ ### Changed
41
+
42
+ - The server reports one version, from its package.
43
+ - Tool descriptions cannot drift from the docs they describe.
44
+ - Fetched pages are cached with a time limit, and requests time out.
45
+
46
+ ## 0.1.0 (2026-07-14)
47
+
48
+ The first release: an MCP server over stdio with `list_components`,
49
+ `get_component`, `get_guide`, `get_theming` and `search_docs`, reading the
50
+ live docs site. Set `ASTRALIS_DOCS_URL` to point it at a local docs server.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Andrew
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,22 +1,28 @@
1
1
  # astralis-mcp
2
2
 
3
- MCP server for [Astralis UI](https://astralis-zeta.vercel.app) — lets AI
3
+ MCP server for [Astralis UI](https://astralis-ui.com) — lets AI
4
4
  coding agents (Claude Code, Cursor, …) look up the library's **current**
5
5
  component APIs, full props tables, runnable demo source, theming guides and
6
- block sources instead of guessing from training data.
6
+ block sources instead of guessing from training data, and check the code they
7
+ write against the design system.
7
8
 
8
9
  Reads the docs site's machine-readable endpoints and its block registry, so
9
10
  answers can never drift from what the documentation actually ships.
10
11
 
11
12
  ## Setup
12
13
 
13
- **Claude Code:**
14
+ The quickest way is `npx astralis-cli connect-mcp`, which configures Claude
15
+ Code, Codex, Cursor, Claude Desktop or Antigravity for you.
16
+
17
+ **Claude Code** by hand:
14
18
 
15
19
  ```bash
16
20
  claude mcp add astralis -- npx -y astralis-mcp
21
+ # Windows: claude mcp add astralis -- cmd /c npx -y astralis-mcp
17
22
  ```
18
23
 
19
- **Any MCP client**, in its config:
24
+ **Any MCP client**, in its config (on Windows use `"command": "cmd"` and
25
+ `"args": ["/c", "npx", "-y", "astralis-mcp"]`):
20
26
 
21
27
  ```json
22
28
  {
@@ -26,25 +32,33 @@ claude mcp add astralis -- npx -y astralis-mcp
26
32
  }
27
33
  ```
28
34
 
29
- No install step — `npx` fetches and runs it on demand.
35
+ No install step — `npx` fetches and runs it on demand. Needs Node `^22.18` or
36
+ `>=24.11`.
30
37
 
31
38
  ## Tools
32
39
 
40
+ All eight are read-only.
41
+
33
42
  | Tool | What it returns |
34
43
  | --- | --- |
35
- | `list_components` | Every docs page — 62 components + 7 guides — with slug, description, category |
44
+ | `list_components` | Every docs page, components and guides, with slug, title, description, section and kind |
36
45
  | `get_component` | One component's full docs: props table, keyboard map, a11y notes, demo source |
37
- | `get_guide` | A guide page: `installation`, `quick-start`, `theming`, `colors`, `responsive`, `style-props`, `tokens` |
38
- | `search_docs` | Full-text search across everything, with snippets |
46
+ | `get_guide` | A guide page, such as `installation`, `quick-start`, `theming` or `tokens` |
47
+ | `search_docs` | Full-text search across everything, with a snippet around each hit |
39
48
  | `get_theming` | The complete theming + design-token reference in one call |
40
49
  | `list_blocks` | Every block — prebuilt page sections — with id, description, category and the components it composes. Filterable by category |
41
50
  | `get_block` | One block's metadata plus the complete source of its files, ready to write into a project |
51
+ | `validate_code` | Verdict on Astralis TSX against the design system's machine-readable spec — unknown components/parts, off-token values, dead `astralis:*` classes, anatomy and a11y mistakes, with actionable reasons. Prefers the spec of the astralis-ui installed in your project; no model involved |
52
+
53
+ When the docs site can't be reached, or answers with an error, every tool
54
+ returns an error result that says so — never "unknown component" or an empty
55
+ answer. Responses over 5 MB are refused.
42
56
 
43
57
  ## Options
44
58
 
45
59
  | Env var | Default | Purpose |
46
60
  | --- | --- | --- |
47
- | `ASTRALIS_DOCS_URL` | `https://astralis-zeta.vercel.app` | Point at a local docs dev server (`http://localhost:3000`) when working on unpublished docs |
61
+ | `ASTRALIS_DOCS_URL` | `https://astralis-ui.com` | Point at a local docs dev server (`http://localhost:3000`) when working on unpublished docs |
48
62
 
49
63
  ## License
50
64
 
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "astralis-mcp",
3
- "version": "0.3.0",
4
- "description": "MCP server exposing Astralis UI docs to AI coding agents — current component APIs, props tables, demo sources, and theming guides instead of hallucinated ones.",
3
+ "version": "0.4.1",
4
+ "description": "MCP server exposing Astralis UI docs to AI coding agents — current component APIs, props tables, demo sources, theming guides, and a validate_code tool that checks generated TSX against the design system's machine-readable spec.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Paul Andrew",
8
- "homepage": "https://astralis-zeta.vercel.app",
8
+ "homepage": "https://astralis-ui.com",
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://github.com/SekiroDev360/astralis-ui.git",
11
+ "url": "git+https://github.com/sekiro-9/astralis-ui.git",
12
12
  "directory": "packages/astralis-mcp"
13
13
  },
14
14
  "bugs": {
15
- "url": "https://github.com/SekiroDev360/astralis-ui/issues"
15
+ "url": "https://github.com/sekiro-9/astralis-ui/issues"
16
16
  },
17
17
  "keywords": [
18
18
  "mcp",
@@ -28,16 +28,19 @@
28
28
  "astralis-mcp": "server.mjs"
29
29
  },
30
30
  "files": [
31
- "server.mjs"
31
+ "server.mjs",
32
+ "CHANGELOG.md"
32
33
  ],
33
34
  "engines": {
34
- "node": ">=18"
35
+ "node": "^22.18.0 || >=24.11.0"
35
36
  },
36
37
  "dependencies": {
37
- "@modelcontextprotocol/sdk": "^1.0.0",
38
- "zod": "^3.23.0"
38
+ "@modelcontextprotocol/sdk": "^1.30.0",
39
+ "zod": "^3.25.0",
40
+ "astralis-cli": "^0.6.0"
39
41
  },
40
42
  "scripts": {
41
- "start": "node server.mjs"
43
+ "start": "node server.mjs",
44
+ "test": "node --test \"test/*.test.mjs\""
42
45
  }
43
46
  }
package/server.mjs CHANGED
@@ -1,61 +1,104 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * Astralis UI MCP server — gives AI coding agents current component APIs
4
- * instead of hallucinated ones.
4
+ * instead of hallucinated ones, and a validator to judge what they write:
5
+ * retrieval AND verification (validate_code), so an agent can close its own
6
+ * write -> validate -> fix loop against the design system's ground truth.
5
7
  *
6
8
  * Data source: the deployed docs site's machine-readable endpoints
7
- * (/llms.txt, /docs/components/*.md, /docs/*.md) and its block registry
8
- * (/r/index.json, /r/{id}.json) — the same single pipeline that renders the
9
- * human docs, so answers can never drift from the site.
10
- * Point ASTRALIS_DOCS_URL at a local dev server (http://localhost:3000)
11
- * when working on unpublished docs.
9
+ * (/llms.txt, /llms-full.txt, /docs/components/*.md, /docs/*.md,
10
+ * /system-spec.json) and its block registry (/r/index.json, /r/{id}.json),
11
+ * the same pipeline that renders the human docs. Point ASTRALIS_DOCS_URL at a
12
+ * local dev server (http://localhost:3000) when working on unpublished docs.
12
13
  *
13
14
  * Register in an MCP client:
14
15
  * { "command": "npx", "args": ["-y", "astralis-mcp"] }
15
16
  */
16
- import { readFileSync } from "node:fs";
17
+ import { readFileSync, statSync } from "node:fs";
17
18
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
18
19
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
19
20
  import { z } from "zod";
21
+ import { prepareSpec, validateSource, findInstalledSpec } from "astralis-cli/validate";
20
22
 
21
23
  /** Single source of truth for the version — the handshake can't drift from what npm publishes. */
22
24
  const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
23
25
 
24
- const SITE = (process.env.ASTRALIS_DOCS_URL ?? "https://astralis-zeta.vercel.app").replace(/\/$/, "");
26
+ const SITE = (process.env.ASTRALIS_DOCS_URL ?? "https://astralis-ui.com").replace(/\/$/, "");
25
27
 
26
28
  /*
27
- * A localhost docs URL means someone is editing docs live — never hand them a
28
- * stale copy. A deployed site is cached, but only briefly, so a long-lived
29
- * server still picks up doc updates without a restart.
29
+ * A localhost docs URL means someone is editing docs live, so nothing is
30
+ * cached. A deployed site is cached briefly, so a long-lived server still
31
+ * picks up doc updates without a restart.
30
32
  */
31
33
  const isLocal = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(?::|\/|$)/.test(SITE);
32
34
  const TTL_MS = 5 * 60_000;
33
35
  const FETCH_TIMEOUT_MS = 10_000;
36
+ /** Remote text goes straight into an agent's context: anything bigger than this is refused. */
37
+ const MAX_RESPONSE_BYTES = 5_000_000;
34
38
 
35
39
  /* ---------- data: fetched on demand, cached with a short TTL ---------- */
36
40
 
41
+ /** The site answered, but not with the page: `status` tells a missing page (404) from a broken one. */
42
+ class HttpError extends Error {
43
+ constructor(status, url) {
44
+ super(`${status} for ${url}`);
45
+ this.status = status;
46
+ }
47
+ }
48
+
49
+ class TooLargeError extends Error {}
50
+
37
51
  const cache = new Map(); // path -> { text, at }
38
52
 
53
+ async function readCapped(response, url) {
54
+ const declared = Number(response.headers.get("content-length"));
55
+ if (declared > MAX_RESPONSE_BYTES) {
56
+ await response.body?.cancel();
57
+ throw new TooLargeError(`${url} is larger than ${MAX_RESPONSE_BYTES} bytes`);
58
+ }
59
+ const chunks = [];
60
+ let size = 0;
61
+ for await (const chunk of response.body) {
62
+ size += chunk.byteLength;
63
+ if (size > MAX_RESPONSE_BYTES) throw new TooLargeError(`${url} is larger than ${MAX_RESPONSE_BYTES} bytes`);
64
+ chunks.push(chunk);
65
+ }
66
+ return Buffer.concat(chunks).toString("utf8");
67
+ }
68
+
39
69
  async function fetchText(path) {
40
70
  const hit = cache.get(path);
41
71
  if (hit && !isLocal && Date.now() - hit.at < TTL_MS) return hit.text;
42
72
 
43
- const ctrl = new AbortController();
44
- const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
73
+ const url = `${SITE}${path}`;
74
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
45
75
  try {
46
- const res = await fetch(`${SITE}${path}`, { signal: ctrl.signal });
47
- if (!res.ok) throw new Error(`${res.status} for ${SITE}${path}`);
48
- const text = await res.text();
76
+ const res = await fetch(url, { signal });
77
+ if (!res.ok) {
78
+ await res.body?.cancel();
79
+ throw new HttpError(res.status, url);
80
+ }
81
+ const text = await readCapped(res, url);
49
82
  cache.set(path, { text, at: Date.now() });
50
83
  return text;
51
84
  } catch (err) {
52
- if (err.name === "AbortError") throw new Error(`timed out after ${FETCH_TIMEOUT_MS}ms for ${SITE}${path}`);
85
+ if (signal.aborted) throw new Error(`timed out after ${FETCH_TIMEOUT_MS}ms for ${url}`);
53
86
  throw err;
54
- } finally {
55
- clearTimeout(timer);
56
87
  }
57
88
  }
58
89
 
90
+ /** A page's text, or null when the site says it doesn't exist. Any other failure throws. */
91
+ async function fetchOptional(path) {
92
+ try {
93
+ return await fetchText(path);
94
+ } catch (err) {
95
+ if (err instanceof HttpError && err.status === 404) return null;
96
+ throw err;
97
+ }
98
+ }
99
+
100
+ const SLUG = /^[a-z0-9-]+$/;
101
+
59
102
  /** Parse llms.txt into [{slug, title, description, section, kind}]. */
60
103
  async function listPages() {
61
104
  const index = await fetchText("/llms.txt");
@@ -78,10 +121,26 @@ async function listPages() {
78
121
  }
79
122
 
80
123
  /**
81
- * The block registry, served as static JSON by the same docs deploy
82
- * (astralis-docs/scripts/gen-block-registry.mjs). Reusing fetchText means
83
- * blocks get the same cache, timeout and local-dev override as the docs.
124
+ * llms-full.txt split back into pages. Each page opens with a marker
125
+ * `<!-- Section / Title — /docs/[components/]slug -->` (astralis-docs
126
+ * src/app/llms-full.txt/route.ts).
84
127
  */
128
+ async function corpusPages() {
129
+ const corpus = await fetchText("/llms-full.txt");
130
+ const marker = /^<!-- .+ — \/docs\/(?:(components)\/)?([a-z0-9-]+) -->$/gm;
131
+ const found = [...corpus.matchAll(marker)];
132
+ return found.map((m, i) => ({
133
+ slug: m[2],
134
+ kind: m[1] ? "component" : "guide",
135
+ body: corpus.slice(m.index + m[0].length, found[i + 1]?.index ?? corpus.length),
136
+ }));
137
+ }
138
+
139
+ async function pageMarkdown(slug, kind) {
140
+ if (!SLUG.test(slug)) return null;
141
+ return fetchOptional(kind === "guide" ? `/docs/${slug}.md` : `/docs/components/${slug}.md`);
142
+ }
143
+
85
144
  async function fetchJson(path) {
86
145
  return JSON.parse(await fetchText(path));
87
146
  }
@@ -92,186 +151,261 @@ async function blockCatalogue() {
92
151
 
93
152
  /** One registry item, source included. Null when the id is unknown. */
94
153
  async function blockItem(id) {
95
- if (!/^[a-z0-9-]+$/.test(id)) return null;
96
- try {
97
- return await fetchJson(`/r/${id}.json`);
98
- } catch {
99
- return null;
100
- }
101
- }
102
-
103
- async function pageMarkdown(slug, kind) {
104
- if (!/^[a-z0-9-]+$/.test(slug)) return null;
105
- try {
106
- return await fetchText(kind === "guide" ? `/docs/${slug}.md` : `/docs/components/${slug}.md`);
107
- } catch {
108
- return null;
109
- }
154
+ if (!SLUG.test(id)) return null;
155
+ const text = await fetchOptional(`/r/${id}.json`);
156
+ return text === null ? null : JSON.parse(text);
110
157
  }
111
158
 
112
159
  const asText = (text) => ({ content: [{ type: "text", text }] });
113
160
  const asError = (text) => ({ content: [{ type: "text", text }], isError: true });
161
+ /** A fetch that failed, as an error result: never mistaken for "unknown" or an empty answer. */
114
162
  const offline = (err) =>
115
- asError(`Could not reach the Astralis docs at ${SITE} (${err.message}). Check your connection, or set ASTRALIS_DOCS_URL.`);
163
+ err instanceof HttpError
164
+ ? asError(`The Astralis docs at ${SITE} answered ${err.message}. Try again later, or set ASTRALIS_DOCS_URL.`)
165
+ : err instanceof TooLargeError
166
+ ? asError(`Refused a response from the Astralis docs: ${err.message}.`)
167
+ : asError(`Could not reach the Astralis docs at ${SITE} (${err.message}). Check your connection, or set ASTRALIS_DOCS_URL.`);
116
168
 
117
169
  /* ---------- server ---------- */
118
170
 
119
171
  const server = new McpServer({ name: "astralis-ui", version: pkg.version });
120
172
 
121
- server.tool(
173
+ /** Every tool only reads; the docs ones read from the web. A failed fetch is always an error result. */
174
+ function tool(name, { title, description, inputSchema = {} }, handler) {
175
+ server.registerTool(
176
+ name,
177
+ {
178
+ title,
179
+ description,
180
+ inputSchema,
181
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
182
+ },
183
+ async (args) => {
184
+ try {
185
+ return await handler(args);
186
+ } catch (err) {
187
+ return offline(err);
188
+ }
189
+ },
190
+ );
191
+ }
192
+
193
+ tool(
122
194
  "list_components",
123
- "List every Astralis UI docs page — all components plus every guide — each with slug, one-line description, category, and kind (component | guide). Call this first to discover valid slugs.",
124
- {},
125
- async () => {
126
- try {
127
- return asText(JSON.stringify(await listPages(), null, 2));
128
- } catch (err) {
129
- return offline(err);
130
- }
195
+ {
196
+ title: "List docs pages",
197
+ description:
198
+ "List every Astralis UI docs page — all components plus every guide — each with slug, title, one-line description, section, and kind (component | guide). Call this first to discover valid slugs.",
131
199
  },
200
+ async () => asText(JSON.stringify(await listPages(), null, 2)),
132
201
  );
133
202
 
134
- server.tool(
203
+ tool(
135
204
  "get_component",
136
- "Full documentation for one component as markdown: usage, complete props table, keyboard/accessibility notes, and runnable demo source code. Use the slug from list_components.",
137
- { slug: z.string().describe("Component docs slug, e.g. 'button', 'number-input'") },
205
+ {
206
+ title: "Get component docs",
207
+ description:
208
+ "Full documentation for one component as markdown: usage, complete props table, keyboard/accessibility notes, and runnable demo source code. Use the slug from list_components.",
209
+ inputSchema: { slug: z.string().describe("Component docs slug, e.g. 'button', 'number-input'") },
210
+ },
138
211
  async ({ slug }) => {
139
- try {
140
- const md = await pageMarkdown(slug, "component");
141
- return md
142
- ? asText(md)
143
- : asError(`Unknown component "${slug}". Call list_components for valid slugs.`);
144
- } catch (err) {
145
- return offline(err);
146
- }
212
+ const md = await pageMarkdown(slug, "component");
213
+ return md ? asText(md) : asError(`Unknown component "${slug}". Call list_components for valid slugs.`);
147
214
  },
148
215
  );
149
216
 
150
- server.tool(
217
+ tool(
151
218
  "get_guide",
152
- "One Astralis guide page as markdown — e.g. installation, theming, tokens. Use a guide slug from list_components for the full set.",
153
- { slug: z.string().describe("Guide slug, e.g. 'installation', 'theming', 'tokens'") },
219
+ {
220
+ title: "Get a guide",
221
+ description:
222
+ "One Astralis guide page as markdown — e.g. installation, theming, tokens. Use a guide slug from list_components for the full set.",
223
+ inputSchema: { slug: z.string().describe("Guide slug, e.g. 'installation', 'theming', 'tokens'") },
224
+ },
154
225
  async ({ slug }) => {
155
- try {
156
- const md = await pageMarkdown(slug, "guide");
157
- if (md) return asText(md);
158
- const guides = (await listPages()).filter((p) => p.kind === "guide").map((p) => p.slug);
159
- return asError(`Unknown guide "${slug}". Valid guides: ${guides.join(", ")}.`);
160
- } catch (err) {
161
- return offline(err);
162
- }
226
+ const md = await pageMarkdown(slug, "guide");
227
+ if (md) return asText(md);
228
+ const guides = (await listPages()).filter((p) => p.kind === "guide").map((p) => p.slug);
229
+ return asError(`Unknown guide "${slug}". Valid guides: ${guides.join(", ")}.`);
163
230
  },
164
231
  );
165
232
 
166
- server.tool(
233
+ tool(
167
234
  "search_docs",
168
- "Full-text search across all Astralis documentation (guides + components). Returns matching pages with a snippet around the first hit.",
169
- { query: z.string().describe("Search text, e.g. 'focus trap' or 'aria-describedby'") },
235
+ {
236
+ title: "Search the docs",
237
+ description:
238
+ "Full-text search across all Astralis documentation (guides + components). Returns matching pages with a snippet around the first hit.",
239
+ inputSchema: { query: z.string().describe("Search text, e.g. 'focus trap' or 'aria-describedby'") },
240
+ },
170
241
  async ({ query }) => {
171
- try {
172
- const q = query.toLowerCase();
173
- const hits = [];
174
- for (const page of await listPages()) {
175
- const md = (await pageMarkdown(page.slug, page.kind)) ?? "";
176
- const idx = md.toLowerCase().indexOf(q);
177
- if (idx === -1) continue;
178
- hits.push({ ...page, snippet: md.slice(Math.max(0, idx - 80), idx + 120).replace(/\s+/g, " ") });
179
- }
180
- return asText(hits.length ? JSON.stringify(hits, null, 2) : "No matches.");
181
- } catch (err) {
182
- return offline(err);
242
+ const q = query.toLowerCase();
243
+ const [pages, index] = await Promise.all([corpusPages(), listPages()]);
244
+ const meta = new Map(index.map((p) => [`${p.kind}:${p.slug}`, p]));
245
+ const hits = [];
246
+ for (const page of pages) {
247
+ const idx = page.body.toLowerCase().indexOf(q);
248
+ if (idx === -1) continue;
249
+ const { title = page.slug, description = "", section = "" } = meta.get(`${page.kind}:${page.slug}`) ?? {};
250
+ const snippet = page.body.slice(Math.max(0, idx - 80), idx + 120).replace(/\s+/g, " ").trim();
251
+ hits.push({ slug: page.slug, title, description, section, kind: page.kind, snippet });
183
252
  }
253
+ return asText(hits.length ? JSON.stringify(hits, null, 2) : "No matches.");
184
254
  },
185
255
  );
186
256
 
187
- server.tool(
257
+ tool(
188
258
  "get_theming",
189
- "The complete Astralis theming reference: the token system, dark mode, runtime brand color, colorScheme/accent channel, plus every design-token scale (spacing, sizing, type, radius, shadows, motion).",
190
- {},
259
+ {
260
+ title: "Get the theming reference",
261
+ description:
262
+ "The complete Astralis theming reference: the token system, dark mode, runtime brand color, colorScheme/accent channel, plus every design-token scale (spacing, sizing, type, radius, shadows, motion).",
263
+ },
191
264
  async () => {
192
- try {
193
- const [theming, tokens] = await Promise.all([
194
- pageMarkdown("theming", "guide"),
195
- pageMarkdown("tokens", "guide"),
196
- ]);
197
- return asText([theming ?? "", "\n---\n", tokens ?? ""].join("\n"));
198
- } catch (err) {
199
- return offline(err);
200
- }
265
+ const [theming, tokens] = await Promise.all([pageMarkdown("theming", "guide"), pageMarkdown("tokens", "guide")]);
266
+ const missing = [!theming && "theming", !tokens && "tokens"].filter(Boolean);
267
+ if (missing.length) return asError(`The docs site has no ${missing.join(" or ")} page, so the reference is incomplete.`);
268
+ return asText([theming, "\n---\n", tokens].join("\n"));
201
269
  },
202
270
  );
203
271
 
204
272
  /* ---------- blocks ---------- */
205
273
 
206
- server.tool(
274
+ tool(
207
275
  "list_blocks",
208
- "List every Astralis block — prebuilt page sections (hero, pricing, dashboard, login…) composed from Astralis UI components. Each entry has id, name, description, category and the components it composes. Call this first to discover valid block ids. Pass a category to narrow the list.",
209
276
  {
210
- category: z
211
- .string()
212
- .optional()
213
- .describe("Optional filter, e.g. 'hero', 'pricing', 'dashboard', 'login'"),
277
+ title: "List blocks",
278
+ description:
279
+ "List every Astralis block — prebuilt page sections (hero, pricing, dashboard, login…) composed from Astralis UI components. Each entry has id, name, description, category and the components it composes. Call this first to discover valid block ids. Pass a category to narrow the list.",
280
+ inputSchema: {
281
+ category: z.string().optional().describe("Optional filter, e.g. 'hero', 'pricing', 'dashboard', 'login'"),
282
+ },
214
283
  },
215
284
  async ({ category }) => {
216
- try {
217
- const blocks = await blockCatalogue();
218
- if (!category) return asText(JSON.stringify(blocks, null, 2));
219
-
220
- const wanted = category.toLowerCase();
221
- const filtered = blocks.filter((b) => b.category === wanted);
222
- if (filtered.length) return asText(JSON.stringify(filtered, null, 2));
223
-
224
- const categories = [...new Set(blocks.map((b) => b.category))].sort();
225
- return asError(`No blocks in category "${category}". Categories: ${categories.join(", ")}.`);
226
- } catch (err) {
227
- return offline(err);
228
- }
285
+ const blocks = await blockCatalogue();
286
+ if (!category) return asText(JSON.stringify(blocks, null, 2));
287
+
288
+ const filtered = blocks.filter((b) => b.category === category.toLowerCase());
289
+ if (filtered.length) return asText(JSON.stringify(filtered, null, 2));
290
+
291
+ const categories = [...new Set(blocks.map((b) => b.category))].sort();
292
+ return asError(`No blocks in category "${category}". Categories: ${categories.join(", ")}.`);
229
293
  },
230
294
  );
231
295
 
232
- server.tool(
296
+ tool(
233
297
  "get_block",
234
- "One Astralis block: its metadata plus the complete source of every file it contains, ready to write into a project. A block depends only on astralis-ui — no other packages, no Tailwind config, no per-block setup. Use an id from list_blocks.",
235
- { id: z.string().describe("Block id, e.g. 'hero-01', 'pricing-02', 'dashboard-03'") },
298
+ {
299
+ title: "Get a block's source",
300
+ description:
301
+ "One Astralis block: its metadata plus the complete source of every file it contains, ready to write into a project. A block depends only on astralis-ui — no other packages, no Tailwind config, no per-block setup. Use an id from list_blocks.",
302
+ inputSchema: { id: z.string().describe("Block id, e.g. 'hero-01', 'pricing-02', 'dashboard-03'") },
303
+ },
236
304
  async ({ id }) => {
237
- try {
238
- const block = await blockItem(id);
239
- if (!block) {
240
- const ids = (await blockCatalogue()).map((b) => b.id);
241
- return asError(`Unknown block "${id}". Valid ids: ${ids.join(", ")}.`);
242
- }
305
+ const block = await blockItem(id);
306
+ if (!block) {
307
+ const ids = (await blockCatalogue()).map((b) => b.id);
308
+ return asError(`Unknown block "${id}". Valid ids: ${ids.join(", ")}.`);
309
+ }
243
310
 
244
- /*
245
- * Markdown rather than raw JSON: the payload is mostly source code, and
246
- * fenced blocks keep an agent from having to unescape a JSON string
247
- * before it can write the file.
248
- */
249
- const sections = [
250
- `# ${block.name}`,
251
- "",
252
- block.description,
253
- "",
254
- `- **id** \`${block.id}\` · **category** \`${block.category}\``,
255
- `- **exports** \`${block.component}\``,
256
- `- **composes** ${block.uses.map((u) => `\`${u}\``).join(", ")}`,
257
- `- **preview** ${SITE}/blocks/${block.id}`,
258
- "",
259
- `Install with \`astralis add ${block.id}\`, or write the files below yourself —`,
260
- `they belong to the project once copied. The only dependency is \`astralis-ui\`.`,
261
- "",
262
- ];
263
-
264
- for (const file of block.contents) {
265
- const lang = file.path.endsWith(".tsx") || file.path.endsWith(".ts") ? "tsx" : "";
266
- sections.push(`## ${file.path}`, "", `\`\`\`${lang}`, file.content.trimEnd(), "```", "");
267
- }
311
+ // Markdown, not JSON: the payload is mostly source, and fenced blocks
312
+ // spare the agent unescaping a JSON string before writing the file.
313
+ const sections = [
314
+ `# ${block.name}`,
315
+ "",
316
+ block.description,
317
+ "",
318
+ `- **id** \`${block.id}\` · **category** \`${block.category}\``,
319
+ `- **exports** \`${block.component}\``,
320
+ `- **composes** ${block.uses.map((u) => `\`${u}\``).join(", ")}`,
321
+ `- **preview** ${SITE}/blocks/${block.id}`,
322
+ "",
323
+ `Install with \`npx astralis-cli add ${block.id}\`, or write the files below yourself —`,
324
+ `they belong to the project once copied. The only dependency is \`astralis-ui\`.`,
325
+ "",
326
+ ];
327
+ for (const file of block.contents) {
328
+ const lang = file.path.endsWith(".tsx") || file.path.endsWith(".ts") ? "tsx" : "";
329
+ sections.push(`## ${file.path}`, "", `\`\`\`${lang}`, file.content.trimEnd(), "```", "");
330
+ }
331
+ return asText(sections.join("\n"));
332
+ },
333
+ );
334
+
335
+ /* ---------- validation ---------- */
336
+
337
+ /*
338
+ * The judge half of verified generation: pure local computation, no model.
339
+ * The spec comes from the project's own installed astralis-ui (the version
340
+ * the code must conform to); with none nearby (a desktop client spawned at
341
+ * $HOME) it falls back to the spec of the version the docs site documents.
342
+ */
343
+ let specState = null; // { key, prepared, version, source }
268
344
 
269
- return asText(sections.join("\n"));
270
- } catch (err) {
271
- return offline(err);
345
+ async function resolveSpec() {
346
+ const localPath = findInstalledSpec(process.cwd());
347
+ if (localPath) {
348
+ const key = `${localPath}@${statSync(localPath).mtimeMs}`;
349
+ if (specState?.key !== key) {
350
+ const spec = JSON.parse(readFileSync(localPath, "utf8"));
351
+ specState = { key, prepared: prepareSpec(spec), version: spec.version, source: "installed astralis-ui" };
272
352
  }
353
+ return specState;
354
+ }
355
+ // fetchText's TTL decides freshness; re-prepare only when the text changed.
356
+ const text = await fetchText("/system-spec.json");
357
+ if (specState?.key !== text) {
358
+ const spec = JSON.parse(text);
359
+ specState = {
360
+ key: text,
361
+ prepared: prepareSpec(spec),
362
+ version: spec.version,
363
+ source: `docs site (${SITE}) — no local astralis-ui found, validated against the latest published version`,
364
+ };
365
+ }
366
+ return specState;
367
+ }
368
+
369
+ tool(
370
+ "validate_code",
371
+ {
372
+ title: "Validate Astralis code",
373
+ description:
374
+ "Validate Astralis UI TSX/JSX against the design system's machine-readable spec. Catches what typechecking cannot: components and compound parts that don't exist, prop values outside their token sets, astralis:* classes missing from the compiled CSS (they render as nothing), undeclared token variables, illegal breakpoint/state keys, broken compound anatomy, Tabs trigger/panel mismatches, and a11y mistakes (typo'd aria-* attributes, invalid roles, missing alt). ALWAYS run this on Astralis code you generate or edit BEFORE presenting it; fix every error, then validate again until clean. Errors include the valid alternatives, so they are directly actionable.",
375
+ inputSchema: {
376
+ code: z
377
+ .string()
378
+ .describe("The complete TSX/JSX source to validate (a whole file or a self-contained snippet with its astralis-ui imports)"),
379
+ strict_tokens: z
380
+ .boolean()
381
+ .optional()
382
+ .describe("Also warn on valid-but-off-token colors (design-system drift check). Default false."),
383
+ },
384
+ },
385
+ async ({ code, strict_tokens }) => {
386
+ const spec = await resolveSpec();
387
+ const { errors, warnings } = validateSource(code, spec.prepared, "<code>", { strictTokens: strict_tokens ?? false });
388
+ const valid = errors.length === 0;
389
+ return {
390
+ content: [{
391
+ type: "text",
392
+ text: JSON.stringify(
393
+ {
394
+ valid,
395
+ spec: { version: spec.version, source: spec.source },
396
+ summary: valid
397
+ ? `valid against astralis-ui@${spec.version}${warnings.length ? ` (${warnings.length} warning(s))` : ""}`
398
+ : `${errors.length} error(s), ${warnings.length} warning(s) — fix the errors and validate again`,
399
+ errors,
400
+ warnings,
401
+ },
402
+ null,
403
+ 2,
404
+ ),
405
+ }],
406
+ isError: false,
407
+ };
273
408
  },
274
409
  );
275
410
 
276
- const transport = new StdioServerTransport();
277
- await server.connect(transport);
411
+ await server.connect(new StdioServerTransport());