@nyxon/nasim-mcp 0.0.0-stage → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/server.js ADDED
@@ -0,0 +1,198 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { z } from 'zod/v4';
4
+ import { checkCode } from "./check.js";
5
+ import { findParts, search } from "./find.js";
6
+ import { nearest } from "./text.js";
7
+ // Both live in this package, beside src/ (and beside dist/lib/ once built); nothing else is read.
8
+ const own = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8');
9
+ export const manifest = JSON.parse(own('manifest.json'));
10
+ const { version } = JSON.parse(own('package.json'));
11
+ const READ_ONLY = { readOnlyHint: true, openWorldHint: false };
12
+ const text = (body, isError = false) => ({
13
+ content: [{ type: 'text', text: body }],
14
+ ...(isError ? { isError } : {}),
15
+ });
16
+ const SECTIONS = [
17
+ 'import',
18
+ 'usage',
19
+ 'examples',
20
+ 'rules',
21
+ 'accessibility',
22
+ 'api',
23
+ 'related',
24
+ ];
25
+ // The facts before a page's first heading, then the one `## Section` asked for. A page opens with
26
+ // its main example above every heading, and its Examples section says «shown above»: that
27
+ // section keeps it.
28
+ function section(markdown, name) {
29
+ const [head = '', ...blocks] = markdown.split(/^(?=## )/m);
30
+ const block = blocks.find((b) => b.toLowerCase().startsWith(`## ${name}`));
31
+ const facts = name === 'examples' ? head : head.split(/^<Example/m)[0];
32
+ return block ? `${facts?.trim()}\n\n${block.trim()}` : undefined;
33
+ }
34
+ const line = (part) => `- **${part.names.join(', ')}** (${part.kind}, ${part.server ? 'Server Component' : 'client'}, ${part.group}): ${part.description} Job: ${part.job}. \`${part.importLine}\``;
35
+ /** The documented page of a name: its own, or the page of the part it is documented with. */
36
+ const pageOf = (name) => manifest.parts.find((part) => part.names.includes(name)) ??
37
+ manifest.parts.find((part) => part.name.toLowerCase() === name.toLowerCase());
38
+ const documented = manifest.parts.flatMap((part) => part.names);
39
+ const groups = [...new Set(manifest.parts.map((part) => part.group))];
40
+ const kinds = [...new Set(manifest.parts.map((part) => part.kind))];
41
+ const guides = manifest.guides.map((guide) => guide.slug);
42
+ const about = `${manifest.package} ${manifest.version}`;
43
+ function unknownName(name) {
44
+ if (manifest.values.includes(name) || manifest.exports.includes(name))
45
+ return `${name} is exported by ${manifest.package} but has no documentation page yet, so this server has no props or examples for it. Read its type in node_modules/${manifest.package}, or use a documented part: ${documented.join(', ')}.`;
46
+ const close = nearest(name, [...documented, ...manifest.values]);
47
+ return `${manifest.package} has no ${name}.${close ? ` Did you mean ${close}?` : ''} list_parts shows the documented parts; find_part finds one for a job.`;
48
+ }
49
+ export function createServer() {
50
+ const server = new McpServer({ name: 'nasim', version }, {
51
+ instructions: `Nasim (${about}) is a React UI library for right-to-left, Persian-first dashboards on HeroUI 3 and React Aria. Before writing a screen: get_rules, then find_part for each job on the screen and get_part for each part you use. After writing it: check_code on the file. Every answer comes from the documentation bundled with this server; nothing is fetched.`,
52
+ });
53
+ server.registerTool('list_parts', {
54
+ title: 'List Nasim parts',
55
+ description: `List every documented part of ${manifest.package} with its kind, whether a Server Component can render it, its group, one line on what it is, the job it does and its import line. Filter by group (${groups.join(', ')}) or kind (${kinds.join(', ')}). Also names the exports that have no page yet.`,
56
+ inputSchema: {
57
+ group: z
58
+ .enum(groups)
59
+ .optional()
60
+ .describe('Only the parts of this group'),
61
+ kind: z.enum(kinds).optional().describe('Only the parts of this kind'),
62
+ },
63
+ annotations: READ_ONLY,
64
+ }, ({ group, kind }) => {
65
+ const parts = manifest.parts.filter((part) => (!group || part.group === group) && (!kind || part.kind === kind));
66
+ const rest = manifest.values.filter((name) => /^[A-Z]/.test(name) && !documented.includes(name));
67
+ return text([
68
+ `${parts.length} documented part(s) of ${about}:`,
69
+ parts.map(line).join('\n'),
70
+ group || kind || !rest.length
71
+ ? ''
72
+ : `Exported but not documented yet (no props or examples here): ${rest.join(', ')}.`,
73
+ ]
74
+ .filter(Boolean)
75
+ .join('\n\n'));
76
+ });
77
+ server.registerTool('get_part', {
78
+ title: 'Get a Nasim part',
79
+ description: `Get a documented part's whole page as Markdown: import line, Server Component or not, since, usage, the code of every example, its rules, accessibility notes and its props table (name, type, default, description). Optionally one section only (${SECTIONS.join(', ')}). Names: ${documented.join(', ')}.`,
80
+ inputSchema: {
81
+ name: z
82
+ .string()
83
+ .min(1)
84
+ .max(100)
85
+ .describe('A part name, such as StatusChip'),
86
+ section: z
87
+ .enum(SECTIONS)
88
+ .optional()
89
+ .describe('Only this section of the page'),
90
+ },
91
+ annotations: READ_ONLY,
92
+ }, ({ name, section: wanted }) => {
93
+ const part = pageOf(name.trim());
94
+ if (!part)
95
+ return text(unknownName(name.trim()), true);
96
+ if (!wanted)
97
+ return text(part.markdown);
98
+ const found = section(part.markdown, wanted);
99
+ return found
100
+ ? text(found)
101
+ : text(`The ${part.name} page has no ${wanted} section.`, true);
102
+ });
103
+ server.registerTool('search_docs', {
104
+ title: 'Search the Nasim docs',
105
+ description: 'Search the parts and guides of the Nasim docs by words, in English or Persian. Returns the best matches, ranked, each with the fields its words were found in. Use find_part instead to choose a part for a job on a screen.',
106
+ inputSchema: {
107
+ query: z
108
+ .string()
109
+ .min(1)
110
+ .max(200)
111
+ .describe('Words to look for, such as «copy link» or «کپی»'),
112
+ limit: z.number().int().min(1).max(20).default(8),
113
+ },
114
+ annotations: READ_ONLY,
115
+ }, ({ query, limit }) => {
116
+ const hits = search(manifest, query, limit);
117
+ if (!hits.length)
118
+ return text(`Nothing in the Nasim docs matches «${query}». Try other words, or list_parts.`);
119
+ return text(hits
120
+ .map((hit) => {
121
+ const page = hit.kind === 'part'
122
+ ? pageOf(hit.name)
123
+ : manifest.guides.find((g) => g.slug === hit.name);
124
+ return `- ${hit.kind} **${hit.name}** (score ${hit.score}): ${page?.description ?? ''} Matched ${hit.reasons.join('; ')}. ${hit.kind === 'part' ? `get_part ${hit.name}` : `get_guide ${hit.name}`}`;
125
+ })
126
+ .join('\n'));
127
+ });
128
+ server.registerTool('find_part', {
129
+ title: 'Find the Nasim part for a job',
130
+ description: "Say what a screen needs, in English or Persian («a status on each row», «confirm before deleting», «nothing to show yet»), and get the documented parts whose job, keywords or description match, ranked, each with its import line and why it matched. Plain word matching, no model: if nothing matches, it lists every part's job to choose from.",
131
+ inputSchema: {
132
+ need: z.string().min(1).max(500).describe('What the screen needs'),
133
+ limit: z.number().int().min(1).max(10).default(3),
134
+ },
135
+ annotations: READ_ONLY,
136
+ }, ({ need, limit }) => {
137
+ const hits = findParts(manifest, need, limit);
138
+ if (!hits.length)
139
+ return text([
140
+ `No documented part's job or keywords match «${need}». The documented jobs:`,
141
+ manifest.parts
142
+ .map((part) => `- ${part.job}: ${part.name}`)
143
+ .join('\n'),
144
+ 'Other exports have no page yet; list_parts names them.',
145
+ ].join('\n\n'));
146
+ return text(hits
147
+ .map((hit) => {
148
+ const part = pageOf(hit.name);
149
+ return part
150
+ ? `- **${part.names.join(', ')}** for «${part.job}»: ${part.description} \`${part.importLine}\` Matched ${hit.reasons.join('; ')}.`
151
+ : '';
152
+ })
153
+ .join('\n'));
154
+ });
155
+ server.registerTool('get_guide', {
156
+ title: 'Get a Nasim guide',
157
+ description: `Get a guide of the Nasim docs as Markdown: ${manifest.guides.map((g) => `${g.slug} (${g.description})`).join('; ')}`,
158
+ inputSchema: { name: z.enum(guides).describe('The guide') },
159
+ annotations: READ_ONLY,
160
+ }, ({ name }) => {
161
+ const guide = manifest.guides.find((g) => g.slug === name);
162
+ return guide ? text(guide.markdown) : text(`No guide ${name}.`, true);
163
+ });
164
+ server.registerTool('get_rules', {
165
+ title: 'Get the rules of Nasim',
166
+ description: 'Get the rules every screen built on Nasim keeps (imports, copy as props, tokens not colours, logical layout, one theme controller), in a few lines. Read them before writing a screen; check_code tests a file against the mechanical ones.',
167
+ inputSchema: {},
168
+ annotations: READ_ONLY,
169
+ }, () => text([
170
+ `The rules of ${about}:`,
171
+ manifest.rules.map((rule) => `- ${rule}`).join('\n'),
172
+ 'The reason for each, and the rest of them: get_guide rules.',
173
+ ].join('\n\n')));
174
+ server.registerTool('check_code', {
175
+ title: "Check code against Nasim's rules",
176
+ description: "Check a screen's source (TSX) against Nasim's rules and get each breach with its line and the fix: UI imported or re-exported from @heroui/* or react-aria-components, a name @nyxon/nasim does not export, a prop a documented part does not take, a hex colour or a `dark:` utility in a class, words written in JSX or in a user-facing attribute instead of coming from the screen's strings. It reports only what the text shows for sure; it does not check layout, logic or accessibility.",
177
+ inputSchema: {
178
+ code: z.string().min(1).max(200_000).describe('The whole file'),
179
+ path: z
180
+ .string()
181
+ .max(300)
182
+ .optional()
183
+ .describe('The file name; a .ts file is read without JSX'),
184
+ },
185
+ annotations: READ_ONLY,
186
+ }, ({ code, path }) => {
187
+ const findings = checkCode(manifest, code, path);
188
+ if (!findings.length)
189
+ return text("No breach found: imports, names, props, colours and copy keep Nasim's rules. Layout, logic and accessibility are not checked.");
190
+ return text([
191
+ `${findings.length} breach(es) of Nasim's rules:`,
192
+ findings
193
+ .map((f) => `- line ${f.line} [${f.rule}] ${f.message} Fix: ${f.fix}`)
194
+ .join('\n'),
195
+ ].join('\n\n'));
196
+ });
197
+ return server;
198
+ }
package/lib/text.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Words as the docs' search reads them (apps/nasim-docs/src/docs/tokenizer.ts, copied because a
3
+ * published package cannot import an app): Persian and Latin runs, lowercased, Arabic yeh and kaf
4
+ * folded to Persian, Persian and Arabic digits to ASCII, and a half-space word kept joined and split.
5
+ */
6
+ export declare function words(text: string): string[];
7
+ /** The closest name to a mistyped one, ignoring case; none when nothing is close. */
8
+ export declare function nearest(name: string, names: readonly string[]): string | undefined;
package/lib/text.js ADDED
@@ -0,0 +1,45 @@
1
+ const ZWNJ = '‌';
2
+ /**
3
+ * Words as the docs' search reads them (apps/nasim-docs/src/docs/tokenizer.ts, copied because a
4
+ * published package cannot import an app): Persian and Latin runs, lowercased, Arabic yeh and kaf
5
+ * folded to Persian, Persian and Arabic digits to ASCII, and a half-space word kept joined and split.
6
+ */
7
+ export function words(text) {
8
+ return text
9
+ .replace(/[۰-۹٠-٩]/g, (digit) => String((digit.charCodeAt(0) & 0xf) % 10))
10
+ .toLowerCase()
11
+ .replace(/ي/g, 'ی')
12
+ .replace(/ك/g, 'ک')
13
+ .split(/[^\p{L}\p{N}‌]+/u)
14
+ .flatMap((word) => word.includes(ZWNJ)
15
+ ? [word.replaceAll(ZWNJ, ''), ...word.split(ZWNJ)]
16
+ : [word])
17
+ .filter(Boolean);
18
+ }
19
+ function distance(a, b) {
20
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
21
+ for (let i = 1; i <= a.length; i++) {
22
+ const current = [i];
23
+ for (let j = 1; j <= b.length; j++)
24
+ current[j] = Math.min((previous[j] ?? 0) + 1, (current[j - 1] ?? 0) + 1, (previous[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1));
25
+ previous = current;
26
+ }
27
+ return previous[b.length] ?? 0;
28
+ }
29
+ /** The closest name to a mistyped one, ignoring case; none when nothing is close. */
30
+ export function nearest(name, names) {
31
+ const target = name.toLowerCase();
32
+ let best;
33
+ for (const candidate of names) {
34
+ const lower = candidate.toLowerCase();
35
+ // A name inside the other (`Chip` in `StatusChip`) is as close as one typo.
36
+ const score = lower.includes(target) || target.includes(lower)
37
+ ? Math.min(1, distance(target, lower))
38
+ : distance(target, lower);
39
+ if (!best || score < best.score)
40
+ best = { name: candidate, score };
41
+ }
42
+ return best && best.score <= Math.max(2, Math.floor(name.length / 3))
43
+ ? best.name
44
+ : undefined;
45
+ }