@sixbell-telco/sdk-tools 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.1.3] - 2026-11-19
11
+
12
+ ### Changed
13
+
14
+ - **mcp**: answers an agent host about 3x faster (about 40 ms to `initialize`, was about 130 ms) through its own stdio layer instead of `@modelcontextprotocol/sdk`, which with `zod` is no longer a dependency; what the host receives is byte for byte the same
15
+
16
+ ### Added
17
+
18
+ - **mcp**: `--cwd <dir>` names the app folder; started at a component root, the server finds the one app folder below it (`mfe/`), and the not-installed error names `--cwd` (NSU-142)
19
+
20
+ ## [0.1.2] - 2026-11-18
21
+
22
+ ### Added
23
+
24
+ - **check**: `MFE_PUBSUB_UNSUBSCRIBE_001` flags `PubSub.unsubscribe(<topic>)` (an `*_EVENTS` member or a string) in app code: pubsub-js removes every MFE's subscriber of that topic, so one child leaving a page left the others without `PERMISSIONS.RESPONSE` (SBP-78, Herald's edit buttons hidden until a reload). Unsubscribe the token `PubSub.subscribe` returns
25
+
10
26
  ## [0.1.1] - 2026-11-13
11
27
 
12
28
  ### Fixed
package/README.md CHANGED
@@ -33,7 +33,7 @@ Test and story files (`*.spec.ts`, `*.stories.ts`) are not linted: their templat
33
33
  | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34
34
  | federation | Child: exposes point at a remote shell that renders `MfeShadowShellComponent`; the stylesheet-href build step. Host: remotes wired, no child-only files. dayjs sharing | `MFE_CHILD_003`..`007`, `MFE_CHILD_FEDERATION_001`..`004`, `MFE_HOST_RUNTIME_002`..`005`, `MFE_FEDERATION_DAYJS_001`/`002` |
35
35
  | harness | The child's standalone harness (`MainLayoutComponent`, no remote shell inside) and the kit shell (`st-app-layout`, `provideLayout`, `provideLayoutAccount`, no local layout copies) | `MFE_CHILD_009`..`011`, `MFE_CHILD_HARNESS_001`/`002`, `MFE_CHILD_ROUTE_001`, `MFE_LAYOUT_001`..`003`, `005`, `006`, `008` |
36
- | wiring | Pubsub (child AUTH, host PERMISSIONS), request bypass by context in a child, the static dev menu, starter identity left behind | `MFE_CHILD_PUBSUB_001`, `MFE_HOST_PUBSUB_001`, `MFE_CHILD_CONFIG_001`, `MFE_MENU_001`/`002`, `MFE_GUAS_MENU_003`/`004`, `MFE_FEATURE_MENU_001`, `MFE_IDENTITY_001` |
36
+ | wiring | Pubsub (child AUTH, host PERMISSIONS, unsubscribing a topic instead of a token), request bypass by context in a child, the static dev menu, starter identity left behind | `MFE_CHILD_PUBSUB_001`, `MFE_HOST_PUBSUB_001`, `MFE_PUBSUB_UNSUBSCRIBE_001`, `MFE_CHILD_CONFIG_001`, `MFE_MENU_001`/`002`, `MFE_GUAS_MENU_003`/`004`, `MFE_FEATURE_MENU_001`, `MFE_IDENTITY_001` |
37
37
  | config | npm scripts against `angular.json` configurations and files, the test target, the showcase script, JSON that does not parse | `MFE_PROJECT_SCRIPT_001`, `MFE_PROJECT_TEST_001`, `MFE_SHOWCASE_001`, `MFE_JSON_001` |
38
38
  | i18n | `translation.json` schema and languages, bundles per language, the SDK bundles served from the installed package (not copied) | `MFE_I18N_001`..`009`, `MFE_CHILD_I18N_001`..`005`, `MFE_CHILD_I18N_WARN_001`, `MFE_TRANSLATIONS_001`, `MFE_ASSET_I18N_001`, `MFE_I18N_SDK_001` |
39
39
  | styles | `src/**/*.css` and the theme catalogs: literal colors outside theme definitions (catalogs, `@plugin "daisyui/theme"`, `@theme`), raw shadows and fonts, theme token overrides, legacy names; `.scss`, `.sass` and `.less` files; component styles (inline `styles`, `styleUrl(s)` files): literal colors and `.st-*`/`st-*` selectors (the Tailwind entry and global stylesheets are not component styles); the status-illustration animations in `styles.css` | `DS_COLOR_LITERAL`, `DS_COLOR_PALETTE`, `DS_SHADOW_RAW`, `DS_FONT_FAMILY`, `DS_THEME_TOKEN_OVERRIDE`, `DS_THEME_DUPLICATE`, `DS_MODIFIER_UNSAFE`, `DS_THEME_STALE_IDENTITY`, `DS_SIXBELL_LEGACY`, `DS_POPPINS_LEGACY`, `DS_SCSS_FILE`, `DS_COMPONENT_COLOR_LITERAL`, `DS_KIT_RESTYLE`, `MFE_STATUS_CSS_001` |
@@ -110,7 +110,9 @@ Findings have the same shape as `check`'s, plus `repo` (the repo's folder relati
110
110
 
111
111
  ## mcp
112
112
 
