@digital-finance-ui/ui-kit-mcp 0.2.13 → 0.2.15

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/dist/server.js CHANGED
@@ -1,8 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ /* eslint-disable import/extensions -- @modelcontextprotocol/sdk requires explicit .js subpaths under NodeNext resolution */
3
+ import fs from 'node:fs';
2
4
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
5
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
6
  import { z } from 'zod';
5
7
  import { resolveIndex } from './resolveIndex.js';
8
+ import { toToolResult } from './toolResponse.js';
6
9
  import { getComponent } from './tools/getComponent.js';
7
10
  import { getComponentExamples } from './tools/getComponentExamples.js';
8
11
  import { getComponentProps } from './tools/getComponentProps.js';
@@ -14,7 +17,6 @@ import { listCategories } from './tools/listCategories.js';
14
17
  import { listComponents } from './tools/listComponents.js';
15
18
  import { listFeatures } from './tools/listFeatures.js';
16
19
  import { searchComponents } from './tools/searchComponents.js';
17
- import { truncateForResponse } from './tools/truncate.js';
18
20
  function loadIndex() {
19
21
  const resolved = resolveIndex();
20
22
  // dataVersionNotice/libNotInstalled/source кладём прямо в index — тулзам
@@ -26,14 +28,6 @@ function loadIndex() {
26
28
  indexSource: resolved.source,
27
29
  };
28
30
  }
