@wastech-mdlint/mcp-server 0.1.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.
@@ -0,0 +1,177 @@
1
+ import { customRuleEntrySchema, duplicateCustomIdMessage, findDuplicateCustomIds, formatLintResultText, lintContent, resolveCustomRule, ruleEntrySchema, ruleRegistry, RuleResolutionError, } from "@wastech-mdlint/core";
2
+ import { z } from "zod";
3
+ import { lintMessageSchema } from "../shared/lint-message-schema.js";
4
+ import { ToolInputError } from "../shared/tool-input-error.js";
5
+ import { errorResult, READ_ONLY_ANNOTATIONS, successResult, withErrorOutput, } from "../shared/tool-response.js";
6
+ // `lint` — lint ad-hoc Markdown text against an explicit set of rules. This tool never loads a
7
+ // project config (that is `lint-files`' job): the whole contract is "content + rules in, findings
8
+ // out", so the input carries the rules to run rather than resolving them from a config. Core still
9
+ // owns rule semantics, so file-resolving rules may inspect paths under the server cwd.
10
+ // A synthetic in-memory path for the single document. Ends in `.md` because some built-in rules
11
+ // accept `files`/`exclude` glob options (fileScopeShape) and match them against the document path;
12
+ // a `.md` suffix behaves least-surprisingly against a caller-supplied glob like `**/*.md`.
13
+ const AD_HOC_DOCUMENT_PATH = "content.md";
14
+ // Reuse core's already-validated rule entry schemas for each requested rule rather than a hand-rolled
15
+ // `{ rule, options }` pair. This is a deliberate small superset of the task's literal wording: it
16
+ // also carries `severity` (including `"off"`), and honoring the field the schema exposes is safer
17
+ // than silently ignoring it.
18
+ //
19
+ // Widened to a union so "executes declarative custom rules" holds for ad-hoc `lint`
20
+ // too. Custom-first, because the strict built-in branch would reject a custom entry's `id`/`target`
21
+ // keys. The second branch is `ruleEntrySchema` — the permissive one — deliberately NOT the config-only
22
+ // `ruleEntryUnionSchema`, whose standard branch refine-rejects the literal `"custom"`: the SDK
23
+ // `safeParseAsync`s this schema *before* the handler runs and turns a failure into an
24
+ // `InvalidParams` result carrying raw validation text and no `structuredContent`, so any shape
25
+ // rejected here can never carry the `{code,message,hint}` payload. A malformed
26
+ // `{ "rule": "custom" }` must therefore reach `handleLint`
27
+ // and be re-validated there (see `resolveCustomRequest`). Config load stays fail-closed on the same
28
+ // shape; only this wire schema is permissive.
29
+ const ruleRequestSchema = z.union([customRuleEntrySchema, ruleEntrySchema]);
30
+ const lintInputShape = {
31
+ content: z.string(),
32
+ rules: z.array(ruleRequestSchema),
33
+ };
34
+ const lintOutputShape = {
35
+ messages: z.array(lintMessageSchema),
36
+ errorCount: z.number().int(),
37
+ warningCount: z.number().int(),
38
+ };
39
+ // Wire clients validate `structuredContent` against `outputSchema` even on errors, so the error
40
+ // path needs schema-compatible zero values for lint's required success fields.
41
+ const EMPTY_LINT_OUTPUT = {
42
+ messages: [],
43
+ errorCount: 0,
44
+ warningCount: 0,
45
+ };
46
+ // `ruleRegistry.resolveRule` throws `RuleResolutionError`, whose `UNKNOWN_RULE`/`INVALID_OPTIONS`
47
+ // codes are a *different* enum than `ToolErrorCode`, so it needs the shared `ToolInputError`
48
+ // translation to keep its "did you mean" / bad-options text instead of degrading to a sanitized
49
+ // `INTERNAL_ERROR`.
50
+ function toToolInputError(error) {
51
+ if (error.code === "UNKNOWN_RULE") {
52
+ const hint = error.suggestion === undefined
53
+ ? undefined
54
+ : `Did you mean "${error.suggestion}"?`;
55
+ return new ToolInputError(error.message, hint);
56
+ }
57
+ // INVALID_OPTIONS: surface the failing option paths so the caller can fix the request.
58
+ const hint = error.issues
59
+ ?.map((issue) => `${issue.path.join(".")}: ${issue.message}`)
60
+ .join("; ");
61
+ return new ToolInputError(error.message, hint === "" ? undefined : hint);
62
+ }
63
+ // Re-validate a `rule: "custom"` request inside the handler. The wire schema's permissive branch lets
64
+ // a malformed custom entry through on purpose (see `ruleRequestSchema`), and `entry.rule === "custom"`
65
+ // does not narrow `RuleConfigEntry` away — its `rule` is an open `z.string()` — so this parses rather
66
+ // than casts. That also means `handleLint`, which tests call directly, never reaches
67
+ // `resolveCustomRule` with an absent `id` — the same crash the config boundary already guards.
68
+ function resolveCustomRequest(entry) {
69
+ const parsed = customRuleEntrySchema.safeParse(entry);
70
+ if (!parsed.success) {
71
+ const hint = parsed.error.issues
72
+ .map((issue) => `${issue.path.join(".")}: ${issue.message}`)
73
+ .join("; ");
74
+ throw new ToolInputError('A "custom" rule entry requires "id" and "options.assert".', hint === "" ? undefined : hint);
75
+ }
76
+ return resolveCustomRule(parsed.data, ruleRegistry);
77
+ }
78
+ // Resolve requested entries to runnable rules, mirroring lintFiles' resolve-then-filter of `"off"`
79
+ // (that helper isn't exported and is only ~6 lines — not worth a core export for one caller).
80
+ function resolveRequestedRules(entries) {
81
+ // Checked here as well as in the config loader because this tool resolves its rules from the
82
+ // request rather than from a config, so it never passes through that check. Two custom entries
83
+ // under one id both run and produce findings labelled identically — which on this host means a
84
+ // model reading them cannot attribute either. Refused before any rule resolves, since the whole
85
+ // request is unusable rather than one entry of it.
86
+ const collision = findDuplicateCustomIds(entries)[0];
87
+ if (collision !== undefined) {
88
+ throw new ToolInputError('A "custom" rule id must identify exactly one rule.', `rules[${collision.index}].id: ${duplicateCustomIdMessage({
89
+ id: collision.id,
90
+ siblingPath: `rules[${collision.firstIndex}]`,
91
+ })}`);
92
+ }
93
+ const resolved = [];
94
+ for (const entry of entries) {
95
+ let rule;
96
+ try {
97
+ // The `else` branch narrows to `RuleConfigEntry` (the literal-`"custom"` member drops out),
98
+ // keeping `entry.options` the `unknown` that per-rule validation expects.
99
+ rule =
100
+ entry.rule === "custom"
101
+ ? resolveCustomRequest(entry)
102
+ : ruleRegistry.resolveRule(entry.rule, entry.options);
103
+ }
104
+ catch (error) {
105
+ if (error instanceof RuleResolutionError) {
106
+ throw toToolInputError(error);
107
+ }
108
+ throw error;
109
+ }
110
+ if (entry.severity === "off") {
111
+ continue;
112
+ }
113
+ resolved.push({ rule, severityOverride: entry.severity });
114
+ }
115
+ return resolved;
116
+ }
117
+ export function handleLint(input) {
118
+ try {
119
+ // Rule *resolution* stays here — `resolveRequestedRules` owns translating a `RuleResolutionError`
120
+ // into this host's `{ code, message, hint }` contract — and every step after it is core's
121
+ // `lintContent`: parse, corpus of one, scope split, inline-disable, counts. Those steps used to
122
+ // be assembled in this function, which made this the one place `lintFiles`' step
123
+ // order existed twice; a step added there would silently not have reached this tool.
124
+ //
125
+ // `rootDir` is the server cwd, mirroring the fallback `resolveToolCwd` applies to the file-based
126
+ // tools. It is a bare `process.cwd()` call, not that helper: this tool takes no `cwd` input, so
127
+ // there is nothing caller-supplied to validate. Passing a real directory rather than a bespoke
128
+ // corpus-only mode is deliberate — REF-001/003 resolve `rootDir` into `existsSync` for targets
129
+ // outside the corpus, so on-disk targets resolve exactly as they do under `lint-files`, and core
130
+ // stays the single owner of REF/SEC resolution semantics.
131
+ const result = lintContent({
132
+ path: AD_HOC_DOCUMENT_PATH,
133
+ content: input.content,
134
+ rules: resolveRequestedRules(input.rules),
135
+ rootDir: process.cwd(),
136
+ });
137
+ return successResult({
138
+ // Core's own text formatter, so `lint` and `lint-files` render byte-for-byte consistently.
139
+ summary: formatLintResultText(result),
140
+ // Deliberately narrower than `LintResult`: an ad-hoc document is not a corpus, so there is no
141
+ // `files` list to report. The divergence from `lint-files` is deliberate, and pinned by
142
+ // `test/lint.test.ts` so it cannot drift into an accident.
143
+ structured: {
144
+ messages: result.messages,
145
+ errorCount: result.errorCount,
146
+ warningCount: result.warningCount,
147
+ },
148
+ });
149
+ }
150
+ catch (error) {
151
+ // `process.cwd()` is the right base here even though this tool takes no `cwd` input: it is the
152
+ // same root the corpus-of-one above lints against (`rootDir`), so a file-resolving rule that
153
+ // fails on an errno names its path relative to the directory the rule actually probed.
154
+ return errorResult(error, {
155
+ successFields: EMPTY_LINT_OUTPUT,
156
+ cwd: process.cwd(),
157
+ });
158
+ }
159
+ }
160
+ export function registerLintTool(server) {
161
+ server.registerTool("lint", {
162
+ title: "Lint Markdown content",
163
+ // This text ships on every `listTools` and is generated into the README inventory, so it stays
164
+ // terse. It must avoid `|` (would be escaped into the table) and `**` (Prettier destructively
165
+ // rewrites a glob-bearing code span nested in bold).
166
+ description: "Lint ad-hoc Markdown content against an explicit set of rules. Does not load project config; " +
167
+ "file-resolving rules such as REF-001/REF-003, SEC-003 and STR-001 may probe or read paths " +
168
+ "inside the server's working directory; an absolute path or a `..`-escaping relative path is " +
169
+ "rejected rather than followed. Each entry is either a built-in rule id or a declarative " +
170
+ '`custom` rule (`rule: "custom"` plus `id` and `options.assert`); code plugins are never ' +
171
+ "loaded. Rules see one synthetic document path, `content.md`, so an `options.files` or " +
172
+ "`options.exclude` glob that does not match that path selects nothing.",
173
+ inputSchema: lintInputShape,
174
+ outputSchema: withErrorOutput(lintOutputShape),
175
+ annotations: READ_ONLY_ANNOTATIONS,
176
+ }, (input) => handleLint(input));
177
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@wastech-mdlint/mcp-server",
3
+ "version": "0.1.0",
4
+ "description": "Model Context Protocol server for wastech-mdlint: a stdio-only, read-only adapter over core.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/VladimirMakarevich/wastech-mdlint.git",
9
+ "directory": "packages/mcp-server"
10
+ },
11
+ "type": "module",
12
+ "bin": {
13
+ "wastech-mdlint-mcp": "./dist/index.js"
14
+ },
15
+ "engines": {
16
+ "node": ">=24.17.0"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "LICENSE",
21
+ "README.md"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsc -b",
25
+ "test": "vitest run"
26
+ },
27
+ "dependencies": {
28
+ "@modelcontextprotocol/sdk": "^1.29.0",
29
+ "@wastech-mdlint/core": "0.1.0",
30
+ "zod": "^4"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "provenance": true
35
+ }
36
+ }