@newtui/mcp 0.0.0-stage → 0.1.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.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +60 -2
  3. package/dist/index.js +490 -0
  4. package/package.json +58 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing
141
+ the origin of the Work and reproducing the content of the NOTICE
142
+ file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 wolfstar-project
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @newtui/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [MCP](https://modelcontextprotocol.io) server for the [newt/ui](https://newtui.dev) documentation — Discord-inspired components for React, Vue and plain HTML/CSS. It gives your editor's agent the docs themselves: installation per framework, theming, the token reference, accessibility notes and the registry format, read from the site rather than recalled from memory.
4
+
5
+ It is the companion to `newtui mcp`, the server inside the CLI: that one answers _which components exist and what their source is_; this one answers _what the documentation says_. Run both.
6
+
7
+ ```bash
8
+ npx @newtui/mcp
9
+ ```
10
+
11
+ ## Tools
12
+
13
+ Every tool is read-only.
14
+
15
+ | Tool | What it returns |
16
+ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
17
+ | `list_docs` | Every page with its title, route, description and section. `section` filters to one heading of the index, e.g. `Installation`. |
18
+ | `search_docs` | Pages ranked by where every keyword appears — title, route, description, section. `content: true` searches page bodies too and adds an excerpt. |
19
+ | `get_doc` | One page as Markdown. Takes a route (`/docs/theming`), a slug (`button`, `installation/nuxt`) or a full URL; an unknown page answers with matches. |
20
+
21
+ ## Configure your client
22
+
23
+ ```json
24
+ {
25
+ "mcpServers": {
26
+ "newtui-docs": {
27
+ "command": "npx",
28
+ "args": ["-y", "@newtui/mcp@latest"]
29
+ }
30
+ }
31
+ }
32
+ ```
33
+
34
+ That shape works for Claude Code (`.mcp.json`), Cursor (`.cursor/mcp.json`) and most other clients. Claude Code can also add it in one line:
35
+
36
+ ```bash
37
+ claude mcp add newtui-docs -- npx -y @newtui/mcp@latest
38
+ ```
39
+
40
+ ## Pointing it at another site
41
+
42
+ The site resolves as `--url` > `NEWTUI_DOCS_URL` > `https://newtui.dev`:
43
+
44
+ ```bash
45
+ npx @newtui/mcp --url http://localhost:4321
46
+ NEWTUI_DOCS_URL=http://localhost:4321 npx @newtui/mcp
47
+ ```
48
+
49
+ The server reads what the site publishes for agents: `llms.txt` for the page index, `llms-full.txt` for full-text search, and the `.md` twin of every page. The Blume dev server serves the twins but not the two `llms` files, so against `localhost:4321` the index comes from the JSON docs API (`/api/docs/pages.json`) and `search_docs` falls back to titles and descriptions — the answer says so in `searchedContent`. A built site (`pnpm --filter docs build`, then any static server on `apps/docs/dist`) has everything.
50
+
51
+ Responses are cached in memory for five minutes; a 404 is cached too, a server error is not.
52
+
53
+ ## Development
54
+
55
+ ```bash
56
+ pnpm build # tsdown -> dist/index.js
57
+ pnpm typecheck # tsc --noEmit
58
+ pnpm test # vitest, with the network replaced by an in-memory site
59
+ ```
60
+
61
+ newt/ui is an independent, community-built project. It is visually inspired by Discord's client but is not affiliated with, endorsed by, or sponsored by Discord Inc.
package/dist/index.js ADDED
@@ -0,0 +1,490 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { z } from "zod";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+
7
+ // package.json
8
+ var version = "0.1.1";
9
+
10
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js
11
+ function _typeof(o) {
12
+ "@babel/helpers - typeof";
13
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
14
+ return typeof o;
15
+ } : function(o) {
16
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
17
+ }, _typeof(o);
18
+ }
19
+
20
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js
21
+ function toPrimitive(t, e) {
22
+ if ("object" != _typeof(t) || !t) return t;
23
+ var r;
24
+ if ("undefined" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {
25
+ var i = r.call(t, e || "default");
26
+ if ("object" != _typeof(i)) return i;
27
+ throw new TypeError("@@toPrimitive must return a primitive value.");
28
+ }
29
+ return ("string" === e ? String : Number)(t);
30
+ }
31
+
32
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js
33
+ function toPropertyKey(t) {
34
+ var i = toPrimitive(t, "string");
35
+ return "symbol" == _typeof(i) ? i : i + "";
36
+ }
37
+
38
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js
39
+ function _defineProperty(e, r, t) {
40
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
41
+ value: t,
42
+ enumerable: !0,
43
+ configurable: !0,
44
+ writable: !0
45
+ }) : e[r] = t, e;
46
+ }
47
+
48
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/checkPrivateRedeclaration.js
49
+ function _checkPrivateRedeclaration(e, t) {
50
+ if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
51
+ }
52
+
53
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/classPrivateMethodInitSpec.js
54
+ function _classPrivateMethodInitSpec(e, a) {
55
+ _checkPrivateRedeclaration(e, a), a.add(e);
56
+ }
57
+
58
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/classPrivateFieldInitSpec.js
59
+ function _classPrivateFieldInitSpec(e, t, a) {
60
+ _checkPrivateRedeclaration(e, t), t.set(e, a);
61
+ }
62
+
63
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/assertClassBrand.js
64
+ function _assertClassBrand(e, t, n) {
65
+ if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
66
+ throw new TypeError("Private element is not present on this object");
67
+ }
68
+
69
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/classPrivateFieldSet2.js
70
+ function _classPrivateFieldSet2(s, a, r) {
71
+ return s.set(_assertClassBrand(s, a), r), r;
72
+ }
73
+
74
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/classPrivateFieldGet2.js
75
+ function _classPrivateFieldGet2(s, a) {
76
+ return s.get(_assertClassBrand(s, a));
77
+ }
78
+
79
+ // src/docs.ts
80
+ const DEFAULT_DOCS_URL = "https://newtui.dev";
81
+ /** How long a fetched document stays fresh, in milliseconds. */
82
+ const DEFAULT_CACHE_TTL = 3e5;
83
+ var DocsRequestError = class extends Error {
84
+ constructor(url, status) {
85
+ super(`GET ${url} answered ${status}`);
86
+ _defineProperty(this, "url", void 0);
87
+ _defineProperty(this, "status", void 0);
88
+ this.name = "DocsRequestError";
89
+ this.url = url;
90
+ this.status = status;
91
+ }
92
+ };
93
+ /** The subset of Blume's JSON docs API the fallback index reads. */
94
+ const pagesApiSchema = z.object({ pages: z.array(z.object({
95
+ route: z.string(),
96
+ title: z.string(),
97
+ description: z.string().optional(),
98
+ contentType: z.string().optional()
99
+ })) });
100
+ /** The docs site resolves as `--url` > `NEWTUI_DOCS_URL` > the default. */
101
+ function resolveDocsUrl(flag, env) {
102
+ return [flag, env].find((value) => value !== void 0 && value.trim() !== "")?.trim() ?? "https://newtui.dev";
103
+ }
104
+ /** Strip the trailing slash so `${base}${path}` never doubles one. */
105
+ function normaliseBaseUrl(url) {
106
+ return new URL(url).toString().replace(/\/+$/u, "");
107
+ }
108
+ const DEFAULT_HOST = new URL(DEFAULT_DOCS_URL).host;
109
+ function pagePathOf(href, base) {
110
+ const link = new URL(href, base);
111
+ if (link.host !== base.host && link.host !== DEFAULT_HOST) return null;
112
+ const path = link.pathname.replace(/\/+$/u, "") || "/";
113
+ const segments = path.split("/");
114
+ const last = segments.at(-1) ?? "";
115
+ if (segments.some((segment) => segment.startsWith(".")) || last.includes(".")) return null;
116
+ return path;
117
+ }
118
+ const LINK_LINE = /^- \[(?<title>[^\]]+)\]\((?<href>[^)\s]+)\)(?::\s*(?<description>.*))?$/u;
119
+ /** Parse an `llms.txt` page index into entries rebased on `baseUrl`. */
120
+ function parseLlmsTxt(source, baseUrl) {
121
+ const base = new URL(baseUrl);
122
+ const entries = [];
123
+ const seen = /* @__PURE__ */ new Set();
124
+ let section;
125
+ for (const line of source.split("\n")) {
126
+ if (line.startsWith("## ")) {
127
+ section = line.slice(3).trim();
128
+ continue;
129
+ }
130
+ const groups = LINK_LINE.exec(line.trim())?.groups;
131
+ if (groups?.title === void 0 || groups.href === void 0) continue;
132
+ const path = pagePathOf(groups.href, base);
133
+ if (path === null || seen.has(path)) continue;
134
+ seen.add(path);
135
+ entries.push(toEntry(baseUrl, path, groups.title, groups.description?.trim(), section));
136
+ }
137
+ return entries;
138
+ }
139
+ /** Parse Blume's `/api/docs/pages.json` into the same entries. */
140
+ function parsePagesApi(source, baseUrl) {
141
+ const { pages } = pagesApiSchema.parse(JSON.parse(source));
142
+ return pages.filter((page) => page.route !== "/404").map((page) => toEntry(baseUrl, page.route.replace(/\/+$/u, "") || "/", page.title, page.description, page.contentType));
143
+ }
144
+ function parseLlmsFull(source, baseUrl) {
145
+ const base = new URL(baseUrl);
146
+ const lines = source.split("\n");
147
+ const starts = [];
148
+ for (let index = 1; index < lines.length; index++) {
149
+ const href = /^Source: (?<href>\S+)$/u.exec(lines[index] ?? "")?.groups?.href;
150
+ if (href === void 0 || !(lines[index - 1] ?? "").startsWith("# ")) continue;
151
+ const path = pagePathOf(href, base);
152
+ if (path !== null) starts.push({
153
+ path,
154
+ heading: index - 1
155
+ });
156
+ }
157
+ const bodies = /* @__PURE__ */ new Map();
158
+ starts.forEach((start, position) => {
159
+ const end = starts[position + 1]?.heading ?? lines.length;
160
+ bodies.set(start.path, lines.slice(start.heading + 2, end).join("\n").trim());
161
+ });
162
+ return bodies;
163
+ }
164
+ function toEntry(baseUrl, path, title, description, section) {
165
+ const entry = {
166
+ title,
167
+ path,
168
+ url: `${baseUrl}${path === "/" ? "" : path}`,
169
+ markdownUrl: `${baseUrl}${markdownPathFor(path)}`
170
+ };
171
+ if (description !== void 0 && description !== "") entry.description = description;
172
+ if (section !== void 0) entry.section = section;
173
+ return entry;
174
+ }
175
+ /** Blume writes `/docs.md` for `/docs` and `/index.md` for the home page. */
176
+ function markdownPathFor(path) {
177
+ return path === "/" ? "/index.md" : `${path}.md`;
178
+ }
179
+ /**
180
+ * Turn whatever an agent passes — a slug, a route, a full URL, with or
181
+ * without `.md` — into a site-relative route.
182
+ */
183
+ function toRoute(input) {
184
+ let value = input.trim();
185
+ if (/^https?:\/\//u.test(value)) value = new URL(value).pathname;
186
+ value = value.replace(/[?#].*$/u, "").replace(/\.mdx?$/u, "").replace(/\/+$/u, "");
187
+ if (value === "" || value === "/index") return "/";
188
+ return value.startsWith("/") ? value : `/${value}`;
189
+ }
190
+ function terms(query) {
191
+ return query.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((term) => term.length > 0);
192
+ }
193
+ function countOccurrences(haystack, needle) {
194
+ let count = 0;
195
+ let index = haystack.indexOf(needle);
196
+ while (index !== -1) {
197
+ count++;
198
+ index = haystack.indexOf(needle, index + needle.length);
199
+ }
200
+ return count;
201
+ }
202
+ function excerptOf(body, query, words) {
203
+ const lines = body.split("\n").map((line) => line.trim());
204
+ const lowered = lines.map((line) => line.toLowerCase());
205
+ const phrase = query.trim().toLowerCase();
206
+ const tests = [
207
+ (line) => line.includes(phrase),
208
+ (line) => words.every((word) => line.includes(word)),
209
+ (line) => words.some((word) => line.includes(word))
210
+ ];
211
+ for (const test of tests) {
212
+ const index = lowered.findIndex(test);
213
+ const line = lines[index];
214
+ if (index !== -1 && line !== void 0) return line.length > 200 ? `${line.slice(0, 197)}...` : line;
215
+ }
216
+ }
217
+ /**
218
+ * Rank entries against a keyword query. Every term has to appear somewhere —
219
+ * the title, the route, the description, the section or (when given) the
220
+ * body — and where it appears decides the weight.
221
+ */
222
+ function rankEntries(entries, query, bodies) {
223
+ const words = terms(query);
224
+ if (words.length === 0) return [];
225
+ const phrase = words.join(" ");
226
+ const hits = [];
227
+ for (const entry of entries) {
228
+ const title = entry.title.toLowerCase();
229
+ const titleWords = new Set(terms(entry.title));
230
+ const route = entry.path.toLowerCase();
231
+ const description = (entry.description ?? "").toLowerCase();
232
+ const section = (entry.section ?? "").toLowerCase();
233
+ const body = bodies?.get(entry.path)?.toLowerCase() ?? "";
234
+ let score = title === phrase ? 20 : title.includes(phrase) ? 8 : 0;
235
+ let everyTermFound = true;
236
+ for (const word of words) {
237
+ let weight = 0;
238
+ if (titleWords.has(word)) weight += 10;
239
+ else if (title.includes(word)) weight += 6;
240
+ if (route.includes(word)) weight += 4;
241
+ if (description.includes(word)) weight += 2;
242
+ if (section.includes(word)) weight += 1;
243
+ weight += Math.min(countOccurrences(body, word), 5);
244
+ if (weight === 0) {
245
+ everyTermFound = false;
246
+ break;
247
+ }
248
+ score += weight;
249
+ }
250
+ if (!everyTermFound) continue;
251
+ const hit = {
252
+ ...entry,
253
+ score
254
+ };
255
+ const excerpt = body === "" ? void 0 : excerptOf(bodies?.get(entry.path) ?? "", query, words);
256
+ if (excerpt !== void 0) hit.excerpt = excerpt;
257
+ hits.push(hit);
258
+ }
259
+ return hits.toSorted((left, right) => right.score - left.score || left.path.localeCompare(right.path));
260
+ }
261
+ var _fetcher = /* @__PURE__ */ new WeakMap();
262
+ var _ttl = /* @__PURE__ */ new WeakMap();
263
+ var _now = /* @__PURE__ */ new WeakMap();
264
+ var _cache = /* @__PURE__ */ new WeakMap();
265
+ var _DocsClient_brand = /* @__PURE__ */ new WeakSet();
266
+ var DocsClient = class {
267
+ constructor(options) {
268
+ _classPrivateMethodInitSpec(this, _DocsClient_brand);
269
+ _defineProperty(this, "baseUrl", void 0);
270
+ _classPrivateFieldInitSpec(this, _fetcher, void 0);
271
+ _classPrivateFieldInitSpec(this, _ttl, void 0);
272
+ _classPrivateFieldInitSpec(this, _now, void 0);
273
+ _classPrivateFieldInitSpec(this, _cache, /* @__PURE__ */ new Map());
274
+ this.baseUrl = normaliseBaseUrl(options.baseUrl);
275
+ _classPrivateFieldSet2(_fetcher, this, options.fetcher ?? ((url) => fetch(url, { signal: AbortSignal.timeout(15e3) })));
276
+ _classPrivateFieldSet2(_ttl, this, options.ttl ?? 3e5);
277
+ _classPrivateFieldSet2(_now, this, options.now ?? Date.now);
278
+ }
279
+ /** Every page the site lists, in the order `llms.txt` lists them. */
280
+ async listDocs() {
281
+ const llms = await _assertClassBrand(_DocsClient_brand, this, _get).call(this, "/llms.txt");
282
+ if (llms !== null) return parseLlmsTxt(llms, this.baseUrl);
283
+ const api = await _assertClassBrand(_DocsClient_brand, this, _get).call(this, "/api/docs/pages.json");
284
+ if (api !== null) return parsePagesApi(api, this.baseUrl);
285
+ throw new DocsRequestError(`${this.baseUrl}/llms.txt`, 404);
286
+ }
287
+ async searchDocs(query, includeContent) {
288
+ const entries = await this.listDocs();
289
+ const bodies = includeContent ? await _assertClassBrand(_DocsClient_brand, this, _bodies).call(this) : null;
290
+ return {
291
+ searchedContent: bodies !== null,
292
+ hits: rankEntries(entries, query, bodies ?? void 0)
293
+ };
294
+ }
295
+ /**
296
+ * One page's Markdown. A bare slug (`button`) is matched against the index
297
+ * first — the last segment of a route — then tried under `/docs/`.
298
+ */
299
+ async getDoc(input) {
300
+ const route = toRoute(input);
301
+ const entries = await this.listDocs().catch(() => []);
302
+ const slug = route.slice(1);
303
+ const known = new Set(entries.map((entry) => entry.path));
304
+ const guesses = [
305
+ route,
306
+ `/docs${route}`,
307
+ ...entries.filter((entry) => entry.path.endsWith(route)).map((entry) => entry.path)
308
+ ];
309
+ const candidates = /* @__PURE__ */ new Set([...guesses.filter((path) => known.has(path)), ...guesses]);
310
+ for (const path of candidates) {
311
+ const markdown = await _assertClassBrand(_DocsClient_brand, this, _get).call(this, markdownPathFor(path));
312
+ if (markdown !== null) return {
313
+ found: true,
314
+ entry: entries.find((candidate) => candidate.path === path) ?? toEntry(this.baseUrl, path, path, void 0, void 0),
315
+ markdown
316
+ };
317
+ }
318
+ return {
319
+ found: false,
320
+ path: route,
321
+ suggestions: rankEntries(entries, terms(slug).map((word) => word.slice(0, Math.max(4, word.length - 2))).join(" ")).slice(0, 5)
322
+ };
323
+ }
324
+ };
325
+ /**
326
+ * A cached GET. `null` means the site answered 404 — a fact worth caching
327
+ * too; any other failure throws and is not cached, so the next call retries.
328
+ */
329
+ async function _get(path) {
330
+ const url = `${this.baseUrl}${path}`;
331
+ const cached = _classPrivateFieldGet2(_cache, this).get(url);
332
+ if (cached !== void 0 && cached.expires > _classPrivateFieldGet2(_now, this).call(this)) return cached.value;
333
+ const value = _classPrivateFieldGet2(_fetcher, this).call(this, url).then(async (response) => {
334
+ if (response.status === 404) return null;
335
+ if (!response.ok) throw new DocsRequestError(url, response.status);
336
+ return response.text();
337
+ });
338
+ if (_classPrivateFieldGet2(_ttl, this) > 0) {
339
+ _classPrivateFieldGet2(_cache, this).set(url, {
340
+ expires: _classPrivateFieldGet2(_now, this).call(this) + _classPrivateFieldGet2(_ttl, this),
341
+ value
342
+ });
343
+ value.catch(() => _classPrivateFieldGet2(_cache, this).delete(url));
344
+ }
345
+ return value;
346
+ }
347
+ /** Page bodies keyed by route, or `null` when the site has no `llms-full.txt`. */
348
+ async function _bodies() {
349
+ const full = await _assertClassBrand(_DocsClient_brand, this, _get).call(this, "/llms-full.txt");
350
+ return full === null ? null : parseLlmsFull(full, this.baseUrl);
351
+ }
352
+
353
+ // src/server.ts
354
+ const DEFAULT_LIMIT = 10;
355
+ const MAX_LIMIT = 50;
356
+ /** A tool answering in prose or Markdown. */
357
+ function text(message) {
358
+ return { content: [{
359
+ type: "text",
360
+ text: message
361
+ }] };
362
+ }
363
+ /** A tool reporting a failure the agent should read rather than retry blindly. */
364
+ function failure(message) {
365
+ return {
366
+ ...text(message),
367
+ isError: true
368
+ };
369
+ }
370
+ function asJson(value) {
371
+ return JSON.stringify(value, null, 2);
372
+ }
373
+ function createServer(docs) {
374
+ const server = new McpServer({
375
+ name: "newtui-docs",
376
+ version
377
+ });
378
+ server.registerTool("list_docs", {
379
+ title: "List documentation pages",
380
+ description: "Every page of the newt/ui documentation (Discord-inspired components for React, Vue and HTML/CSS) with its title, route, description and section. Use it to find the page to read with get_doc.",
381
+ inputSchema: { section: z.string().optional().describe("Only pages listed under this section, e.g. 'Installation' or 'Forms'. Case-insensitive.") },
382
+ annotations: {
383
+ readOnlyHint: true,
384
+ openWorldHint: true
385
+ }
386
+ }, async ({ section }) => {
387
+ const all = await docs.listDocs();
388
+ const pages = section === void 0 ? all : all.filter((page) => page.section?.toLowerCase() === section.toLowerCase());
389
+ return text(asJson({
390
+ site: docs.baseUrl,
391
+ count: pages.length,
392
+ pages
393
+ }));
394
+ });
395
+ server.registerTool("search_docs", {
396
+ title: "Search the documentation",
397
+ description: "Keyword search over the newt/ui docs. Ranks pages by where every query term appears: title first, then route, description and section. Set content to true to search page bodies as well — slower, but it finds a prop or a token mentioned only inside a page.",
398
+ inputSchema: {
399
+ query: z.string().min(1).describe("Keywords, e.g. 'dark mode' or 'nuxt install'."),
400
+ content: z.boolean().optional().describe("Also search the full text of every page."),
401
+ limit: z.number().int().min(1).max(MAX_LIMIT).optional().describe(`How many results to return. Defaults to ${DEFAULT_LIMIT}.`)
402
+ },
403
+ annotations: {
404
+ readOnlyHint: true,
405
+ openWorldHint: true
406
+ }
407
+ }, async ({ query, content, limit }) => {
408
+ const result = await docs.searchDocs(query, content ?? false);
409
+ const results = result.hits.slice(0, limit ?? DEFAULT_LIMIT);
410
+ return text(asJson({
411
+ site: docs.baseUrl,
412
+ query,
413
+ searchedContent: result.searchedContent,
414
+ count: results.length,
415
+ results
416
+ }));
417
+ });
418
+ server.registerTool("get_doc", {
419
+ title: "Read a documentation page",
420
+ description: "One page of the newt/ui docs as Markdown. Accepts a route ('/docs/theming'), a slug ('button', 'installation/nuxt') or a full newtui.dev URL. Read this rather than recalling an API from memory.",
421
+ inputSchema: { path: z.string().min(1).describe("The page: a route, a slug or a URL.") },
422
+ annotations: {
423
+ readOnlyHint: true,
424
+ openWorldHint: true
425
+ }
426
+ }, async ({ path }) => {
427
+ const page = await docs.getDoc(path);
428
+ if (!page.found) return failure(`No documentation page at "${page.path}". Closest matches:\n\n${asJson({
429
+ site: docs.baseUrl,
430
+ path: page.path,
431
+ suggestions: page.suggestions
432
+ })}`);
433
+ return text(`<!-- Source: ${page.entry.url} -->\n\n${page.markdown}`);
434
+ });
435
+ return server;
436
+ }
437
+ /** Serve over stdio, which is how every MCP client launches a local server. */
438
+ async function startServer(docs) {
439
+ await createServer(docs).connect(new StdioServerTransport());
440
+ }
441
+
442
+ // src/index.ts
443
+ const HELP = `newtui-mcp — an MCP server for the newt/ui documentation
444
+
445
+ Usage
446
+ $ npx @newtui/mcp [--url <site>]
447
+
448
+ Options
449
+ --url <site> the docs site to read (default: ${DEFAULT_DOCS_URL})
450
+ also read from NEWTUI_DOCS_URL
451
+ -h, --help show this help
452
+ -v, --version print the version
453
+
454
+ The server speaks MCP over stdio; an editor launches it, not a person.`;
455
+ async function main() {
456
+ const { values } = parseArgs({ options: {
457
+ url: { type: "string" },
458
+ help: {
459
+ type: "boolean",
460
+ short: "h"
461
+ },
462
+ version: {
463
+ type: "boolean",
464
+ short: "v"
465
+ }
466
+ } });
467
+ if (values.help === true) {
468
+ console.log(HELP);
469
+ return;
470
+ }
471
+ if (values.version === true) {
472
+ console.log(version);
473
+ return;
474
+ }
475
+ const baseUrl = resolveDocsUrl(values.url, process.env.NEWTUI_DOCS_URL);
476
+ let docs;
477
+ try {
478
+ docs = new DocsClient({ baseUrl });
479
+ } catch {
480
+ console.error(`newtui-mcp: "${baseUrl}" is not a URL.`);
481
+ process.exit(1);
482
+ }
483
+ await startServer(docs);
484
+ }
485
+ main().catch((error) => {
486
+ console.error(`newtui-mcp: ${error instanceof Error ? error.message : String(error)}`);
487
+ process.exit(1);
488
+ });
489
+
490
+ export { };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@newtui/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "MCP server for the newt/ui documentation — lets a coding agent list, search and read the Discord-inspired component library's docs. Part of the WolfStar toolchain.",
5
+ "keywords": [
6
+ "component-library",
7
+ "design-system",
8
+ "discord",
9
+ "documentation",
10
+ "mcp",
11
+ "model-context-protocol",
12
+ "ui",
13
+ "wolfstar"
14
+ ],
15
+ "homepage": "https://newtui.dev/docs/mcp",
16
+ "bugs": {
17
+ "url": "https://github.com/wolfstar-project/newt-ui/issues"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": "@wolfstar",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/wolfstar-project/newt-ui.git",
24
+ "directory": "packages/mcp"
25
+ },
26
+ "bin": {
27
+ "newtui-mcp": "./dist/index.js"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "type": "module",
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "provenance": true
38
+ },
39
+ "dependencies": {
40
+ "@modelcontextprotocol/sdk": "^1.32.2",
41
+ "zod": "^3.25.76"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^22.10.2",
45
+ "tsdown": "^0.23.5",
46
+ "typescript": "^5.7.2",
47
+ "unrun": "^0.3.1",
48
+ "vitest": "^5.1.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=20"
52
+ },
53
+ "scripts": {
54
+ "build": "tsdown --config-loader unrun",
55
+ "dev": "tsdown --config-loader unrun --watch",
56
+ "start": "node dist/index.js",
57
+ "typecheck": "tsc --noEmit",
58
+ "test": "vitest run",
59
+ "test:watch": "vitest"
60
+ }
6
61
  }