29
- /**
30
- * Явная аннотация возврата CallToolResult обязательна: без неё литерал
31
- * 'text' расширяется до string и объект перестаёт подходить под
32
- * дискриминированный union content-блоков SDK.
33
- */
34
- function toToolResult(payload) {
35
- return { content: [{ type: 'text', text: truncateForResponse(payload) }] };
36
- }
37
31
  /**
38
32
  * Дженерик Shape нужен ровно для одного: чтобы TS проверил, что тип args
39
33
  * хендлера согласован с переданной zod-схемой (иначе рассинхрон схемы и
@@ -53,7 +47,8 @@ function registerJsonTool(server, index, name, description, inputSchema, handler
53
47
  }
54
48
  function main() {
55
49
  const index = loadIndex();
56
- const server = new McpServer({ name: '@digital-finance-ui/ui-kit-mcp', version: '0.1.0' });
50
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
51
+ const server = new McpServer({ name: pkg.name, version: pkg.version });
57
52
  registerJsonTool(server, index, 'list_components', 'Список компонентов @sber-digital-finance-ui/ui-kit с фильтрами по типу (wrapper/composition/standalone/form), категории ("Локальные компоненты" / "Композиции" / "Формы" — количество по типам отдаёт list_categories), scope. По умолчанию — только самостоятельные компоненты (role: "primary", ~177 из 243): слоты вроде DrawerDFHeader и служебные примитивы вроде CanvasRect скрыты, они видны через relatedExports в карточке владельца (get_component) или напрямую по имени; role: "all" снимает фильтр. Без limit список бюджетируется автоматически (см. shown/total/truncationNotice в ответе); limit/offset — явная пагинация.', {
58
53
  type: z.string().optional(),
59
54
  category: z.string().optional(),
@@ -0,0 +1,8 @@
1
+ import { truncateForResponse } from './tools/truncate.js';
2
+ import { ToolError } from './types.js';
3
+ export function toToolResult(payload) {
4
+ return {
5
+ content: [{ type: 'text', text: truncateForResponse(payload) }],
6
+ ...(payload instanceof ToolError ? { isError: true } : {}),
7
+ };
8
+ }
@@ -1,4 +1,4 @@
1
- import { isOkComponent } from '../types.js';
1
+ import { isOkComponent, ToolError } from '../types.js';
2
2
  import { findComponent, listComponentFeatures, summarizeProp, } from './shared.js';
3
3
  /**
4
4
  * Сколько необязательных пропсов с описанием показывать в компактной
@@ -32,12 +32,10 @@ function selectOwnProps(props) {
32
32
  export function getComponent(index, { name } = {}) {
33
33
  const record = findComponent(index, name);
34
34
  if (!record) {
35
- return {
36
- error: `Компонент "${name}" не найден. Используйте search_components или list_components.`,
37
- };
35
+ return new ToolError(`Компонент "${name}" не найден. Используйте search_components или list_components.`);
38
36
  }
39
37
  if (!isOkComponent(record)) {
40
- return { error: record.error };
38
+ return new ToolError(record.error);
41
39
  }
42
40
  const features = listComponentFeatures(index, record.name);
43
41
  const exampleTitles = (record.examples || []).map((e) => e.displayName || e.exportName);
@@ -57,6 +55,7 @@ export function getComponent(index, { name } = {}) {
57
55
  : ''}${examplesHint}${features.length ? '; list_features({component}) — фичи компонента' : ''}`;
58
56
  return {
59
57
  name: record.name,
58
+ apiKind: record.apiKind,
60
59
  type: record.type,
61
60
  category: record.category,
62
61
  description: record.description || undefined,
@@ -1,12 +1,12 @@
1
- import { isOkComponent } from '../types.js';
1
+ import { isOkComponent, ToolError } from '../types.js';
2
2
  import { findComponent } from './shared.js';
3
3
  export function getComponentExamples(index, { name, title } = {}) {
4
4
  const record = findComponent(index, name);
5
5
  if (!record) {
6
- return { error: `Компонент "${name}" не найден.` };
6
+ return new ToolError(`Компонент "${name}" не найден.`);
7
7
  }
8
8
  if (!isOkComponent(record)) {
9
- return { error: record.error };
9
+ return new ToolError(record.error);
10
10
  }
11
11
  const examples = record.examples || [];
12
12
  if (!title) {
@@ -19,9 +19,7 @@ export function getComponentExamples(index, { name, title } = {}) {
19
19
  const found = examples.find((e) => (e.displayName || '').toLowerCase() === title.toLowerCase() ||
20
20
  (e.exportName || '').toLowerCase() === title.toLowerCase());
21
21
  if (!found) {
22
- return {
23
- error: `Пример "${title}" не найден у "${record.name}". Доступные: ${examples.map((e) => e.displayName || e.exportName).join(', ') || '(нет)'}`,
24
- };
22
+ return new ToolError(`Пример "${title}" не найден у "${record.name}". Доступные: ${examples.map((e) => e.displayName || e.exportName).join(', ') || '(нет)'}`);
25
23
  }
26
24
  return { name: record.name, example: found };
27
25
  }
@@ -1,4 +1,4 @@
1
- import { isOkComponent } from '../types.js';
1
+ import { isOkComponent, ToolError } from '../types.js';
2
2
  import { findComponent } from './shared.js';
3
3
  /**
4
4
  * Пустой props[] у generic-типа — не факт "у компонента нет пропсов", а
@@ -8,7 +8,9 @@ import { findComponent } from './shared.js';
8
8
  * только на MCP, не может отличить одно от другого и рискует придумать
9
9
  * пропсы по общему паттерну (реальный кейс — FormMask до фикса индексера).
10
10
  */