113
- `sdk-tools mcp` starts an MCP server over stdio, named `SixbellSdk`. Its tools answer from the `@sixbell-telco/sdk` installed in the folder it starts in (the SDK's `manifest.json`), so an agent gets the facts of the version the app really uses. `check_usage` runs the same lint as `check`.
113
+ `sdk-tools mcp` starts an MCP server over stdio, named `SixbellSdk`. Its tools answer from the `@sixbell-telco/sdk` installed in the app folder (the SDK's `manifest.json`), so an agent gets the facts of the version the app really uses. `check_usage` runs the same lint as `check`.
114
+
115
+ The app folder is `--cwd <dir>`, else the folder the server starts in when the SDK is installed there, else the one folder directly under it whose `package.json` lists `@sixbell-telco/sdk`. With more than one such folder the tools return an error naming them; pass `--cwd`.
114
116
 
115
117
  Add it to the app's `.mcp.json`:
116
118
 
@@ -118,6 +120,12 @@ Add it to the app's `.mcp.json`:
118
120
  { "mcpServers": { "SixbellSdk": { "command": "npx", "args": ["@sixbell-telco/sdk-tools", "mcp"] } } }
119
121
  ```
120
122
 
123
+ A component repo set (the `.mcp.json` at the component root, the app in `mfe/`) runs the `sdk-tools` the app already has as a devDependency, so it starts in well under a second instead of downloading the package on a cold npx cache (an agent host such as Claude Code gives up after 30 seconds):
124
+
125
+ ```json
126
+ { "mcpServers": { "SixbellSdk": { "command": "npx", "args": ["--prefix", "mfe", "--no-install", "sdk-tools", "mcp", "--cwd", "mfe"] } } }
127
+ ```
128
+
121
129
  | Tool | Returns |
122
130
  | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
123
131
  | `list_components` | Every component, directive and pipe: selector, class, kind, entry point, one-line description (`kind` filters) |
@@ -131,7 +139,7 @@ Add it to the app's `.mcp.json`:
131
139
 
132
140
  Resources: `sixbell-sdk://design` (the app's `DESIGN.md`), `sixbell-sdk://glossary` (the installed SDK's `GLOSSARY.md`; an SDK before 4.6.0 gets a one-line message) and `sixbell-sdk://recipes/<id>`. Recipes live in [`recipes/`](recipes), whose README documents the format.
133
141
 
134
- A tool that needs the manifest returns an error naming the fix when the SDK is not installed or ships no manifest (SDK 4.6.0 or later). `--manifest <file>` answers from another manifest.
142
+ A tool that needs the manifest returns an error naming the folder and the fix when the SDK is not installed or ships no manifest (SDK 4.6.0 or later). `--manifest <file>` answers from another manifest.
135
143
 
136
144
  ## init
137
145
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sixbell-telco/sdk-tools",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "CLI and MCP server for apps built with @sixbell-telco/sdk: check templates, imports and types against the installed SDK, and create or upgrade MFEs from their template repos",
5
5
  "type": "module",
6
6
  "bin": {
@@ -27,13 +27,11 @@
27
27
  "node": "^22.12.0 || ^24.0.0"
28
28
  },
29
29
  "dependencies": {
30
- "@modelcontextprotocol/sdk": "^1.32.2",
31
30
  "@sixbell-telco/eslint-plugin-sdk": "0.1.1",
32
31
  "angular-eslint": "^19.0.0",
33
32
  "eslint": "^9.0.0",
34
33
  "shadcn-lint-angular": "0.1.2",
35
- "typescript-eslint": "^8.0.0",
36
- "zod": "^4.4.3"
34
+ "typescript-eslint": "^8.0.0"
37
35
  },
38
36
  "peerDependencies": {
39
37
  "@angular-devkit/core": "^19.0.0",
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * Project wiring step: pubsub, host-owned code in a child, the static dev menu and starter leftovers.
3
- * Ids: MFE_CHILD_PUBSUB_001, MFE_HOST_PUBSUB_001, MFE_CHILD_CONFIG_001, MFE_MENU_001/002,
4
- * MFE_GUAS_MENU_003/004, MFE_FEATURE_MENU_001, MFE_IDENTITY_001.
3
+ * Ids: MFE_CHILD_PUBSUB_001, MFE_HOST_PUBSUB_001, MFE_PUBSUB_UNSUBSCRIBE_001, MFE_CHILD_CONFIG_001,
4
+ * MFE_MENU_001/002, MFE_GUAS_MENU_003/004, MFE_FEATURE_MENU_001, MFE_IDENTITY_001.
5
5
  */
6
6
  import { readText, walk } from '../project/project.mjs';
7
- import { finding } from './finding.mjs';
7
+ import { finding, position } from './finding.mjs';
8
8
 
9
9
  /**
10
10
  * @typedef {import('../types.js').Finding} Finding
@@ -59,6 +59,38 @@ function pubsub(project) {
59
59
  return [];
60
60
  }
61
61
 
62
+ /** `PubSub.unsubscribe(<arg>)`; the argument is checked on its own. */
63
+ const UNSUBSCRIBE = /PubSub\.unsubscribe\(\s*([^)]*?)\s*\)/g;
64
+ /** A topic rather than a token: an `*_EVENTS.X` member or a string literal. */
65
+ const TOPIC = /^(?:[A-Z][A-Z0-9_]*_EVENTS\.[A-Z][A-Z0-9_]*|(['"`])[^'"`]*\1)$/;
66
+
67
+ /**
68
+ * MFE_PUBSUB_UNSUBSCRIBE_001: unsubscribe the token `PubSub.subscribe` returned, never a topic. pubsub-js
69
+ * removes every subscriber of a topic, so one child leaving a page deafens the host and every other child
70
+ * (SBP-78: Herald lost PERMISSIONS.RESPONSE and hid its edit buttons until a reload).
71
+ * @param {ProjectInfo} project
72
+ * @returns {Finding[]}
73
+ */
74
+ function pubsubUnsubscribe(project) {
75
+ /** @type {Finding[]} */
76
+ const findings = [];
77
+ for (const file of walk(project.root, 'src', (name) => name.endsWith('.ts') && !name.endsWith('.spec.ts'))) {
78
+ const source = readText(project.root, file) ?? '';
79
+ for (const match of source.matchAll(UNSUBSCRIBE)) {
80
+ if (!TOPIC.test(match[1])) continue;
81
+ findings.push(
82
+ finding(
83
+ 'MFE_PUBSUB_UNSUBSCRIBE_001',
84
+ file,
85
+ `PubSub.unsubscribe(${match[1]}) removes every MFE's subscriber of that topic. Keep the token PubSub.subscribe returns and unsubscribe it.`,
86
+ position(source, match.index ?? 0),
87
+ ),
88
+ );
89
+ }
90
+ }
91
+ return findings;
92
+ }
93
+
62
94
  /**
63
95
  * MFE_CHILD_CONFIG_001: request bypass by context, not by URL, and no host manifest loading in a child.
64
96
  * @param {ProjectInfo} project
@@ -194,5 +226,11 @@ function identity(project) {
194
226
  */
195
227
  export function wiringStep(project) {
196
228
  if (!project.role) return [];
197
- return [...pubsub(project), ...(project.role === 'child' ? childConfig(project) : []), ...staticMenu(project), ...identity(project)];
229
+ return [
230
+ ...pubsub(project),
231
+ ...pubsubUnsubscribe(project),
232
+ ...(project.role === 'child' ? childConfig(project) : []),
233
+ ...staticMenu(project),
234
+ ...identity(project),
235
+ ];
198
236
  }
package/src/cli.mjs CHANGED
@@ -118,23 +118,39 @@ const VERBS = {
118
118
  usage: 'sdk-tools mcp [options]',
119
119
  help: [
120
120
  'Starts an MCP server on stdin/stdout (server name SixbellSdk). Its tools answer from the',
121
- '@sixbell-telco/sdk installed in the current folder and run the same checks as sdk-tools check:',
121
+ '@sixbell-telco/sdk installed in the app folder and run the same checks as sdk-tools check:',
122
122
  'list_components, search_components, get_component, get_tokens, check_usage, get_recipe.',
123
- "Resources: the app's DESIGN.md and the recipes. Start it from the app's folder.",
123
+ "Resources: the app's DESIGN.md and the recipes.",
124
+ '',
125
+ 'The app folder is --cwd, else the current folder when the SDK is installed there, else the',
126
+ 'one folder directly under it whose package.json lists @sixbell-telco/sdk (a component root',
127
+ 'such as componentes/timezone/ with the app in mfe/). With several such folders, pass --cwd.',
124
128
  '',
125
129
  'Options:',
130
+ ' --cwd <dir> the app folder (relative to the current folder)',
126
131
  ' --manifest <file> answer from this manifest instead of the installed SDK',
127
132
  '',
128
133
  'Example (.mcp.json of an app):',
129
134
  ' { "mcpServers": { "SixbellSdk": { "command": "npx", "args": ["@sixbell-telco/sdk-tools", "mcp"] } } }',
135
+ "Example (.mcp.json of a component root, app in mfe/; runs the app's installed sdk-tools):",
136
+ ' { "mcpServers": { "SixbellSdk": { "command": "npx",',
137
+ ' "args": ["--prefix", "mfe", "--no-install", "sdk-tools", "mcp", "--cwd", "mfe"] } } }',
130
138
  ].join('\n'),
131
139
  options: {
140
+ cwd: { type: 'string' },
132
141
  manifest: { type: 'string' },
133
142
  help: { type: 'boolean', short: 'h', default: false },
134
143
  },
135
144
  async run(values) {
145
+ const { statSync } = await import('node:fs');
146
+ const { resolve } = await import('node:path');
147
+ const explicit = typeof values.cwd === 'string';
148
+ const cwd = resolve(explicit ? /** @type {string} */ (values.cwd) : '.');
149
+ if (explicit && !statSync(cwd, { throwIfNoEntry: false })?.isDirectory()) throw new UsageError(`--cwd ${cwd} is not a folder`);
136
150
  const { serve } = await import('./mcp/server.mjs');
137
- await serve({ cwd: process.cwd(), manifestPath: typeof values.manifest === 'string' ? values.manifest : undefined });
151
+ // --manifest stays relative to where the server starts, not to the app folder.
152
+ const manifestPath = typeof values.manifest === 'string' ? resolve(values.manifest) : undefined;
153
+ await serve({ cwd, explicit, manifestPath });
138
154
  // The client is gone: exit without writing to stdout, which carried the protocol.
139
155
  process.exit(0);
140
156
  },
@@ -2,7 +2,7 @@
2
2
  * The manifest the MCP tools answer from: `@sixbell-telco/sdk/manifest.json` of the SDK installed
3
3
  * in the app (resolved from the app's folder), so every answer matches the version the app uses.
4
4
  */
5
- import { readFileSync } from 'node:fs';
5
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
6
6
  import { createRequire } from 'node:module';
7
7
  import { join, resolve } from 'node:path';
8
8
 
@@ -17,6 +17,55 @@ const SDK = '@sixbell-telco/sdk';
17
17
  /** A problem the user fixes in the app (install or upgrade the SDK), reported without a stack. */
18
18
  export class ManifestError extends Error {}
19
19
 
20
+ /** @param {string} dir @returns {boolean} the SDK resolves from `dir` (its node_modules or above). */
21
+ function hasSdk(dir) {
22
+ try {
23
+ createRequire(join(dir, 'noop.js')).resolve(`${SDK}/package.json`);
24
+ return true;
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ /** @param {string} dir @returns {boolean} `dir`/package.json lists the SDK as a dependency. */
31
+ function declaresSdk(dir) {
32
+ try {
33
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
34
+ return [pkg.dependencies, pkg.devDependencies, pkg.peerDependencies].some((deps) => deps && Object.hasOwn(deps, SDK));
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The app folder the server answers for. `cwd` itself when the SDK resolves from it. Otherwise,
42
+ * for a session opened at a component root (`componentes/timezone/` with the app in `mfe/`), the
43
+ * one folder directly under `cwd` whose package.json lists the SDK. Several such folders, or none,
44
+ * is a ManifestError naming them and `--cwd`. `explicit` (from --cwd) skips the search.
45
+ * @param {string} cwd
46
+ * @param {{ explicit?: boolean }} [options]
47
+ * @returns {string}
48
+ */
49
+ export function findApp(cwd, { explicit = false } = {}) {
50
+ if (explicit || hasSdk(cwd)) return cwd;
51
+ /** @type {string[]} */
52
+ let names = [];
53
+ try {
54
+ names = readdirSync(cwd, { withFileTypes: true })
55
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules' && declaresSdk(join(cwd, e.name)))
56
+ .map((e) => e.name)
57
+ .sort();
58
+ } catch {
59
+ // unreadable: no candidates
60
+ }
61
+ if (names.length === 1) return join(cwd, names[0]);
62
+ if (names.length > 1)
63
+ throw new ManifestError(
64
+ `@sixbell-telco/sdk is not installed in ${cwd}, and more than one folder under it is an app: ${names.join(', ')}. Fix: start the MCP server with --cwd <app folder> (for example sdk-tools mcp --cwd ${names[0]}), then restart the server.`,
65
+ );
66
+ return cwd;
67
+ }
68
+
20
69
  /**
21
70
  * The installed manifest, or the one at `manifestPath`. Throws ManifestError naming the fix when
22
71
  * the SDK is missing or too old to ship a manifest.
@@ -46,7 +95,7 @@ export function loadManifest({ cwd, manifestPath }) {
46
95
  throw new ManifestError(
47
96
  version
48
97
  ? `@sixbell-telco/sdk ${version} is installed in ${cwd} but ships no manifest.json (SDK 4.6.0 or later ships it). Fix: npm install @sixbell-telco/sdk@latest, then restart the MCP server.`
49
- : `@sixbell-telco/sdk is not installed in ${cwd}. Fix: start the MCP server from the app's folder (the one with package.json and node_modules), or run npm install @sixbell-telco/sdk there, then restart the server.`,
98
+ : `@sixbell-telco/sdk is not installed in ${cwd}${existsSync(join(cwd, 'package.json')) ? '' : ' or a folder directly under it'}. Fix: start the MCP server with --cwd <app folder> (the one with package.json and node_modules), or run npm install @sixbell-telco/sdk there, then restart the server.`,
50
99
  );
51
100
  }
52
101
  return { path, manifest: JSON.parse(readFileSync(path, 'utf8')) };
@@ -0,0 +1,240 @@
1
+ /**
2
+ * The part of MCP this server uses, over stdio: initialize, ping, tools and resources.
3
+ *
4
+ * Hand-written so `sdk-tools mcp` answers an agent host in tens of milliseconds: the
5
+ * @modelcontextprotocol/sdk McpServer took about 65 ms to load (zod, ajv and the schemas of the
6
+ * whole protocol). What a host receives is held to the bytes the SDK server sent by
7
+ * test/fixtures/mcp-surface.json (tool and resource lists, validation and not-found errors,
8
+ * protocol version negotiation), and the tests drive it with the SDK's own client.
9
+ */
10
+ import { createInterface } from 'node:readline';
11
+
12
+ /**
13
+ * @typedef {{ type: 'text', text: string }} TextContent
14
+ * @typedef {{ content: TextContent[], isError?: boolean }} ToolResult
15
+ * @typedef {{ description?: string, type: 'string', minLength?: number, enum?: string[] }} StringSchema
16
+ * @typedef {{ $schema: string, type: 'object', properties: Record<string, StringSchema>, required?: string[] }} InputSchema
17
+ * @typedef {{ readOnlyHint?: boolean, openWorldHint?: boolean }} ToolAnnotations
18
+ * @typedef {{ title: string, description: string, inputSchema: InputSchema, annotations: ToolAnnotations }} ToolConfig
19
+ * @typedef {{ title: string, description: string, mimeType: string }} ResourceConfig
20
+ * @typedef {{ uri: string, mimeType: string, text: string }} ResourceContent
21
+ * @typedef {{ jsonrpc?: string, id?: string | number, method?: string, params?: any }} Message
22
+ */
23
+
24
+ /** The protocol versions the SDK server accepted, newest first; any other gets the newest. */
25
+ const SUPPORTED_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];
26
+
27
+ /** A string the tool may go without. */
28
+ export function optionalString(/** @type {string} */ description, /** @type {string[]} */ values = []) {
29
+ /** @type {StringSchema} */
30
+ const schema = { description, type: 'string' };
31
+ if (values.length) schema.enum = values;
32
+ return schema;
33
+ }
34
+
35
+ /** A string the tool needs, not empty. */
36
+ export function requiredString(/** @type {string} */ description) {
37
+ return /** @type {StringSchema} */ ({ type: 'string', minLength: 1, description });
38
+ }
39
+
40
+ /**
41
+ * A tool's input: an object of string properties; the required ones are those with minLength.
42
+ * @param {Record<string, StringSchema>} properties
43
+ * @returns {InputSchema}
44
+ */
45
+ export function inputSchema(properties) {
46
+ const required = Object.keys(properties).filter((key) => properties[key].minLength !== undefined);
47
+ return {
48
+ $schema: 'http://json-schema.org/draft-07/schema#',
49
+ type: 'object',
50
+ properties,
51
+ ...(required.length ? { required } : {}),
52
+ };
53
+ }
54
+
55
+ /** @param {unknown} value */
56
+ function typeName(value) {
57
+ if (value === null) return 'null';
58
+ if (Array.isArray(value)) return 'array';
59
+ if (typeof value === 'number' && Number.isNaN(value)) return 'nan';
60
+ return typeof value;
61
+ }
62
+
63
+ /**
64
+ * The problems of `args` against `schema`, one line each, in property order (the wording the SDK
65
+ * server's validation gave, so an agent that retries sees the same text).
66
+ * @param {InputSchema} schema
67
+ * @param {Record<string, unknown>} args
68
+ * @returns {string[]}
69
+ */
70
+ function validate(schema, args) {
71
+ const required = new Set(schema.required ?? []);
72
+ /** @type {string[]} */
73
+ const problems = [];
74
+ for (const [key, property] of Object.entries(schema.properties)) {
75
+ const value = args[key];
76
+ if (value === undefined && !required.has(key)) continue;
77
+ if (property.enum) {
78
+ if (!property.enum.includes(/** @type {string} */ (value)))
79
+ problems.push(`Invalid option: expected one of ${property.enum.map((v) => JSON.stringify(v)).join('|')} at ${key}`);
80
+ } else if (typeof value !== 'string') {
81
+ problems.push(`Invalid input: expected string, received ${typeName(value)} at ${key}`);
82
+ // zod still ran the length check on an array, so a short one got a second line.
83
+ if (Array.isArray(value) && property.minLength !== undefined && value.length < property.minLength)
84
+ problems.push(`Too small: expected array to have >=${property.minLength} items at ${key}`);
85
+ } else if (property.minLength !== undefined && value.length < property.minLength)
86
+ problems.push(`Too small: expected string to have >=${property.minLength} characters at ${key}`);
87
+ }
88
+ return problems;
89
+ }
90
+
91
+ /** A JSON-RPC error answered to a request. */
92
+ class RpcError extends Error {
93
+ /** @param {number} code @param {string} message */
94
+ constructor(code, message) {
95
+ super(message);
96
+ this.code = code;
97
+ }
98
+ }
99
+
100
+ /** An MCP server with tools and fixed-URI resources, answering one JSON-RPC message at a time. */
101
+ export class Server {
102
+ /** @type {Map<string, { config: ToolConfig, run: (args: any) => Promise<ToolResult> }>} */
103
+ #tools = new Map();
104
+ /** @type {Map<string, { name: string, config: ResourceConfig, read: (uri: URL) => { contents: ResourceContent[] } }>} */
105
+ #resources = new Map();
106
+
107
+ /** @param {{ name: string, version: string, instructions: string }} info */
108
+ constructor(info) {
109
+ this.info = info;
110
+ }
111
+
112
+ /**
113
+ * @param {string} name
114
+ * @param {ToolConfig} config
115
+ * @param {(args: any) => Promise<ToolResult>} run
116
+ */
117
+ registerTool(name, config, run) {
118
+ this.#tools.set(name, { config, run });
119
+ }
120
+
121
+ /**
122
+ * @param {string} name
123
+ * @param {string} uri
124
+ * @param {ResourceConfig} config
125
+ * @param {(uri: URL) => { contents: ResourceContent[] }} read
126
+ */
127
+ registerResource(name, uri, config, read) {
128
+ this.#resources.set(uri, { name, config, read });
129
+ }
130
+
131
+ /**
132
+ * The response line for one incoming message, or null for a notification or a response.
133
+ * @param {Message} message
134
+ * @returns {Promise<string | null>}
135
+ */
136
+ async handle(message) {
137
+ if (message === null || typeof message !== 'object' || message.id === undefined || typeof message.method !== 'string') return null;
138
+ const { id } = message;
139
+ try {
140
+ const result = await this.#answer(message.method, message.params ?? {});
141
+ return JSON.stringify({ result, jsonrpc: '2.0', id });
142
+ } catch (thrown) {
143
+ if (!(thrown instanceof RpcError)) throw thrown;
144
+ return JSON.stringify({ jsonrpc: '2.0', id, error: { code: thrown.code, message: thrown.message } });
145
+ }
146
+ }
147
+
148
+ /** @param {string} method @param {any} params */
149
+ async #answer(method, params) {
150
+ switch (method) {
151
+ case 'initialize':
152
+ return {
153
+ protocolVersion: SUPPORTED_VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : SUPPORTED_VERSIONS[0],
154
+ capabilities: { tools: { listChanged: true }, resources: { listChanged: true } },
155
+ serverInfo: { name: this.info.name, version: this.info.version },
156
+ instructions: this.info.instructions,
157
+ };
158
+ case 'ping':
159
+ return {};
160
+ case 'tools/list':
161
+ return {
162
+ tools: [...this.#tools].map(([name, { config }]) => ({
163
+ name,
164
+ title: config.title,
165
+ description: config.description,
166
+ inputSchema: config.inputSchema,
167
+ annotations: config.annotations,
168
+ execution: { taskSupport: 'forbidden' },
169
+ })),
170
+ };
171
+ case 'tools/call':
172
+ return this.#call(params.name, params.arguments ?? {});
173
+ case 'resources/list':
174
+ return {
175
+ resources: [...this.#resources].map(([uri, { name, config }]) => ({
176
+ uri,
177
+ name,
178
+ title: config.title,
179
+ description: config.description,
180
+ mimeType: config.mimeType,
181
+ })),
182
+ };
183
+ case 'resources/templates/list':
184
+ return { resourceTemplates: [] };
185
+ case 'resources/read': {
186
+ const resource = this.#resources.get(params.uri);
187
+ if (!resource) throw new RpcError(-32602, `MCP error -32602: Resource ${params.uri} not found`);
188
+ return resource.read(new URL(params.uri));
189
+ }
190
+ default:
191
+ throw new RpcError(-32601, 'Method not found');
192
+ }
193
+ }
194
+
195
+ /**
196
+ * @param {string} name
197
+ * @param {Record<string, unknown>} args
198
+ * @returns {Promise<ToolResult>}
199
+ */
200
+ async #call(name, args) {
201
+ const tool = this.#tools.get(name);
202
+ /** @param {string} text */
203
+ const failed = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text: `MCP error -32602: ${text}` }], isError: true });
204
+ if (!tool) return failed(`Tool ${name} not found`);
205
+ const problems = validate(tool.config.inputSchema, args);
206
+ if (problems.length) return failed(`Input validation error: Invalid arguments for tool ${name}: ${problems.join('\n')}`);
207
+ // Like the SDK, the tool gets only the properties it declares.
208
+ const known = Object.fromEntries(
209
+ Object.keys(tool.config.inputSchema.properties)
210
+ .filter((k) => args[k] !== undefined)
211
+ .map((k) => [k, args[k]]),
212
+ );
213
+ return tool.run(known);
214
+ }
215
+
216
+ /**
217
+ * Reads newline-delimited JSON-RPC from `input` and writes each answer to `output` as soon as
218
+ * it is ready, until `input` ends. A line that is not JSON gets no answer, as with the SDK.
219
+ * @param {NodeJS.ReadableStream} input
220
+ * @param {NodeJS.WritableStream} output
221
+ * @returns {Promise<void>}
222
+ */
223
+ serve(input, output) {
224
+ const lines = createInterface({ input, crlfDelay: Infinity });
225
+ lines.on('line', (line) => {
226
+ if (!line.trim()) return;
227
+ let message;
228
+ try {
229
+ message = JSON.parse(line);
230
+ } catch {
231
+ return;
232
+ }
233
+ this.handle(message).then(
234
+ (answer) => answer && output.write(`${answer}\n`),
235
+ (thrown) => console.error(`sdk-tools mcp: ${thrown instanceof Error ? thrown.stack : thrown}`),
236
+ );
237
+ });
238
+ return new Promise((done) => lines.once('close', () => done()));
239
+ }
240
+ }
@@ -172,16 +172,19 @@ function withFiles(recipe, dir) {
172
172
 
173
173
  /**
174
174
  * Every recipe in `dir`, sorted by id. README.md documents the format and is not a recipe.
175
+ * `files: false` skips reading the template parts (`files` and `i18nKeys` stay empty): the MCP
176
+ * server lists recipes at startup and reads the parts on the first get_recipe call.
175
177
  * @param {string} [dir]
178
+ * @param {{ files?: boolean }} [options]
176
179
  * @returns {Recipe[]}
177
180
  */
178
- export function loadRecipes(dir = RECIPES_DIR) {
181
+ export function loadRecipes(dir = RECIPES_DIR, { files = true } = {}) {
179
182
  return readdirSync(dir)
180
183
  .filter((name) => name.endsWith('.md') && name !== 'README.md')
181
184
  .map((name) => {
182
185
  const recipe = parseRecipe(readFileSync(join(dir, name), 'utf8'), name);
183
186
  if (`${recipe.id}.md` !== name) throw new Error(`${name}: the file name must be <id>.md (id is "${recipe.id}")`);
184
- return withFiles(recipe, dir);
187
+ return files ? withFiles(recipe, dir) : recipe;
185
188
  })
186
189
  .sort((a, b) => a.id.localeCompare(b.id));
187
190
  }
@@ -3,21 +3,17 @@
3
3
  * Every answer comes from the SDK installed in the app (its manifest) and the same check engine as
4
4
  * `sdk-tools check`, so it matches the kit version the app really uses.
5
5
  */
6
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
6
  import { existsSync, readFileSync } from 'node:fs';
9
7
  import { join } from 'node:path';
10
- import { z } from 'zod';
11
8
  import { getComponent, getTokens, listComponents, NotFoundError, searchComponents } from './catalog.mjs';
12
9
  import { findTerm, GlossaryError, loadGlossary } from './glossary.mjs';
13
- import { loadManifest, ManifestError } from './manifest.mjs';
10
+ import { findApp, loadManifest, ManifestError } from './manifest.mjs';
11
+ import { inputSchema, optionalString, requiredString, Server } from './protocol.mjs';
14
12
  import { findRecipe, loadRecipes } from './recipes.mjs';
15
- import { upgradeGuide } from './upgrade-guide.mjs';
16
- import { checkUsage } from './usage.mjs';
17
13
 
18
14
  /**
19
- * @typedef {import('@modelcontextprotocol/sdk/types.js').CallToolResult} CallToolResult
20
- * @typedef {{ cwd: string, manifestPath?: string }} ServerOptions
15
+ * @typedef {import('./protocol.mjs').ToolResult} CallToolResult
16
+ * @typedef {{ cwd: string, explicit?: boolean, manifestPath?: string }} ServerOptions
21
17
  */
22
18
 
23
19
  /** The server name agents see: its tools show up as `SixbellSdk:<tool>`. */
@@ -41,25 +37,31 @@ async function answer(body) {
41
37
  } catch (thrown) {
42
38
  const known = thrown instanceof ManifestError || thrown instanceof NotFoundError || thrown instanceof GlossaryError;
43
39
  const message = thrown instanceof Error ? thrown.message : String(thrown);
44
- return { isError: true, content: [{ type: 'text', text: known ? message : `sdk-tools failed: ${message}` }] };
40
+ return { content: [{ type: 'text', text: known ? message : `sdk-tools failed: ${message}` }], isError: true };
45
41
  }
46
42
  }
47
43
 
48
44
  /**
49
45
  * The configured server (not yet connected), for `serve`.
50
46
  * @param {ServerOptions} options
51
- * @returns {McpServer}
47
+ * @returns {Server}
52
48
  */
53
- function createServer({ cwd, manifestPath }) {
54
- const server = new McpServer(
55
- { name: SERVER_NAME, version: version() },
56
- {
57
- instructions:
58
- 'Facts about the Enghouse Networks UI Kit (@sixbell-telco/sdk) installed in this app. Use these tools instead of guessing: search_components or list_components to find a kit component, get_component for its exact inputs and allowed values, get_tokens for theme colors and roles, get_recipe for how to build a screen or a local component, check_usage to verify your template before you finish, get_upgrade_guide for what an SDK upgrade involves, and get_glossary for what a kit term means. Use the glossary terms when you write about the kit.',
59
- },
60
- );
61
- const manifest = () => loadManifest({ cwd, manifestPath }).manifest;
62
- const recipes = loadRecipes();
49
+ function createServer({ cwd: start, explicit = false, manifestPath }) {
50
+ const server = new Server({
51
+ name: SERVER_NAME,
52
+ version: version(),
53
+ instructions:
54
+ 'Facts about the Enghouse Networks UI Kit (@sixbell-telco/sdk) installed in this app. Use these tools instead of guessing: search_components or list_components to find a kit component, get_component for its exact inputs and allowed values, get_tokens for theme colors and roles, get_recipe for how to build a screen or a local component, check_usage to verify your template before you finish, get_upgrade_guide for what an SDK upgrade involves, and get_glossary for what a kit term means. Use the glossary terms when you write about the kit.',
55
+ });
56
+ // The app folder: the start folder, or the one app directly under it (a component root).
57
+ // Found on each call, so installing the SDK or adding the app needs no restart.
58
+ const app = () => findApp(start, { explicit });
59
+ const manifest = () => loadManifest({ cwd: app(), manifestPath }).manifest;
60
+ // Ids, titles and bodies now; the files and i18n keys get_recipe returns on its first call.
61
+ const recipes = loadRecipes(undefined, { files: false });
62
+ /** @type {ReturnType<typeof loadRecipes> | undefined} */
63
+ let withFiles;
64
+ const fullRecipes = () => (withFiles ??= loadRecipes());
63
65
  const readOnly = { readOnlyHint: true, openWorldHint: false };
64
66
 
65
67
  server.registerTool(
@@ -68,7 +70,7 @@ function createServer({ cwd, manifestPath }) {
68
70
  title: 'List kit components',
69
71
  description:
70
72
  "List every component, directive and pipe of the installed @sixbell-telco/sdk: selector (st-*), class name, kind, entry point and a one-line description. Use it to see what the kit has. For one component's inputs, call get_component.",
71
- inputSchema: { kind: z.enum(['component', 'directive', 'pipe']).optional().describe('Only this kind. Leave empty for all.') },
73
+ inputSchema: inputSchema({ kind: optionalString('Only this kind. Leave empty for all.', ['component', 'directive', 'pipe']) }),
72
74
  annotations: readOnly,
73
75
  },
74
76
  ({ kind }) => answer(() => listComponents(manifest(), { kind })),
@@ -80,7 +82,7 @@ function createServer({ cwd, manifestPath }) {
80
82
  title: 'Search kit components',
81
83
  description:
82
84
  'Find kit components for a need, by words such as "dialog", "table", "date picker" or "status badge". Returns the best matches with selector, entry point and description. Then call get_component with the selector you pick.',
83
- inputSchema: { query: z.string().min(1).describe('What you need, in a few words. Example: "confirm dialog".') },
85
+ inputSchema: inputSchema({ query: requiredString('What you need, in a few words. Example: "confirm dialog".') }),
84
86
  annotations: readOnly,
85
87
  },
86
88
  ({ query }) => answer(() => searchComponents(manifest(), query)),
@@ -92,9 +94,9 @@ function createServer({ cwd, manifestPath }) {
92
94
  title: 'Get a kit component',
93
95
  description:
94
96
  "Get the exact API of one kit component from the installed SDK: inputs with their allowed values and defaults, outputs, content slots, the import line, a starting template, related components, Storybook examples, and do and don't rules. Use only the inputs and values it lists.",
95
- inputSchema: {
96
- selector: z.string().min(1).describe('The selector or class name. Examples: "st-dialog", "dialog", "DialogComponent", "stTextColor".'),
97
- },
97
+ inputSchema: inputSchema({
98
+ selector: requiredString('The selector or class name. Examples: "st-dialog", "dialog", "DialogComponent", "stTextColor".'),
99
+ }),
98
100
  annotations: readOnly,
99
101
  },
100
102
  ({ selector }) => answer(() => getComponent(manifest(), selector)),
@@ -106,9 +108,9 @@ function createServer({ cwd, manifestPath }) {
106
108
  title: 'Get theme tokens',
107
109
  description:
108
110
  'Get the theme tokens of the installed SDK: semantic colors (use as bg-<token>, text-<token>, border-<token>), radius, shadow, easing, animation, font and text roles, plus deprecated tokens and their replacements. Use these instead of palette colors (bg-red-500), hex values or arbitrary values.',
109
- inputSchema: {
110
- group: z.string().optional().describe('Only one group: color, radius, shadow, ease, animate, font or text. Leave empty for all.'),
111
- },
111
+ inputSchema: inputSchema({
112
+ group: optionalString('Only one group: color, radius, shadow, ease, animate, font or text. Leave empty for all.'),
113
+ }),
112
114
  annotations: readOnly,
113
115
  },
114
116
  ({ group }) => answer(() => getTokens(manifest(), { group })),
@@ -120,17 +122,19 @@ function createServer({ cwd, manifestPath }) {
120
122
  title: 'Check kit usage',
121
123
  description:
122
124
  'Check a template or component against the kit, with the same rules as `sdk-tools check` (kit API, allowed input values, imports, design rules: no raw colors, arbitrary values, inline styles or restyled kit components). Pass a file path inside the app, or a snippet (HTML template or a whole .component.ts). Returns findings with rule, line and message; fix every error and check again. It does not type-check; run `sdk-tools check` for that.',
123
- inputSchema: {
124
- file: z.string().optional().describe('A file path relative to the app folder. Example: "src/app/orders/orders.component.html".'),
125
- snippet: z.string().optional().describe('Template or component source to check without saving it.'),
126
- language: z.enum(['html', 'ts']).optional().describe('What the snippet is. Default: ts when it has @Component( or imports, else html.'),
127
- },
125
+ inputSchema: inputSchema({
126
+ file: optionalString('A file path relative to the app folder. Example: "src/app/orders/orders.component.html".'),
127
+ snippet: optionalString('Template or component source to check without saving it.'),
128
+ language: optionalString('What the snippet is. Default: ts when it has @Component( or imports, else html.', ['html', 'ts']),
129
+ }),
128
130
  annotations: { readOnlyHint: true, openWorldHint: false },
129
131
  },
130
132
  ({ file, snippet, language }) =>
131
133
  answer(async () => {
132
134
  if ((file === undefined) === (snippet === undefined)) throw new NotFoundError('pass either file or snippet (one of them, not both)');
135
+ const cwd = app();
133
136
  const { path } = loadManifest({ cwd, manifestPath });
137
+ const { checkUsage } = await import('./usage.mjs');
134
138
  const result = await checkUsage({ cwd, manifestPath: path, file, snippet, language });
135
139
  return { ...result, ok: result.counts.errors === 0 };
136
140
  }),
@@ -141,18 +145,13 @@ function createServer({ cwd, manifestPath }) {
141
145
  {
142
146
  title: 'Get a recipe',
143
147
  description: `Get a step-by-step recipe for building something with the kit. Recipes: ${recipes.map((r) => `${r.id} (${r.summary})`).join('; ')}. Call it with no id to list them.`,
144
- inputSchema: {
145
- id: z
146
- .string()
147
- .optional()
148
- .describe(`The recipe id: ${recipes.map((r) => r.id).join(', ')}.`),
149
- },
148
+ inputSchema: inputSchema({ id: optionalString(`The recipe id: ${recipes.map((r) => r.id).join(', ')}.`) }),
150
149
  annotations: readOnly,
151
150
  },
152
151
  ({ id }) =>
153
152
  answer(() =>
154
153
  id
155
- ? findRecipe(recipes, id)
154
+ ? findRecipe(fullRecipes(), id)
156
155
  : { recipes: recipes.map(({ id: recipeId, title, summary, kitCandidate }) => ({ id: recipeId, title, summary, kitCandidate })) },
157
156
  ),
158
157
  );
@@ -163,13 +162,13 @@ function createServer({ cwd, manifestPath }) {
163
162
  title: 'Get the upgrade guide',
164
163
  description:
165
164
  'Get what moving the app between two @sixbell-telco/sdk versions involves, from the installed SDK: the ng update migrations that would run (sdk-tools upgrade applies them), the steps no migration applies, and the changelog consumer-upgrade steps of every version in between. Use it before or after an upgrade; versions above the installed one are an error (upgrade first).',
166
- inputSchema: {
167
- from: z.string().min(1).describe('The version the app is on. Examples: "4.5.0", "3.x".'),
168
- to: z.string().min(1).describe('The version to move to, at most the installed one. Example: "4.6.0".'),
169
- },
165
+ inputSchema: inputSchema({
166
+ from: requiredString('The version the app is on. Examples: "4.5.0", "3.x".'),
167
+ to: requiredString('The version to move to, at most the installed one. Example: "4.6.0".'),
168
+ }),
170
169
  annotations: readOnly,
171
170
  },
172
- ({ from, to }) => answer(() => upgradeGuide({ cwd, manifestPath, from, to })),
171
+ ({ from, to }) => answer(async () => (await import('./upgrade-guide.mjs')).upgradeGuide({ cwd: app(), manifestPath, from, to })),
173
172
  );
174
173
 
175
174
  server.registerTool(
@@ -178,12 +177,12 @@ function createServer({ cwd, manifestPath }) {
178
177
  title: 'Get the kit glossary',
179
178
  description:
180
179
  'Get the kit glossary from the installed SDK: each term (surface, role, variant, slot, host, child, finding ...) with its definition, an example and the words not to use for it. Pass a term for one entry, or nothing for all of them. A rejected word (for example `modal`) returns the term to use instead.',
181
- inputSchema: { term: z.string().optional().describe('One term. Examples: "surface", "menu param". Leave empty for all terms.') },
180
+ inputSchema: inputSchema({ term: optionalString('One term. Examples: "surface", "menu param". Leave empty for all terms.') }),
182
181
  annotations: readOnly,
183
182
  },
184
183
  ({ term }) =>
185
184
  answer(() => {
186
- const { version, entries } = loadGlossary({ cwd, manifestPath });
185
+ const { version, entries } = loadGlossary({ cwd: app(), manifestPath });
187
186
  return term ? findTerm(entries, term) : { sdkVersion: version, terms: entries };
188
187
  }),
189
188
  );
@@ -199,7 +198,7 @@ function createServer({ cwd, manifestPath }) {
199
198
  (uri) => {
200
199
  let text;
201
200
  try {
202
- text = loadGlossary({ cwd, manifestPath }).text;
201
+ text = loadGlossary({ cwd: app(), manifestPath }).text;
203
202
  } catch (thrown) {
204
203
  text = thrown instanceof Error ? thrown.message : String(thrown);
205
204
  }
@@ -212,6 +211,12 @@ function createServer({ cwd, manifestPath }) {
212
211
  'sixbell-sdk://design',
213
212
  { title: 'DESIGN.md', description: "The app's DESIGN.md: the kit's styling, composition and accessibility rules.", mimeType: 'text/markdown' },
214
213
  (uri) => {
214
+ let cwd;
215
+ try {
216
+ cwd = app();
217
+ } catch (thrown) {
218
+ return { contents: [{ uri: uri.href, mimeType: 'text/markdown', text: thrown instanceof Error ? thrown.message : String(thrown) }] };
219
+ }
215
220
  const path = join(cwd, 'DESIGN.md');
216
221
  const text = existsSync(path)
217
222
  ? readFileSync(path, 'utf8')
@@ -238,12 +243,5 @@ function createServer({ cwd, manifestPath }) {
238
243
  */
239
244
  export async function serve(options) {
240
245
  console.log = console.info = console.debug = console.error;
241
- const server = createServer(options);
242
- const transport = new StdioServerTransport();
243
- const closed = new Promise((done) => {
244
- transport.onclose = () => done(undefined);
245
- process.stdin.once('end', () => done(undefined));
246
- });
247
- await server.connect(transport);
248
- await closed;
246
+ await createServer(options).serve(process.stdin, process.stdout);
249
247
  }