@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vladimir Makarevich
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # @wastech-mdlint/mcp-server
2
+
3
+ A [Model Context Protocol](https://modelcontextprotocol.io) server that gives an agent read-only access to a repository's Markdown context: lint findings, the context graph, reachability slices, change impact, and a compiled skill.
4
+
5
+ **stdio only, read-only, six tools.** No HTTP or SSE transport, no mutating tools, no code-plugin execution. Every tool runs through [`@wastech-mdlint/core`](https://github.com/VladimirMakarevich/wastech-mdlint/blob/main/packages/core/README.md), the same pipeline the CLI uses — this package is the host adapter around it: tool registration, input validation, structured output, and error wrapping.
6
+
7
+ ## Run it
8
+
9
+ ```bash
10
+ npx @wastech-mdlint/mcp-server # run directly, no install
11
+ npm i -D @wastech-mdlint/mcp-server # or install the wastech-mdlint-mcp bin
12
+ ```
13
+
14
+ Add it to any stdio-based MCP host (Claude Code's `.mcp.json`, Claude Desktop's `claude_desktop_config.json`, and so on):
15
+
16
+ ```jsonc
17
+ {
18
+ "mcpServers": {
19
+ "wastech-mdlint": {
20
+ "command": "npx",
21
+ "args": ["-y", "@wastech-mdlint/mcp-server"],
22
+ },
23
+ },
24
+ }
25
+ ```
26
+
27
+ Node.js `>=24.17.0`. Readiness is announced on stderr; stdout carries only the protocol, so nothing the server logs can corrupt a JSON-RPC frame.
28
+
29
+ ## The six tools
30
+
31
+ | Tool | What it does |
32
+ | --- | --- |
33
+ | `lint` | Lint ad-hoc Markdown content against an explicit rule list. Does not load project config. |
34
+ | `lint-files` | Lint the project's Markdown files using the resolved config, or the zero-config default. |
35
+ | `context-graph` | Build the project's context graph — nodes, edges, cycles, or a summary document. |
36
+ | `context-slice` | The files reachable within `depth` hops of a query resolved by exact match. |
37
+ | `impact-analysis` | The blast radius of changing one file: direct and transitive dependents. |
38
+ | `compile-context` | Compile the project skill (`SKILL.md`) from `config.compile`. |
39
+
40
+ All six carry a `readOnlyHint` annotation. Five return `structuredContent` alongside an `outputSchema`; `compile-context` returns two plain-text content blocks instead.
41
+
42
+ The five file-based tools accept a `cwd`. A `cwd` that does not exist, or that names a file rather than a directory, is rejected with an actionable error rather than answered with an empty result — an empty corpus is indistinguishable from a clean repository, so a plausible-looking success would answer a different question than the one asked. Omit it to analyze the server process's own working directory.
43
+
44
+ ## Errors
45
+
46
+ Tool failures use a structured `{ code, message, hint }` contract, carried in `structuredContent` with `message` and `hint` also rendered into the text block, so a host that shows only text still sees the actionable half.
47
+
48
+ One limit is deliberate: that contract covers failures the tool itself detects. An argument shape the tool's advertised `inputSchema` rejects outright is refused by the protocol layer before the tool runs, and comes back as a validation error with no `structuredContent` at all.
49
+
50
+ ## Documentation
51
+
52
+ - [MCP server guide](https://github.com/VladimirMakarevich/wastech-mdlint/blob/main/docs/guide/mcp-server.md) — every tool's arguments, the full error contract, and host wiring
53
+ - [Project README](https://github.com/VladimirMakarevich/wastech-mdlint#readme) · [Configuration](https://github.com/VladimirMakarevich/wastech-mdlint/blob/main/docs/guide/configuration.md) · [Output & exit codes](https://github.com/VladimirMakarevich/wastech-mdlint/blob/main/docs/guide/output.md)
54
+
55
+ ## License
56
+
57
+ MIT — see [LICENSE](./LICENSE).
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ export declare function createServer(): Promise<McpServer>;
4
+ export declare function startServer(): Promise<void>;
package/dist/index.js ADDED
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { registerTools } from "./tools/index.js";
9
+ // The server shell. Tools are registered through the modular seam in tools/index.ts — one
10
+ // module per tool — so this file stays the transport/lifecycle owner, not a tool mega-file.
11
+ // Every read-only tool is appended to that seam rather than registered here.
12
+ // The invariants this shell locks in: transport is stdio-only and the server never loads
13
+ // code-plugins.
14
+ // Resolves relative to the compiled module (dist/index.js), one level under dist/, so the read
15
+ // keeps finding packages/mcp-server/package.json regardless of the caller's cwd — the same
16
+ // approach the CLI uses for its version lookup.
17
+ async function readPackageVersion() {
18
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
19
+ const packageJsonPath = path.resolve(moduleDir, "../package.json");
20
+ const packageJsonText = await readFile(packageJsonPath, "utf8");
21
+ const packageJson = JSON.parse(packageJsonText);
22
+ return packageJson.version ?? "0.0.0";
23
+ }
24
+ export async function createServer() {
25
+ const server = new McpServer({
26
+ name: "wastech-mdlint-mcp",
27
+ version: await readPackageVersion(),
28
+ });
29
+ registerTools(server);
30
+ return server;
31
+ }
32
+ export async function startServer() {
33
+ const server = await createServer();
34
+ const transport = new StdioServerTransport();
35
+ await server.connect(transport);
36
+ // Readiness is announced on stderr, never stdout: stdout is the MCP JSON-RPC channel, so any
37
+ // stray write there would corrupt the protocol stream for the connected host.
38
+ process.stderr.write("wastech-mdlint-mcp: ready (stdio)\n");
39
+ }
40
+ const invokedPath = process.argv[1];
41
+ const modulePath = fileURLToPath(import.meta.url);
42
+ // Same symlink defect as the CLI entrypoint (packages/cli/src/index.ts) — see its comment for the
43
+ // full explanation. process.argv[1] keeps the node_modules/.bin symlink path while import.meta.url
44
+ // resolves to the realpath, so dereferencing before comparing is required for the guard to ever
45
+ // match a symlinked invocation.
46
+ function realOrSelf(candidate) {
47
+ try {
48
+ return realpathSync(candidate);
49
+ }
50
+ catch {
51
+ return candidate;
52
+ }
53
+ }
54
+ // Only auto-start when run as the real bin; importing this module (e.g. from a smoke test) must
55
+ // not spin up a transport that seizes stdio, mirroring the CLI entrypoint guard. Both sides are
56
+ // dereferenced (not just invokedPath): import.meta.url is only a realpath under Node's default
57
+ // module resolution — under --preserve-symlinks/--preserve-symlinks-main it stays the symlink path
58
+ // too, and an unresolved comparison there would reject a legitimate bin invocation in that mode.
59
+ if (invokedPath !== undefined &&
60
+ realOrSelf(path.resolve(invokedPath)) === realOrSelf(modulePath)) {
61
+ startServer().catch((error) => {
62
+ const message = error instanceof Error ? error.message : String(error);
63
+ process.stderr.write(`wastech-mdlint-mcp: failed to start: ${message}\n`);
64
+ process.exitCode = 1;
65
+ });
66
+ }
@@ -0,0 +1,16 @@
1
+ import { z } from "zod";
2
+ export declare const lintMessageSchema: z.ZodObject<{
3
+ ruleId: z.ZodString;
4
+ severity: z.ZodEnum<{
5
+ error: "error";
6
+ warning: "warning";
7
+ }>;
8
+ message: z.ZodString;
9
+ filePath: z.ZodString;
10
+ line: z.ZodNumber;
11
+ column: z.ZodOptional<z.ZodNumber>;
12
+ endLine: z.ZodOptional<z.ZodNumber>;
13
+ fixable: z.ZodOptional<z.ZodBoolean>;
14
+ data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
15
+ helpUri: z.ZodOptional<z.ZodString>;
16
+ }, z.core.$strip>;
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ // Hand-maintained Zod mirror of core's `LintMessage` TS type (engine/types.ts). v2 has no codegen,
3
+ // so this shape must move in lockstep with that type: a field added, renamed, or made
4
+ // required/optional there has to be reflected here or the tools' structured output silently drifts
5
+ // from the finding contract core promises. Shared by both lint tools' `outputSchema` so there is one mirror,
6
+ // not two.
7
+ //
8
+ // The key set has not changed; `helpUri`'s *value* has. It used to cross the wire as a bare
9
+ // rule id (identical to `ruleId`) and is now the rule's documentation URL, so a caller that read it as
10
+ // an id gets a link instead. Wire-visible but safe to take now: nothing is published (every package is
11
+ // `version: "0.0.0"`), and `ruleId` was always the field for the id.
12
+ export const lintMessageSchema = z.object({
13
+ ruleId: z.string(),
14
+ severity: z.enum(["error", "warning"]),
15
+ message: z.string(),
16
+ filePath: z.string(),
17
+ line: z.number(),
18
+ column: z.number().optional(),
19
+ endLine: z.number().optional(),
20
+ fixable: z.boolean().optional(),
21
+ data: z.record(z.string(), z.unknown()).optional(),
22
+ helpUri: z.string().optional(),
23
+ });
@@ -0,0 +1,26 @@
1
+ import { type StructuredErrorInfo } from "@wastech-mdlint/core";
2
+ /**
3
+ * The `OPERATIONAL_ERROR` payload for an errno that names a path inside `cwd`, or `undefined` for
4
+ * anything the caller should keep treating as a sanitized `INTERNAL_ERROR`.
5
+ *
6
+ * **Both fields are required.** An errno with no `path` (`ENOSPC: no space left on device, write`)
7
+ * has nothing to name, and its own message is the only diagnostic there is — but that message is
8
+ * exactly the unvetted text `INTERNAL_ERROR` exists to withhold, so it falls through rather than
9
+ * being surfaced. The CLI can afford the opposite choice because its output is a terminal, not a
10
+ * machine contract.
11
+ *
12
+ * **Containment is stricter than the CLI's.** A `../` chain or (across Windows drives) an outright
13
+ * absolute path is refused here instead of rendered, because "no payload names a host path the
14
+ * caller did not itself *supply*" is the property MCP's sanitization exists for, and it outweighs
15
+ * naming a file outside the analyzed root. Two caller-supplied paths do come back: the `cwd`, in the
16
+ * `INVALID_INPUT` message (`tool-context.ts`), where the value is the caller's own and is the broken
17
+ * thing being reported; and a `configPath`, which core renders relative to `cwd` with no containment
18
+ * check of its own. What this function must not do is add a *third* — a path the run discovered
19
+ * rather than the caller named. The CLI keeps the `../` form on purpose (see
20
+ * `operational-errors.ts`); the two hosts differ here by decision, which is why this is not that
21
+ * function.
22
+ *
23
+ * **No `hint`.** An errno-specific remedy would be guesswork (`EACCES` on a config is a permissions
24
+ * fix; `EISDIR` is a wrong-path fix), and the message already carries the whole actionable content.
25
+ */
26
+ export declare function toOperationalErrorInfo(error: unknown, cwd: string): StructuredErrorInfo | undefined;
@@ -0,0 +1,72 @@
1
+ import path from "node:path";
2
+ import { normalizeRelativePath, } from "@wastech-mdlint/core";
3
+ // Classify a raw Node errno into the shared `OPERATIONAL_ERROR` payload. The code lives
4
+ // in core's closed taxonomy; the mapping lives here because deciding that a throwable is an
5
+ // environment failure rather than an internal one is a host-boundary judgement — the same split
6
+ // `INVALID_INPUT`/`ToolInputError` already uses. Core's `isStructuredError` is deliberately NOT
7
+ // widened to duck-type errnos (its comment says why), so this is the only door such an error has.
8
+ //
9
+ // Deliberately a third host-local copy of the two-field errno guard rather than a promoted core
10
+ // export, matching the argument the CLI's copy already makes in place: core's feeds a structured
11
+ // `AtomicWriteResult.code`, the CLI's renders stderr, and this one produces a taxonomy payload.
12
+ // Three unrelated consumers of the same Node detail, six lines each.
13
+ function errnoCode(error) {
14
+ if (error instanceof Error &&
15
+ typeof error.code === "string") {
16
+ return error.code;
17
+ }
18
+ return undefined;
19
+ }
20
+ function errnoPath(error) {
21
+ if (error instanceof Error &&
22
+ typeof error.path === "string") {
23
+ return error.path;
24
+ }
25
+ return undefined;
26
+ }
27
+ /**
28
+ * The `OPERATIONAL_ERROR` payload for an errno that names a path inside `cwd`, or `undefined` for
29
+ * anything the caller should keep treating as a sanitized `INTERNAL_ERROR`.
30
+ *
31
+ * **Both fields are required.** An errno with no `path` (`ENOSPC: no space left on device, write`)
32
+ * has nothing to name, and its own message is the only diagnostic there is — but that message is
33
+ * exactly the unvetted text `INTERNAL_ERROR` exists to withhold, so it falls through rather than
34
+ * being surfaced. The CLI can afford the opposite choice because its output is a terminal, not a
35
+ * machine contract.
36
+ *
37
+ * **Containment is stricter than the CLI's.** A `../` chain or (across Windows drives) an outright
38
+ * absolute path is refused here instead of rendered, because "no payload names a host path the
39
+ * caller did not itself *supply*" is the property MCP's sanitization exists for, and it outweighs
40
+ * naming a file outside the analyzed root. Two caller-supplied paths do come back: the `cwd`, in the
41
+ * `INVALID_INPUT` message (`tool-context.ts`), where the value is the caller's own and is the broken
42
+ * thing being reported; and a `configPath`, which core renders relative to `cwd` with no containment
43
+ * check of its own. What this function must not do is add a *third* — a path the run discovered
44
+ * rather than the caller named. The CLI keeps the `../` form on purpose (see
45
+ * `operational-errors.ts`); the two hosts differ here by decision, which is why this is not that
46
+ * function.
47
+ *
48
+ * **No `hint`.** An errno-specific remedy would be guesswork (`EACCES` on a config is a permissions
49
+ * fix; `EISDIR` is a wrong-path fix), and the message already carries the whole actionable content.
50
+ */
51
+ export function toOperationalErrorInfo(error, cwd) {
52
+ const code = errnoCode(error);
53
+ const failingPath = errnoPath(error);
54
+ if (code === undefined || failingPath === undefined) {
55
+ return undefined;
56
+ }
57
+ const relative = path.relative(cwd, failingPath);
58
+ // Compared by first *segment* rather than by string prefix, so `..\out` and `../out` both match
59
+ // while a sibling directory named `..foo` does not. `path.relative` answers an already-absolute
60
+ // path when no relative form exists at all (two Windows drives), which the first test catches.
61
+ if (path.isAbsolute(relative) || relative.split(path.sep)[0] === "..") {
62
+ return undefined;
63
+ }
64
+ // Byte-identical to the CLI's stderr line (`formatOperationalError` behind its `Operational error:`
65
+ // prefix), so "both hosts name the errno and the path" is literally true and a user comparing the
66
+ // two surfaces sees one sentence. `""` — the failing path being `cwd` itself — renders as `.`.
67
+ const rendered = normalizeRelativePath(relative);
68
+ return {
69
+ code: "OPERATIONAL_ERROR",
70
+ message: `Operational error: ${code} on ${rendered === "" ? "." : rendered}`,
71
+ };
72
+ }
@@ -0,0 +1,40 @@
1
+ import { type GraphContext, type LoadedConfiguration } from "@wastech-mdlint/core";
2
+ export type ToolFileInput = {
3
+ cwd?: string;
4
+ configPath?: string;
5
+ };
6
+ /**
7
+ * The resolved `cwd` a call will use, computed without touching the filesystem.
8
+ *
9
+ * `cwd ?? process.cwd()` is a deliberate departure from the CLI's layering, where commander supplies
10
+ * the default; MCP tools have no argument-parsing layer. It lives here alone so the callers below and
11
+ * the tool modules that need the value read it back rather than recomputing it — four copies of the
12
+ * same line was how `resolveToolCwd`'s guard came to be missed at three of them.
13
+ *
14
+ * Split out of `resolveToolCwd` so a tool's `catch` block can name the base its failure happened
15
+ * under — `errorResult` renders an errno's path relative to it — even when the failure is the
16
+ * `stat` inside `resolveToolCwd` itself, and so the requirement that `cwd ?? process.cwd()`
17
+ * appears in exactly one place — keeps holding. Deliberately not async and deliberately not
18
+ * validating: a `catch` handler cannot afford a second throw.
19
+ */
20
+ export declare function toolCwdBase(input: ToolFileInput): string;
21
+ /**
22
+ * Resolve a tool's `cwd` and reject it if it is not a usable directory.
23
+ *
24
+ * Core deliberately does not do this: `loadDocuments` answers a root that does not stat as a
25
+ * directory with a silent empty map, pinned as intentional by core's own test and relied on by other
26
+ * callers. Left unguarded that reads to a client as `No problems found.` / an empty graph / `No match
27
+ * for query` — a plausible answer to a different question, which is the CLI's own stated rationale
28
+ * for its identical check ("indistinguishable from a clean repository").
29
+ *
30
+ * Runs on every call, including when `cwd` is omitted: one `stat` against a whole corpus walk is not
31
+ * worth an `input.cwd !== undefined` branch, and a server whose own working directory has gone away
32
+ * is a real failure worth naming.
33
+ */
34
+ export declare function resolveToolCwd(input: ToolFileInput): Promise<string>;
35
+ export type ResolvedToolConfiguration = LoadedConfiguration & {
36
+ cwd: string;
37
+ };
38
+ export declare function resolveToolConfiguration(input: ToolFileInput): Promise<ResolvedToolConfiguration>;
39
+ export type ResolvedToolContext = ResolvedToolConfiguration & GraphContext;
40
+ export declare function resolveToolContext(input: ToolFileInput): Promise<ResolvedToolContext>;
@@ -0,0 +1,103 @@
1
+ import { stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { loadConfiguration, loadContext, } from "@wastech-mdlint/core";
4
+ import { ToolInputError } from "./tool-input-error.js";
5
+ // `path.sep` -> `/` for a message only; the returned value stays platform-native so callers keep
6
+ // handing core a real path. One line, local: core's `normalizeRelativePath` also strips a leading
7
+ // `./`, which is meaningless for an absolute path and would misdescribe what was stat'ed.
8
+ function toPosixPath(value) {
9
+ return value.split(path.sep).join("/");
10
+ }
11
+ /**
12
+ * The resolved `cwd` a call will use, computed without touching the filesystem.
13
+ *
14
+ * `cwd ?? process.cwd()` is a deliberate departure from the CLI's layering, where commander supplies
15
+ * the default; MCP tools have no argument-parsing layer. It lives here alone so the callers below and
16
+ * the tool modules that need the value read it back rather than recomputing it — four copies of the
17
+ * same line was how `resolveToolCwd`'s guard came to be missed at three of them.
18
+ *
19
+ * Split out of `resolveToolCwd` so a tool's `catch` block can name the base its failure happened
20
+ * under — `errorResult` renders an errno's path relative to it — even when the failure is the
21
+ * `stat` inside `resolveToolCwd` itself, and so the requirement that `cwd ?? process.cwd()`
22
+ * appears in exactly one place — keeps holding. Deliberately not async and deliberately not
23
+ * validating: a `catch` handler cannot afford a second throw.
24
+ */
25
+ export function toolCwdBase(input) {
26
+ return path.resolve(input.cwd ?? process.cwd());
27
+ }
28
+ /**
29
+ * Resolve a tool's `cwd` and reject it if it is not a usable directory.
30
+ *
31
+ * Core deliberately does not do this: `loadDocuments` answers a root that does not stat as a
32
+ * directory with a silent empty map, pinned as intentional by core's own test and relied on by other
33
+ * callers. Left unguarded that reads to a client as `No problems found.` / an empty graph / `No match
34
+ * for query` — a plausible answer to a different question, which is the CLI's own stated rationale
35
+ * for its identical check ("indistinguishable from a clean repository").
36
+ *
37
+ * Runs on every call, including when `cwd` is omitted: one `stat` against a whole corpus walk is not
38
+ * worth an `input.cwd !== undefined` branch, and a server whose own working directory has gone away
39
+ * is a real failure worth naming.
40
+ */
41
+ export async function resolveToolCwd(input) {
42
+ // Always present: the stdio error contract carries `hint` as the actionable half of `{ code,
43
+ // message, hint }`, and there is exactly one useful remedy here.
44
+ const hint = 'Pass an absolute path to an existing directory, or omit "cwd" to analyze the server\'s working directory.';
45
+ // Rejected before `path.resolve`, because it cannot be caught after: `path.resolve("")` returns
46
+ // `process.cwd()`, so an explicit empty (or blank) `cwd` would pass every check below and silently
47
+ // analyze the server's own working directory — a plausible answer to a different question, which is
48
+ // the exact failure this guard exists to name. Not expressed as `.min(1)` on the tools'
49
+ // `inputSchema`s: a schema rejection is refused before the handler runs, arriving as a bare
50
+ // `InvalidParams` with no `structuredContent` and no `hint`.
51
+ if (input.cwd !== undefined && input.cwd.trim() === "") {
52
+ throw new ToolInputError("cwd must not be empty", hint);
53
+ }
54
+ const resolved = toolCwdBase(input);
55
+ // The message names the RESOLVED absolute path, unlike the CLI's repo-relative rendering. The CLI
56
+ // has a known-good cwd to anchor against; here the cwd *is* the anchor and it is the broken thing,
57
+ // so a relative form would have nothing to mean. The value is derived from caller input and is
58
+ // exactly what was stat'ed, so it exposes no unrelated host state. Rendered with `/` separators
59
+ // even on Windows: absolute-versus-relative is the deliberate part, the separator is not, and every
60
+ // other user-visible path in the product is POSIX-normalized.
61
+ const shown = toPosixPath(resolved);
62
+ const stats = await stat(resolved).catch((error) => {
63
+ // Mirrors the CLI's `resolveDirectoryArgument`: only these two errnos mean "no usable directory
64
+ // here". Anything else (EACCES, ELOOP, …) is a *different* operational failure and must not be
65
+ // misreported as bad input, so it rethrows — and it reaches `errorResult`'s errno
66
+ // classifier, which answers `OPERATIONAL_ERROR` naming the errno (or a sanitized INTERNAL_ERROR
67
+ // when the errno names no path) instead of the flat INTERNAL_ERROR it used to get.
68
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
69
+ if (code === "ENOENT") {
70
+ throw new ToolInputError(`cwd does not exist: ${shown}`, hint);
71
+ }
72
+ if (code === "ENOTDIR") {
73
+ throw new ToolInputError(`cwd is not a directory: ${shown}`, hint);
74
+ }
75
+ throw error;
76
+ });
77
+ if (!stats.isDirectory()) {
78
+ throw new ToolInputError(`cwd is not a directory: ${shown}`, hint);
79
+ }
80
+ return resolved;
81
+ }
82
+ export async function resolveToolConfiguration(input) {
83
+ // Before `loadConfiguration`, not after: a bad `cwd` is the more fundamental of the two failures,
84
+ // and checking it second would report `CONFIG_NOT_FOUND` for a `configPath` under a root that does
85
+ // not exist — naming the wrong cause.
86
+ const cwd = await resolveToolCwd(input);
87
+ const loaded = await loadConfiguration({
88
+ cwd,
89
+ explicitConfigPath: input.configPath,
90
+ });
91
+ return { ...loaded, cwd };
92
+ }
93
+ export async function resolveToolContext(input) {
94
+ const loaded = await resolveToolConfiguration(input);
95
+ const graphContext = await loadContext({
96
+ cwd: loaded.cwd,
97
+ config: loaded.config,
98
+ settings: loaded.settings,
99
+ });
100
+ // Neither function catches: errors now carry `code`/`hint` and propagate to the caller, which
101
+ // recodes them per its own call-site semantics (see tool-response.ts and the per-tool modules).
102
+ return { ...loaded, ...graphContext };
103
+ }
@@ -0,0 +1,6 @@
1
+ import type { ToolErrorCode } from "@wastech-mdlint/core";
2
+ export declare class ToolInputError extends Error {
3
+ readonly code: ToolErrorCode;
4
+ readonly hint?: string;
5
+ constructor(message: string, hint?: string);
6
+ }
@@ -0,0 +1,20 @@
1
+ // Error wrapping lives on the MCP boundary (architecture split: "error wrapping" is a host concern),
2
+ // so this class translates a throwable that carries no `ToolErrorCode` into one `errorResult` will
3
+ // pass through verbatim. Without it, `isStructuredError`'s allowlist rejects the throwable and it
4
+ // degrades to a sanitized `INTERNAL_ERROR`, losing exactly the actionable text the error contract exists to preserve
5
+ // — the "did you mean" suggestion behind `lint`'s `RuleResolutionError`, or the offending path behind
6
+ // a bad tool `cwd`.
7
+ //
8
+ // Shared *within mcp-server* (it started local to `tools/lint.ts` when there was one call site, and
9
+ // `shared/tool-context.ts` is the second). Still deliberately not promoted to core: the
10
+ // codes it produces are host-boundary input judgements, and core's own errors already carry their own
11
+ // taxonomy codes.
12
+ export class ToolInputError extends Error {
13
+ code = "INVALID_INPUT";
14
+ hint;
15
+ constructor(message, hint) {
16
+ super(message);
17
+ this.name = "ToolInputError";
18
+ this.hint = hint;
19
+ }
20
+ }
@@ -0,0 +1,12 @@
1
+ import type { CallToolResult, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
2
+ import { z } from "zod";
3
+ export declare const READ_ONLY_ANNOTATIONS: ToolAnnotations;
4
+ export declare function successResult(params: {
5
+ summary: string;
6
+ structured: Record<string, unknown>;
7
+ }): CallToolResult;
8
+ export declare function errorResult(error: unknown, options?: {
9
+ successFields?: Readonly<Record<string, unknown>>;
10
+ cwd?: string;
11
+ }): CallToolResult;
12
+ export declare function withErrorOutput(success: Readonly<Record<string, z.ZodTypeAny>>): Record<string, z.ZodTypeAny>;
@@ -0,0 +1,98 @@
1
+ import { isStructuredError, TOOL_ERROR_CODES, } from "@wastech-mdlint/core";
2
+ import { z } from "zod";
3
+ import { toOperationalErrorInfo } from "./operational-error.js";
4
+ // Output/error/annotation conventions as reusable wrappers so every tool
5
+ // renders the same success/error shape without re-deriving it.
6
+ // The annotation every tool carries. openWorldHint/idempotentHint are intentionally omitted — they
7
+ // are not part of the decided read-only contract, and adding them would advertise hints the shipped
8
+ // tools never agreed to.
9
+ export const READ_ONLY_ANNOTATIONS = { readOnlyHint: true };
10
+ // Success: a machine-readable structuredContent (validated against the tool's own outputSchema by
11
+ // the SDK) plus a human-readable text summary.
12
+ export function successResult(params) {
13
+ return {
14
+ content: [{ type: "text", text: params.summary }],
15
+ structuredContent: params.structured,
16
+ };
17
+ }
18
+ // Fixed, source-independent text for the INTERNAL_ERROR catch-all. A non-taxonomy throwable is
19
+ // unexpected, so its raw message must never reach the client: `error.message`/`String(error)` can
20
+ // carry absolute paths, stack fragments, or other internal detail (the error contract requires
21
+ // INTERNAL_ERROR be sanitized). Structured errors keep their own vetted messages; only this
22
+ // fallthrough is redacted.
23
+ const INTERNAL_ERROR_MESSAGE = "An unexpected internal error occurred.";
24
+ /**
25
+ * The text block a host renders and a model reads. It carries the `hint` too: the
26
+ * structured payload had the actionable sentence and the text did not, so a host that renders only
27
+ * `content[].text` — the common case — saw `Unknown rule "SIZE-002".` with the did-you-mean dropped,
28
+ * while the CLI prints both for the same typo.
29
+ *
30
+ * The `includes` test is not defensive noise, it is the whole reason this is a function. Some core
31
+ * errors already interpolate their hint INTO the message — `CompileConfigMissingError` and
32
+ * `ImpactAnalysisError` build theirs from it, and a `CONFIG_INVALID` `ConfigError`'s hint is the
33
+ * first of the issue lines its message lists — so a blind concatenation would print those sentences
34
+ * twice. Others do not (`CONFIG_NOT_FOUND`, `ToolInputError`), which is why the choice is per-error
35
+ * rather than per-class. Doing it here rather than at the one offending call site is what makes a
36
+ * newly added error path inherit the behavior.
37
+ */
38
+ function renderErrorText(structured) {
39
+ if (structured.hint === undefined ||
40
+ structured.message.includes(structured.hint)) {
41
+ return structured.message;
42
+ }
43
+ return `${structured.message} ${structured.hint}`;
44
+ }
45
+ // The error contract { code, message, hint }, carried in `structuredContent` as the public
46
+ // machine result: every error carries a code alongside structured output. Three-way classification, in
47
+ // order: a structured error from core (or `ToolInputError`) passes through verbatim; a raw errno
48
+ // naming a path inside `options.cwd` becomes an OPERATIONAL_ERROR; everything else is
49
+ // wrapped as a sanitized INTERNAL_ERROR. The stack is never included, so the human-readable
50
+ // `content` message and the structured payload only ever expose vetted text.
51
+ //
52
+ // `cwd` is optional because the classifier needs a base to render the failing path against and
53
+ // cannot invent one — without it the errno branch is skipped and the old INTERNAL_ERROR behavior
54
+ // stands, which is the safe direction.
55
+ //
56
+ // For this to round-trip over the wire on the five tools that declare an `outputSchema`, each such
57
+ // error payload may need schema-compatible placeholder success fields attached to it: a
58
+ // spec-compliant client validates any present `structuredContent` against the advertised schema,
59
+ // even on `isError` results. `compile-context` has no `outputSchema`, so it passes no placeholders.
60
+ // An options object rather than positional parameters so that tool — which supplies a `cwd` and no
61
+ // placeholders — does not have to pass a mid-list `undefined`.
62
+ export function errorResult(error, options = {}) {
63
+ const structured = isStructuredError(error)
64
+ ? { code: error.code, message: error.message, hint: error.hint }
65
+ : ((options.cwd === undefined
66
+ ? undefined
67
+ : toOperationalErrorInfo(error, options.cwd)) ?? {
68
+ code: "INTERNAL_ERROR",
69
+ message: INTERNAL_ERROR_MESSAGE,
70
+ });
71
+ return {
72
+ isError: true,
73
+ content: [{ type: "text", text: renderErrorText(structured) }],
74
+ // Spread unconditionally, including when there are no placeholders: `structuredContent` is typed
75
+ // as an index-signature record, and a named interface does not satisfy one without being widened
76
+ // into a fresh object literal. Spreading `undefined` is a no-op, so this is also the shorter form.
77
+ structuredContent: { ...options.successFields, ...structured },
78
+ };
79
+ }
80
+ // The error object folded into every schema-carrying tool's advertised `outputSchema` so an
81
+ // `errorResult` payload validates as structured output. `code` is constrained to the closed
82
+ // `TOOL_ERROR_CODES` taxonomy, not a bare string, so the advertised schema still documents the
83
+ // exact recoverable codes. Fields stay optional because the success schema remains the primary
84
+ // contract and only some results carry error metadata.
85
+ const ERROR_OUTPUT_SHAPE = {
86
+ code: z.enum(TOOL_ERROR_CODES).optional(),
87
+ message: z.string().optional(),
88
+ hint: z.string().optional(),
89
+ };
90
+ // Extend a success output shape with the optional error fields WITHOUT weakening the success
91
+ // contract. The pinned MCP SDK (1.29) validates any present `structuredContent` against the
92
+ // advertised schema even on errors, but it only advertises object schemas — a Zod union / `oneOf`
93
+ // is silently dropped. So the safe expressible shape is "success schema plus optional error
94
+ // metadata", and each tool's error path supplies schema-compatible placeholder success fields via
95
+ // `errorResult(..., successFields)`.
96
+ export function withErrorOutput(success) {
97
+ return { ...success, ...ERROR_OUTPUT_SHAPE };
98
+ }
@@ -0,0 +1 @@
1
+ export declare function generateToolInventory(): Promise<string>;
@@ -0,0 +1,46 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
3
+ import { createServer } from "./index.js";
4
+ // Renders the README's MCP tool inventory from the *live* registered tools rather than
5
+ // a hand-maintained name list. `tools/index.ts` deliberately keeps its registrars function-only so
6
+ // no second source of truth can drift ("5 vs 6 tools"); introspecting a connected client — the same
7
+ // `createServer()` + `InMemoryTransport` + `listTools()` technique `smoke.test.ts` uses — is the
8
+ // only generic, non-private-field way to enumerate what is actually advertised.
9
+ // Guard the table's Markdown against free-text descriptions: a `|` would split a cell and a newline
10
+ // would break the row. None of the six current descriptions contain either, but the table is
11
+ // machine-generated from prose a future tool author could grow one into — escaping here closes that
12
+ // off permanently rather than leaving a latent doc-corruption risk.
13
+ function escapeCell(text) {
14
+ return text.replace(/\r?\n/g, " ").replace(/\|/g, "\\|");
15
+ }
16
+ export async function generateToolInventory() {
17
+ const server = await createServer();
18
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
19
+ const client = new Client({
20
+ name: "wastech-mdlint-doc-generator",
21
+ version: "0.0.0",
22
+ });
23
+ await Promise.all([
24
+ server.connect(serverTransport),
25
+ client.connect(clientTransport),
26
+ ]);
27
+ try {
28
+ const { tools } = await client.listTools();
29
+ const header = "| Tool | Description | Read-only | Structured output |";
30
+ const divider = "| --- | --- | --- | --- |";
31
+ // Registration order is preserved deliberately (not alphabetized): it groups by family
32
+ // (lint/lint-files, the three graph tools, then compile-context last as the structured-output
33
+ // exception), which reads better than alphabetical and is still fully deterministic — the order
34
+ // comes from a fixed registrar array, not filesystem or Map-iteration order.
35
+ const rows = tools.map((tool) => {
36
+ const readOnly = tool.annotations?.readOnlyHint === true ? "yes" : "no";
37
+ const structured = tool.outputSchema !== undefined ? "yes" : "no";
38
+ return `| \`${tool.name}\` | ${escapeCell(tool.description ?? "")} | ${readOnly} | ${structured} |`;
39
+ });
40
+ return [header, divider, ...rows].join("\n");
41
+ }
42
+ finally {
43
+ await client.close();
44
+ await server.close();
45
+ }
46
+ }
@@ -0,0 +1,5 @@
1
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
3
+ import { type ToolFileInput } from "../shared/tool-context.js";
4
+ export declare function handleCompileContext(input: ToolFileInput): Promise<CallToolResult>;
5
+ export declare function registerCompileContextTool(server: McpServer): void;