11
- function genericEmptyPropsWarning(isGeneric, propsLength) {
11
+ function genericEmptyPropsWarning(isGeneric, propsLength, openProps) {
12
+ if (openProps)
13
+ return 'Публичный тип допускает произвольные ключи. Индекс перечисляет известные поля; это не закрытый контракт и не гарантия проверки произвольных JSX-пропсов.';
12
14
  if (!isGeneric || propsLength > 0)
13
15
  return undefined;
14
16
  return ('Пропсы не резолвлены (сложный generic-тип) — пустой props[] не значит, ' +
@@ -19,17 +21,15 @@ function genericEmptyPropsWarning(isGeneric, propsLength) {
19
21
  export function getComponentProps(index, { name, part } = {}) {
20
22
  const record = findComponent(index, name);
21
23
  if (!record) {
22
- return { error: `Компонент "${name}" не найден.` };
24
+ return new ToolError(`Компонент "${name}" не найден.`);
23
25
  }
24
26
  if (!isOkComponent(record)) {
25
- return { error: record.error };
27
+ return new ToolError(record.error);
26
28
  }
27
29
  if (part) {
28
30
  const compoundPart = (record.compoundParts || []).find((p) => p.name.toLowerCase() === part.toLowerCase());
29
31
  if (!compoundPart) {
30
- return {
31
- error: `Compound-часть "${part}" не найдена у "${record.name}". Доступные: ${(record.compoundParts || []).map((p) => p.name).join(', ') || '(нет)'}`,
32
- };
32
+ return new ToolError(`Compound-часть "${part}" не найдена у "${record.name}". Доступные: ${(record.compoundParts || []).map((p) => p.name).join(', ') || '(нет)'}`);
33
33
  }
34
34
  const compoundPartProps = compoundPart.props || [];
35
35
  return {
@@ -39,7 +39,7 @@ export function getComponentProps(index, { name, part } = {}) {
39
39
  rawType: compoundPart.rawType,
40
40
  isGeneric: compoundPart.isGeneric || undefined,
41
41
  props: compoundPartProps,
42
- warning: genericEmptyPropsWarning(compoundPart.isGeneric, compoundPartProps.length),
42
+ warning: genericEmptyPropsWarning(compoundPart.isGeneric, compoundPartProps.length, compoundPart.openProps),
43
43
  };
44
44
  }
45
45
  const props = record.props || [];
@@ -54,6 +54,6 @@ export function getComponentProps(index, { name, part } = {}) {
54
54
  atomicDataMissing: record.atomicDataMissing || undefined,
55
55
  compoundPartOf: record.compoundPartOf,
56
56
  dataVersionNotice: index.dataVersionNotice,
57
- warning: genericEmptyPropsWarning(record.isGeneric, props.length),
57
+ warning: genericEmptyPropsWarning(record.isGeneric, props.length, record.openProps),
58
58
  };
59
59
  }
@@ -1,10 +1,9 @@
1
+ import { ToolError } from '../types.js';
1
2
  import { findFeature } from './shared.js';
2
3
  export function getFeature(index, { component, feature } = {}) {
3
4
  const found = findFeature(index, component, feature);
4
5
  if (!found) {
5
- return {
6
- error: `Фича "${feature}" не найдена у "${component}". Используйте list_features({component}).`,
7
- };
6
+ return new ToolError(`Фича "${feature}" не найдена у "${component}". Используйте list_features({component}).`);
8
7
  }
9
8
  return {
10
9
  component: found.component,
@@ -1,10 +1,9 @@
1
+ import { ToolError } from '../types.js';
1
2
  import { findFeature } from './shared.js';
2
3
  export function getFeatureExamples(index, { component, feature, title } = {}) {
3
4
  const found = findFeature(index, component, feature);
4
5
  if (!found) {
5
- return {
6
- error: `Фича "${feature}" не найдена у "${component}". Используйте list_features({component}).`,
7
- };
6
+ return new ToolError(`Фича "${feature}" не найдена у "${component}". Используйте list_features({component}).`);
8
7
  }
9
8
  const stories = found.stories || [];
10
9
  if (!title) {
@@ -18,9 +17,7 @@ export function getFeatureExamples(index, { component, feature, title } = {}) {
18
17
  const story = stories.find((s) => (s.displayName || '').toLowerCase() === title.toLowerCase() ||
19
18
  (s.exportName || '').toLowerCase() === title.toLowerCase());
20
19
  if (!story) {
21
- return {
22
- error: `Пример "${title}" не найден у "${component}/${feature}". Доступные: ${stories.map((s) => s.displayName || s.exportName).join(', ') || '(нет)'}`,
23
- };
20
+ return new ToolError(`Пример "${title}" не найден у "${component}/${feature}". Доступные: ${stories.map((s) => s.displayName || s.exportName).join(', ') || '(нет)'}`);
24
21
  }
25
22
  return { component: found.component, feature: found.feature, example: story };
26
23
  }
@@ -1,7 +1,8 @@
1
+ import { ToolError } from '../types.js';
1
2
  export function getInstallationGuide(index) {
2
3
  const guide = index.guides?.installation;
3
4
  if (!guide) {
4
- return { error: 'Гайд по установке не найден в индексе.' };
5
+ return new ToolError('Гайд по установке не найден в индексе.');
5
6
  }
6
7
  return guide;
7
8
  }
@@ -1,4 +1,4 @@
1
- import { isOkComponent } from '../types.js';
1
+ import { isOkComponent, ToolError } from '../types.js';
2
2
  /** Сколько похожих имён показывать при промахе — список подсказок, а не выгрузка индекса. */
3
3
  const MAX_SUGGESTIONS = 8;
4
4
  /** Опечатка в одну-две буквы — да; произвольно похожее имя — нет. */
@@ -95,7 +95,7 @@ function findComponentByPropsTypeName(index, name) {
95
95
  */
96
96
  export function getType(index, { name } = {}) {
97
97
  if (!name) {
98
- return { error: 'Не указано имя типа.' };
98
+ return new ToolError('Не указано имя типа.');
99
99
  }
100
100
  const direct = index.types[name];
101
101
  if (direct)
@@ -109,28 +109,20 @@ export function getType(index, { name } = {}) {
109
109
  const keys = candidates
110
110
  .map(([key, record]) => describeCandidate(key, record))
111
111
  .join('; ');
112
- return {
113
- error: `Тип "${name}" неоднозначен — в ui-kit несколько разных типов с этим именем в разных модулях. Уточните одним из ключей: ${keys}.`,
114
- };
112
+ return new ToolError(`Тип "${name}" неоднозначен — в ui-kit несколько разных типов с этим именем в разных модулях. Уточните одним из ключей: ${keys}.`);
115
113
  }
116
114
  const ownerComponent = findComponentByPropsTypeName(index, name);
117
115
  if (ownerComponent) {
118
- return {
119
- error: `"${name}" — тип пропсов компонента ${ownerComponent}, в индексе типов его нет: ` +
120
- `пропсы разобраны по полям. Используйте get_component_props({name: "${ownerComponent}"}).`,
121
- };
116
+ return new ToolError(`"${name}" — тип пропсов компонента ${ownerComponent}, в индексе типов его нет: ` +
117
+ `пропсы разобраны по полям. Используйте get_component_props({name: "${ownerComponent}"}).`);
122
118
  }
123
119
  const similar = findSimilarKeys(index, lowerName);
124
120
  if (similar.length > 0) {
125
- return {
126
- error: `Тип "${name}" не найден в индексе. Похожие имена: ${similar.join(', ')}. ` +
127
- 'Если нужного нет и среди них — тип внутренний для ui-kit и наружу не экспортирован; ' +
128
- 'его форму можно увидеть в определении типа, который на него ссылается.',
129
- };
121
+ return new ToolError(`Тип "${name}" не найден в индексе. Похожие имена: ${similar.join(', ')}. ` +
122
+ 'Если нужного нет и среди них — тип внутренний для ui-kit и наружу не экспортирован; ' +
123
+ 'его форму можно увидеть в определении типа, который на него ссылается.');
130
124
  }
131
- return {
132
- error: `Тип "${name}" не найден в индексе. В индекс попадают типы, названные в пропсах компонентов, ` +
133
- 'и то, на что они ссылаются вглубь. Проверьте имя через get_component_props нужного компонента — ' +
134
- 'там типы полей приведены ровно так, как их печатает тайпчекер.',
135
- };
125
+ return new ToolError(`Тип "${name}" не найден в индексе. В индекс попадают типы, названные в пропсах компонентов, ` +
126
+ 'и то, на что они ссылаются вглубь. Проверьте имя через get_component_props нужного компонента — ' +
127
+ 'там типы полей приведены ровно так, как их печатает тайпчекер.');
136
128
  }
@@ -1,7 +1,8 @@
1
+ import { ToolError } from '../types.js';
1
2
  import { listComponentFeatures } from './shared.js';
2
3
  export function listFeatures(index, { component } = {}) {
3
4
  if (!component) {
4
- return { error: 'Параметр component обязателен.' };
5
+ return new ToolError('Параметр component обязателен.');
5
6
  }
6
7
  const features = listComponentFeatures(index, component);
7
8
  return {
@@ -1,4 +1,5 @@
1
1
  import { isOkComponent } from '../types.js';
2
+ import { COMPONENT_SEARCH_HINTS, FEATURE_SEARCH_HINTS, scoreSearchHints, TYPE_SEARCH_HINTS, } from './searchVocabulary.js';
2
3
  const LEGACY_PENALTY_FACTOR = 0.6;
3
4
  /**
4
5
  * По роли (см. classifyRole.ts) НЕ фильтруем — агент может целенаправленно
@@ -76,7 +77,7 @@ function scoreComponent(component, tokens) {
76
77
  const keywords = (component.keywords || []).join(' ').toLowerCase();
77
78
  const docs = (component.docs || '').toLowerCase();
78
79
  const category = (component.category || '').toLowerCase();
79
- let score = 0;
80
+ let score = scoreSearchHints(COMPONENT_SEARCH_HINTS[component.name], tokens);
80
81
  tokens.forEach((w) => {
81
82
  if (name === w)
82
83
  score += 100;
@@ -109,7 +110,7 @@ function scoreFeature(feature, tokens) {
109
110
  const summary = (feature.summary || '').toLowerCase();
110
111
  const docs = (feature.docs || '').toLowerCase();
111
112
  const apiDocs = (feature.apiDocs || '').toLowerCase();
112
- let score = 0;
113
+ let score = scoreSearchHints(FEATURE_SEARCH_HINTS[feature.feature], tokens);
113
114
  tokens.forEach((w) => {
114
115
  if (featureName === w)
115
116
  score += 80;
@@ -143,7 +144,7 @@ function scoreFeature(feature, tokens) {
143
144
  function scoreType(record, tokens) {
144
145
  const name = record.name.toLowerCase();
145
146
  const definition = record.definition.toLowerCase();
146
- let score = 0;
147
+ let score = scoreSearchHints(TYPE_SEARCH_HINTS[record.name], tokens);
147
148
  tokens.forEach((w) => {
148
149
  if (name === w)
149
150
  score += 90;
@@ -0,0 +1,20 @@
1
+ /** Короткие предметные синонимы для сущностей с техническими английскими именами. */
2
+ export const FEATURE_SEARCH_HINTS = {
3
+ ColumnsGrouping: 'группировка группировки колонок столбцов column grouping grouped columns',
4
+ RowsGrouping: 'группировка группировки строк rows grouping grouped rows',
5
+ InfinityScroll: 'бесконечная прокрутка прокрутки строк подгрузка infinite scroll lazy loading',
6
+ };
7
+ export const TYPE_SEARCH_HINTS = {
8
+ NumberFormatOptions: 'формат форматирование числа чисел колонке колонках столбце number column format formatting decimal precision',
9
+ ContentFormat: 'формат форматирование содержимого ячеек колонке столбце cell content column format',
10
+ };
11
+ export const COMPONENT_SEARCH_HINTS = {
12
+ FormDatePicker: 'поле ввода даты дата форме формы form date input picker',
13
+ FormDatePickerRange: 'диапазон дат даты форме формы form date range picker',
14
+ };
15
+ /** Несколько совпавших слов важнее единичного совпадения в длинной документации. */
16
+ export function scoreSearchHints(hints, tokens) {
17
+ const words = new Set((hints || '').split(/\s+/));
18
+ const hits = new Set(tokens.filter((token) => words.has(token))).size;
19
+ return hits >= 2 ? hits * 18 : hits * 4;
20
+ }
package/dist/types.js CHANGED
@@ -3,6 +3,13 @@
3
3
  export function isOkComponent(record) {
4
4
  return record.error === undefined;
5
5
  }
6
- export function isToolError(result) {
7
- return typeof result === 'object' && result !== null && 'error' in result;
6
+ /* ─────────────── Результаты тулзов ─────────────── */
7
+ export class ToolError {
8
+ error;
9
+ constructor(error) {
10
+ this.error = error;
11
+ }
12
+ toJSON() {
13
+ return { error: this.error };
14
+ }
8
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@digital-finance-ui/ui-kit-mcp",
3
- "version": "0.2.13",
3
+ "version": "0.2.15",
4
4
  "description": "MCP server for @sber-digital-finance-ui/ui-kit — component discovery, props and examples for coding agents",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,6 +11,11 @@
11
11
  "dist",
12
12
  "data"
13
13
  ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/daisforge/dais-ui.git",
17
+ "directory": "packages/mcp-server"
18
+ },
14
19
  "license": "MIT",
15
20
  "publishConfig": {
16
21
  "access": "public"