mcp-gauntlet 0.0.0-stage → 0.2.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,9 @@
1
+ export * from "./types.js";
2
+ export { RULES, runRules } from "./rules/index.js";
3
+ export { connect, type Target, type Session } from "./connect.js";
4
+ export { toLockfile, diffLock, type Lockfile, type Change } from "./lock.js";
5
+ export { runSmoke, type SmokeResult } from "./smoke.js";
6
+ export { loadConfig, type Config, type SmokeCall } from "./config.js";
7
+ export { buildReport, formatText, formatMarkdown, formatGithub, verdicts, type Report } from "./report.js";
8
+ export { estimateTokens } from "./tokens.js";
9
+ export { parseSurface } from "./surface.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export * from "./types.js";
2
+ export { RULES, runRules } from "./rules/index.js";
3
+ export { connect } from "./connect.js";
4
+ export { toLockfile, diffLock } from "./lock.js";
5
+ export { runSmoke } from "./smoke.js";
6
+ export { loadConfig } from "./config.js";
7
+ export { buildReport, formatText, formatMarkdown, formatGithub, verdicts } from "./report.js";
8
+ export { estimateTokens } from "./tokens.js";
9
+ export { parseSurface } from "./surface.js";
package/dist/lock.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import type { JsonSchema, Surface } from "./types.js";
2
+ export interface LockTool {
3
+ description: string;
4
+ inputSchema: JsonSchema;
5
+ outputSchema?: JsonSchema;
6
+ annotations?: Record<string, unknown>;
7
+ }
8
+ export interface Lockfile {
9
+ lockfileVersion: 1;
10
+ server: {
11
+ name: string;
12
+ version: string;
13
+ };
14
+ tools: Record<string, LockTool>;
15
+ prompts: string[];
16
+ resources: string[];
17
+ }
18
+ export interface Change {
19
+ kind: "breaking" | "compatible";
20
+ target: string;
21
+ message: string;
22
+ }
23
+ export declare function toLockfile(surface: Surface): Lockfile;
24
+ export declare function diffLock(before: Lockfile, after: Lockfile): Change[];
package/dist/lock.js ADDED
@@ -0,0 +1,103 @@
1
+ import { createHash } from "node:crypto";
2
+ import { schemaTypes } from "./schema-walk.js";
3
+ function sortKeys(v) {
4
+ if (Array.isArray(v))
5
+ return v.map(sortKeys);
6
+ if (v && typeof v === "object")
7
+ return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
8
+ return v;
9
+ }
10
+ const hash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 12);
11
+ export function toLockfile(surface) {
12
+ const tools = {};
13
+ for (const t of [...surface.tools].sort((a, b) => a.name.localeCompare(b.name))) {
14
+ tools[t.name] = sortKeys({
15
+ description: hash(t.description ?? ""),
16
+ inputSchema: t.inputSchema,
17
+ ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}),
18
+ ...(t.annotations ? { annotations: t.annotations } : {}),
19
+ });
20
+ }
21
+ return {
22
+ lockfileVersion: 1,
23
+ server: surface.server,
24
+ tools,
25
+ prompts: surface.prompts.map((p) => p.name).sort(),
26
+ resources: surface.resources.map((r) => r.uri).sort(),
27
+ };
28
+ }
29
+ /** Flatten nested object properties into dotted paths: "filters.state" etc. Array items use "[]". */
30
+ function fields(schema, prefix = "", out = new Map(), parentRequired = true) {
31
+ if (!schema || typeof schema !== "object")
32
+ return out;
33
+ const props = (schema.properties ?? {});
34
+ const req = new Set(Array.isArray(schema.required) ? schema.required : []);
35
+ for (const [name, sub] of Object.entries(props)) {
36
+ const path = prefix ? `${prefix}.${name}` : name;
37
+ const required = parentRequired && req.has(name);
38
+ out.set(path, { types: schemaTypes(sub).sort(), required, enum: Array.isArray(sub.enum) ? sub.enum : undefined });
39
+ fields(sub, path, out, required);
40
+ if (sub.items && typeof sub.items === "object" && !Array.isArray(sub.items))
41
+ fields(sub.items, `${path}[]`, out, false);
42
+ }
43
+ return out;
44
+ }
45
+ export function diffLock(before, after) {
46
+ const changes = [];
47
+ const b = before.tools, a = after.tools;
48
+ for (const name of Object.keys(b)) {
49
+ if (!(name in a)) {
50
+ changes.push({ kind: "breaking", target: `tool:${name}`, message: "Tool removed. Agents and saved workflows that call it will fail." });
51
+ continue;
52
+ }
53
+ const fb = fields(b[name].inputSchema), fa = fields(a[name].inputSchema);
54
+ for (const [path, old] of fb) {
55
+ const now = fa.get(path);
56
+ if (!now) {
57
+ changes.push({ kind: "breaking", target: `tool:${name}#${path}`, message: "Parameter removed. Callers that still send it may be rejected." });
58
+ continue;
59
+ }
60
+ if (old.types.join() !== now.types.join() && old.types.length && now.types.length && !old.types.every((t) => now.types.includes(t)))
61
+ changes.push({ kind: "breaking", target: `tool:${name}#${path}`, message: `Type changed from ${old.types.join("|")} to ${now.types.join("|")}.` });
62
+ if (!old.required && now.required)
63
+ changes.push({ kind: "breaking", target: `tool:${name}#${path}`, message: "Parameter became required." });
64
+ if (old.required && !now.required)
65
+ changes.push({ kind: "compatible", target: `tool:${name}#${path}`, message: "Parameter became optional." });
66
+ if (old.enum && now.enum) {
67
+ const gone = old.enum.filter((v) => !now.enum.some((w) => JSON.stringify(w) === JSON.stringify(v)));
68
+ const added = now.enum.filter((v) => !old.enum.some((w) => JSON.stringify(w) === JSON.stringify(v)));
69
+ if (gone.length)
70
+ changes.push({ kind: "breaking", target: `tool:${name}#${path}`, message: `Enum values removed: ${gone.map((v) => JSON.stringify(v)).join(", ")}.` });
71
+ if (added.length)
72
+ changes.push({ kind: "compatible", target: `tool:${name}#${path}`, message: `Enum values added: ${added.map((v) => JSON.stringify(v)).join(", ")}.` });
73
+ }
74
+ else if (!old.enum && now.enum) {
75
+ changes.push({ kind: "breaking", target: `tool:${name}#${path}`, message: "Parameter now restricted to an enum." });
76
+ }
77
+ }
78
+ for (const [path, now] of fa) {
79
+ if (fb.has(path))
80
+ continue;
81
+ changes.push(now.required
82
+ ? { kind: "breaking", target: `tool:${name}#${path}`, message: "New required parameter. Existing callers do not send it." }
83
+ : { kind: "compatible", target: `tool:${name}#${path}`, message: "New optional parameter." });
84
+ }
85
+ if (b[name].description !== a[name].description)
86
+ changes.push({ kind: "compatible", target: `tool:${name}`, message: "Description changed (models may pick this tool differently)." });
87
+ const ro = (l) => l.annotations?.readOnlyHint, de = (l) => l.annotations?.destructiveHint;
88
+ if (ro(b[name]) === true && ro(a[name]) !== true)
89
+ changes.push({ kind: "breaking", target: `tool:${name}`, message: "No longer marked readOnlyHint; clients that auto-approved it will now ask, or worse, still auto-approve a tool that writes." });
90
+ if (de(b[name]) !== true && de(a[name]) === true)
91
+ changes.push({ kind: "compatible", target: `tool:${name}`, message: "Now marked destructiveHint." });
92
+ }
93
+ for (const name of Object.keys(a))
94
+ if (!(name in b))
95
+ changes.push({ kind: "compatible", target: `tool:${name}`, message: "Tool added." });
96
+ for (const p of before.prompts)
97
+ if (!after.prompts.includes(p))
98
+ changes.push({ kind: "breaking", target: `prompt:${p}`, message: "Prompt removed." });
99
+ for (const r of before.resources)
100
+ if (!after.resources.includes(r))
101
+ changes.push({ kind: "breaking", target: `resource:${r}`, message: "Resource removed." });
102
+ return changes.sort((x, y) => (x.kind === y.kind ? x.target.localeCompare(y.target) : x.kind === "breaking" ? -1 : 1));
103
+ }
@@ -0,0 +1,20 @@
1
+ import type { Change } from "./lock.js";
2
+ import type { SmokeResult } from "./smoke.js";
3
+ import type { ClientId, Finding, Surface } from "./types.js";
4
+ export interface Report {
5
+ surface: Surface;
6
+ clients: ClientId[];
7
+ findings: Finding[];
8
+ changes: Change[] | null;
9
+ smoke: SmokeResult[];
10
+ tokens: number;
11
+ }
12
+ export declare function buildReport(surface: Surface, clients: ClientId[], findings: Finding[], changes: Change[] | null, smoke: SmokeResult[]): Report;
13
+ /** Per-client verdict: does any error affect this client (or the spec, which affects all)? */
14
+ export declare function verdicts(r: Report): Record<ClientId, "pass" | "warn" | "fail">;
15
+ /** Group findings by target; worst groups first, and worst findings first within a group. */
16
+ export declare function groupByTarget(findings: Finding[]): [string, Finding[]][];
17
+ export declare function formatText(r: Report, color: boolean, verbose?: boolean): string;
18
+ export declare function formatMarkdown(r: Report): string;
19
+ /** GitHub Actions workflow commands, so findings show up as annotations on the run. */
20
+ export declare function formatGithub(r: Report): string;
package/dist/report.js ADDED
@@ -0,0 +1,111 @@
1
+ import { estimateTokens } from "./tokens.js";
2
+ export function buildReport(surface, clients, findings, changes, smoke) {
3
+ return { surface, clients, findings, changes, smoke, tokens: surface.tools.reduce((s, t) => s + estimateTokens(t), 0) };
4
+ }
5
+ const count = (f, s) => f.filter((x) => x.severity === s).length;
6
+ /** Per-client verdict: does any error affect this client (or the spec, which affects all)? */
7
+ export function verdicts(r) {
8
+ const out = {};
9
+ for (const c of r.clients) {
10
+ const hit = r.findings.filter((f) => f.clients.includes(c) || f.clients.includes("mcp"));
11
+ out[c] = hit.some((f) => f.severity === "error") ? "fail" : hit.some((f) => f.severity === "warning") ? "warn" : "pass";
12
+ }
13
+ return out;
14
+ }
15
+ const RANK = { error: 0, warning: 1, info: 2 };
16
+ /** Group findings by target; worst groups first, and worst findings first within a group. */
17
+ export function groupByTarget(findings) {
18
+ const groups = new Map();
19
+ for (const f of findings)
20
+ groups.set(f.target, [...(groups.get(f.target) ?? []), f]);
21
+ const worst = (g) => Math.min(...g.map((f) => RANK[f.severity]));
22
+ return [...groups.entries()]
23
+ .map(([t, g]) => [t, g.sort((a, b) => RANK[a.severity] - RANK[b.severity])])
24
+ .sort((a, b) => worst(a[1]) - worst(b[1]) || a[0].localeCompare(b[0]));
25
+ }
26
+ const LABEL = { mcp: "MCP spec", claude: "Claude", "claude-code": "Claude Code", cursor: "Cursor", openai: "OpenAI", gemini: "Gemini" };
27
+ export function formatText(r, color, verbose = false) {
28
+ const c = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
29
+ const sev = { error: c(31, "error"), warning: c(33, "warn "), info: c(36, "info ") };
30
+ const lines = [];
31
+ const s = r.surface;
32
+ lines.push(c(1, `${s.server.name} ${s.server.version}`) + c(2, ` ${s.tools.length} tools · ${s.prompts.length} prompts · ${s.resources.length} resources · ~${r.tokens} tokens of tool definitions`));
33
+ lines.push("");
34
+ const v = verdicts(r);
35
+ lines.push(r.clients.map((k) => `${v[k] === "pass" ? c(32, "✔") : v[k] === "warn" ? c(33, "▲") : c(31, "✖")} ${LABEL[k]}`).join(" "));
36
+ lines.push("");
37
+ const shown = verbose ? r.findings : r.findings.filter((f) => f.severity !== "info");
38
+ groupByTarget(shown).forEach(([target, group], i) => {
39
+ if (i)
40
+ lines.push("");
41
+ lines.push(c(1, target));
42
+ for (const f of group) {
43
+ lines.push(` ${sev[f.severity]} ${f.message} ${c(2, `[${f.rule}]`)}`);
44
+ if (f.fix)
45
+ lines.push(` ${c(2, "→ " + f.fix)}`);
46
+ }
47
+ });
48
+ if (r.changes) {
49
+ lines.push("");
50
+ if (!r.changes.length)
51
+ lines.push(c(2, "No changes against lockfile."));
52
+ for (const ch of r.changes)
53
+ lines.push(`${ch.kind === "breaking" ? c(31, "BREAKING") : c(32, "change ")} ${ch.target} ${ch.message}`);
54
+ }
55
+ if (r.smoke.length) {
56
+ lines.push("");
57
+ for (const sm of r.smoke)
58
+ lines.push(`${sm.ok ? c(32, "✔") : c(31, "✖")} ${sm.call.tool} ${c(2, `${sm.ms} ms`)}${sm.ok ? "" : " " + sm.detail}`);
59
+ }
60
+ lines.push("");
61
+ const breaking = r.changes?.filter((x) => x.kind === "breaking").length ?? 0;
62
+ lines.push(`${count(r.findings, "error")} errors, ${count(r.findings, "warning")} warnings, ${count(r.findings, "info")} notes${!verbose && count(r.findings, "info") ? " (--verbose to show)" : ""}${r.changes ? `, ${breaking} breaking changes` : ""}`);
63
+ return lines.join("\n");
64
+ }
65
+ export function formatMarkdown(r) {
66
+ const v = verdicts(r);
67
+ const icon = { pass: "✅", warn: "⚠️", fail: "❌" };
68
+ const s = r.surface;
69
+ const out = [];
70
+ out.push(`### mcp-gauntlet · ${s.server.name} ${s.server.version}`);
71
+ out.push("");
72
+ out.push(`| ${r.clients.map((k) => LABEL[k]).join(" | ")} |`);
73
+ out.push(`|${r.clients.map(() => ":-:").join("|")}|`);
74
+ out.push(`| ${r.clients.map((k) => icon[v[k]]).join(" | ")} |`);
75
+ out.push("");
76
+ out.push(`${s.tools.length} tools · ~${r.tokens} tokens · ${count(r.findings, "error")} errors · ${count(r.findings, "warning")} warnings · ${count(r.findings, "info")} notes`);
77
+ const rows = r.findings.filter((f) => f.severity !== "info");
78
+ if (rows.length) {
79
+ out.push("", "| | Where | Problem | Clients |", "|-|-|-|-|");
80
+ for (const f of rows)
81
+ out.push(`| ${f.severity === "error" ? "❌" : "⚠️"} | \`${f.target}\` | ${f.message.replace(/\|/g, "\\|")}${f.fix ? `<br><sub>→ ${f.fix.replace(/\|/g, "\\|")}</sub>` : ""} | ${f.clients.map((k) => LABEL[k]).join(", ")} |`);
82
+ }
83
+ if (r.changes?.length) {
84
+ out.push("", "**Changes since lockfile**", "");
85
+ for (const ch of r.changes)
86
+ out.push(`- ${ch.kind === "breaking" ? "**BREAKING**" : "compatible"} \`${ch.target}\` ${ch.message}`);
87
+ }
88
+ if (r.smoke.length) {
89
+ out.push("", "**Smoke calls**", "");
90
+ for (const sm of r.smoke)
91
+ out.push(`- ${sm.ok ? "✅" : "❌"} \`${sm.call.tool}\` ${sm.ms} ms${sm.ok ? "" : ` — ${sm.detail}`}`);
92
+ }
93
+ const notes = r.findings.filter((f) => f.severity === "info");
94
+ if (notes.length) {
95
+ out.push("", `<details><summary>${notes.length} notes</summary>`, "");
96
+ for (const f of notes)
97
+ out.push(`- \`${f.target}\` ${f.message}`);
98
+ out.push("", "</details>");
99
+ }
100
+ return out.join("\n") + "\n";
101
+ }
102
+ /** GitHub Actions workflow commands, so findings show up as annotations on the run. */
103
+ export function formatGithub(r) {
104
+ const lvl = { error: "error", warning: "warning", info: "notice" };
105
+ const esc = (s) => s.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
106
+ const lines = r.findings.map((f) => `::${lvl[f.severity]} title=${esc(`${f.rule} ${f.target}`)}::${esc(f.message + (f.fix ? ` → ${f.fix}` : ""))}`);
107
+ for (const ch of r.changes ?? [])
108
+ if (ch.kind === "breaking")
109
+ lines.push(`::error title=${esc(`breaking ${ch.target}`)}::${esc(ch.message)}`);
110
+ return lines.join("\n");
111
+ }
@@ -0,0 +1,6 @@
1
+ import type { Rule } from "../types.js";
2
+ /** Per-request tool caps are shared by every server a user enables, so one server should leave room. */
3
+ export declare const DEFAULT_TOOL_BUDGET = 40;
4
+ /** OpenAI API: "Invalid 'tools': array too long. Expected an array with maximum length 128". VS Code Copilot caps a chat request at 128 too. */
5
+ export declare const OPENAI_MAX_TOOLS = 128;
6
+ export declare const docRules: Rule[];
@@ -0,0 +1,92 @@
1
+ import { walkSchema } from "../schema-walk.js";
2
+ import { estimateTokens } from "../tokens.js";
3
+ /** Per-request tool caps are shared by every server a user enables, so one server should leave room. */
4
+ export const DEFAULT_TOOL_BUDGET = 40;
5
+ /** OpenAI API: "Invalid 'tools': array too long. Expected an array with maximum length 128". VS Code Copilot caps a chat request at 128 too. */
6
+ export const OPENAI_MAX_TOOLS = 128;
7
+ export const docRules = [
8
+ {
9
+ id: "docs/tool-description",
10
+ summary: "Every tool has a description a model can choose it by",
11
+ check({ surface }) {
12
+ const out = [];
13
+ for (const t of surface.tools) {
14
+ const d = (t.description ?? "").trim();
15
+ if (!d)
16
+ out.push({ rule: "docs/tool-description", severity: "warning", clients: ["mcp"], target: `tool:${t.name}`, message: "No description; models pick tools by description, so this one will be misused or ignored.", fix: "Say what it does, when to use it, and what it returns." });
17
+ else if (d.length < 12)
18
+ out.push({ rule: "docs/tool-description", severity: "warning", clients: ["mcp"], target: `tool:${t.name}`, message: `Description "${d}" is too short to tell a model when to use this tool.`, fix: "Add when to use it and what it returns." });
19
+ }
20
+ return out;
21
+ },
22
+ },
23
+ {
24
+ id: "docs/description-length",
25
+ summary: "Descriptions stay within the configured character budget",
26
+ check({ surface, budget }) {
27
+ return surface.tools
28
+ .filter((t) => (t.description ?? "").length > budget.descriptionChars)
29
+ .map((t) => ({
30
+ rule: "docs/description-length",
31
+ severity: "warning",
32
+ clients: ["cursor", "claude-code"],
33
+ target: `tool:${t.name}`,
34
+ message: `Description is ${(t.description ?? "").length} chars (budget ${budget.descriptionChars}); some clients truncate long descriptions and every char costs context on every turn.`,
35
+ fix: "Move detail into parameter descriptions or a resource.",
36
+ }));
37
+ },
38
+ },
39
+ {
40
+ id: "docs/param-description",
41
+ summary: "Parameters have descriptions",
42
+ check({ surface }) {
43
+ const out = [];
44
+ for (const t of surface.tools) {
45
+ const missing = [];
46
+ for (const n of walkSchema(t.inputSchema))
47
+ if (n.isProperty && !n.schema.description && !n.schema.title)
48
+ missing.push(n.pointer.split("/").pop());
49
+ if (missing.length)
50
+ out.push({ rule: "docs/param-description", severity: "info", clients: ["mcp"], target: `tool:${t.name}`, message: `Parameters without a description: ${missing.slice(0, 6).join(", ")}${missing.length > 6 ? ` (+${missing.length - 6})` : ""}.` });
51
+ }
52
+ return out;
53
+ },
54
+ },
55
+ {
56
+ id: "docs/annotations",
57
+ summary: "Tools declare readOnlyHint / destructiveHint so clients can decide when to ask the user",
58
+ check({ surface }) {
59
+ return surface.tools
60
+ .filter((t) => !t.annotations || (t.annotations.readOnlyHint === undefined && t.annotations.destructiveHint === undefined))
61
+ .map((t) => ({ rule: "docs/annotations", severity: "info", clients: ["mcp"], target: `tool:${t.name}`, message: "No readOnlyHint or destructiveHint annotation; clients fall back to asking for approval on every call, or never.", fix: "Add annotations: { readOnlyHint: true } for safe reads, destructiveHint: true for deletes." }));
62
+ },
63
+ },
64
+ {
65
+ id: "budget/tokens",
66
+ summary: "The whole tool list fits the configured context budget",
67
+ check({ surface, budget }) {
68
+ const sized = surface.tools.map((t) => ({ t, n: estimateTokens(t) })).sort((a, b) => b.n - a.n);
69
+ const total = sized.reduce((s, x) => s + x.n, 0);
70
+ if (total <= budget.totalTokens)
71
+ return [];
72
+ const top = sized.slice(0, 3).map((x) => `${x.t.name} ~${x.n}`).join(", ");
73
+ return [{ rule: "budget/tokens", severity: "warning", clients: ["mcp"], target: "server", message: `Tool definitions cost ~${total} tokens on every request (budget ${budget.totalTokens}). Heaviest: ${top}.`, fix: "Merge overlapping tools, trim descriptions, or split into several servers users can enable separately." }];
74
+ },
75
+ },
76
+ {
77
+ id: "budget/tool-count",
78
+ summary: "The server leaves room under clients' per-request tool caps (128 in the OpenAI API and VS Code)",
79
+ check({ surface, budget, clients }) {
80
+ const n = surface.tools.length;
81
+ const limit = budget.tools ?? DEFAULT_TOOL_BUDGET;
82
+ const out = [];
83
+ if (n > OPENAI_MAX_TOOLS && clients.has("openai")) {
84
+ out.push({ rule: "budget/tool-count", severity: "error", clients: ["openai"], target: "server", message: `${n} tools: the OpenAI API rejects any request with more than ${OPENAI_MAX_TOOLS} tools ("array too long"), so no request that includes this server can succeed. VS Code Copilot has the same ${OPENAI_MAX_TOOLS}-tool cap per chat request.`, fix: "Split the server into smaller ones by area, or merge tools that differ only by a parameter." });
85
+ }
86
+ if (n > limit) {
87
+ out.push({ rule: "budget/tool-count", severity: "warning", clients: ["mcp"], target: "server", message: `${n} tools (budget ${limit}). Clients cap tools per request across every server the user has enabled (128 in VS Code and the OpenAI API), so a large server crowds out others or gets tools dropped.`, fix: "Group related actions behind one tool with an action parameter, or offer focused servers users can enable separately." });
88
+ }
89
+ return out;
90
+ },
91
+ },
92
+ ];
@@ -0,0 +1,3 @@
1
+ import type { Finding, Rule, RuleContext } from "../types.js";
2
+ export declare const RULES: Rule[];
3
+ export declare function runRules(ctx: RuleContext, disabled?: Set<string>): Finding[];
@@ -0,0 +1,14 @@
1
+ import { nameRules } from "./names.js";
2
+ import { schemaRules } from "./schema.js";
3
+ import { docRules } from "./docs.js";
4
+ export const RULES = [...nameRules, ...schemaRules, ...docRules];
5
+ const ORDER = { error: 0, warning: 1, info: 2 };
6
+ export function runRules(ctx, disabled = new Set()) {
7
+ const out = [];
8
+ for (const rule of RULES) {
9
+ if (disabled.has(rule.id))
10
+ continue;
11
+ out.push(...rule.check(ctx));
12
+ }
13
+ return out.sort((a, b) => ORDER[a.severity] - ORDER[b.severity] || a.target.localeCompare(b.target));
14
+ }
@@ -0,0 +1,6 @@
1
+ import type { Rule } from "../types.js";
2
+ export declare const CLAUDE_CODE_MAX = 64;
3
+ export declare const CURSOR_MAX = 60;
4
+ export declare const nameRules: Rule[];
5
+ /** Produce a safe replacement name: API charset, starting with a letter, bounded length. */
6
+ export declare function suggest(name: string, max: number): string;
@@ -0,0 +1,135 @@
1
+ const MCP_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
2
+ const API_NAME = /^[A-Za-z0-9_-]{1,64}$/; // OpenAI and Anthropic function/tool names
3
+ const GEMINI_NAME = /^[A-Za-z_][A-Za-z0-9_.:-]{0,63}$/;
4
+ export const CLAUDE_CODE_MAX = 64;
5
+ export const CURSOR_MAX = 60;
6
+ export const nameRules = [
7
+ {
8
+ id: "name/spec",
9
+ summary: "Tool names follow the MCP spec: 1-128 chars of A-Z a-z 0-9 _ - .",
10
+ check({ surface }) {
11
+ return surface.tools
12
+ .filter((t) => !MCP_NAME.test(t.name))
13
+ .map((t) => ({
14
+ rule: "name/spec",
15
+ severity: "error",
16
+ clients: ["mcp"],
17
+ target: `tool:${t.name}`,
18
+ message: `"${t.name}" is not a valid MCP tool name (1-128 chars, letters, digits, "_", "-", ".").`,
19
+ fix: `Rename to something like "${suggest(t.name, 64)}".`,
20
+ }));
21
+ },
22
+ },
23
+ {
24
+ id: "name/unique",
25
+ summary: "Tool names are unique, and do not collide when compared case-insensitively",
26
+ check({ surface }) {
27
+ const out = [];
28
+ const seen = new Map();
29
+ for (const t of surface.tools) {
30
+ const key = t.name.toLowerCase();
31
+ const prev = seen.get(key);
32
+ if (prev === t.name) {
33
+ out.push({ rule: "name/unique", severity: "error", clients: ["mcp"], target: `tool:${t.name}`, message: `Tool "${t.name}" is listed more than once.` });
34
+ }
35
+ else if (prev !== undefined) {
36
+ out.push({
37
+ rule: "name/unique",
38
+ severity: "warning",
39
+ clients: ["mcp"],
40
+ target: `tool:${t.name}`,
41
+ message: `"${t.name}" and "${prev}" differ only by case; some clients and models treat them as the same tool.`,
42
+ });
43
+ }
44
+ else
45
+ seen.set(key, t.name);
46
+ }
47
+ return out;
48
+ },
49
+ },
50
+ {
51
+ id: "name/api-charset",
52
+ summary: "Names are accepted unchanged by the OpenAI and Anthropic APIs (^[A-Za-z0-9_-]{1,64}$)",
53
+ check({ surface, clients }) {
54
+ const affected = ["claude", "openai"].filter((c) => clients.has(c));
55
+ if (!affected.length)
56
+ return [];
57
+ return surface.tools
58
+ .filter((t) => MCP_NAME.test(t.name) && !API_NAME.test(t.name))
59
+ .map((t) => ({
60
+ rule: "name/api-charset",
61
+ severity: "error",
62
+ clients: [...affected],
63
+ target: `tool:${t.name}`,
64
+ message: t.name.length > 64
65
+ ? `"${t.name}" is ${t.name.length} chars; OpenAI and Anthropic reject tool names over 64.`
66
+ : `"${t.name}" contains "." which OpenAI and Anthropic reject in tool names; clients either fail or silently rename it.`,
67
+ fix: `Use "${suggest(t.name, 64)}".`,
68
+ }));
69
+ },
70
+ },
71
+ {
72
+ id: "name/gemini",
73
+ summary: "Names are valid Gemini function names (start with a letter or _, max 64)",
74
+ check({ surface, clients }) {
75
+ if (!clients.has("gemini"))
76
+ return [];
77
+ return surface.tools
78
+ .filter((t) => MCP_NAME.test(t.name) && !GEMINI_NAME.test(t.name))
79
+ .map((t) => ({
80
+ rule: "name/gemini",
81
+ severity: "error",
82
+ clients: ["gemini"],
83
+ target: `tool:${t.name}`,
84
+ message: `"${t.name}" is not a valid Gemini function name (must start with a letter or "_" and be at most 64 chars).`,
85
+ fix: `Use "${suggest(t.name, 64)}".`,
86
+ }));
87
+ },
88
+ },
89
+ {
90
+ id: "name/claude-code-prefix",
91
+ summary: `"mcp__<server>__<tool>" fits Claude Code's ${CLAUDE_CODE_MAX}-char limit`,
92
+ check({ surface, clients, serverAlias }) {
93
+ if (!clients.has("claude-code"))
94
+ return [];
95
+ return surface.tools
96
+ .map((t) => ({ t, full: `mcp__${serverAlias}__${t.name}` }))
97
+ .filter(({ full }) => full.length > CLAUDE_CODE_MAX)
98
+ .map(({ t, full }) => ({
99
+ rule: "name/claude-code-prefix",
100
+ severity: "error",
101
+ clients: ["claude-code"],
102
+ target: `tool:${t.name}`,
103
+ message: `Claude Code exposes this tool as "${full}" (${full.length} chars), over its ${CLAUDE_CODE_MAX}-char limit, so the API rejects the whole tool list.`,
104
+ fix: `Shorten the tool name to at most ${Math.max(1, CLAUDE_CODE_MAX - 7 - serverAlias.length)} chars, or tell users to register the server under a shorter name than "${serverAlias}".`,
105
+ }));
106
+ },
107
+ },
108
+ {
109
+ id: "name/cursor-length",
110
+ summary: `Server name + tool name fits Cursor's ${CURSOR_MAX}-char limit`,
111
+ check({ surface, clients, serverAlias }) {
112
+ if (!clients.has("cursor"))
113
+ return [];
114
+ return surface.tools
115
+ .filter((t) => serverAlias.length + t.name.length > CURSOR_MAX)
116
+ .map((t) => ({
117
+ rule: "name/cursor-length",
118
+ severity: "warning",
119
+ clients: ["cursor"],
120
+ target: `tool:${t.name}`,
121
+ message: `"${serverAlias}" + "${t.name}" is ${serverAlias.length + t.name.length} chars; Cursor warns above ${CURSOR_MAX} and shows the model a truncated, hashed name.`,
122
+ fix: `Keep tool names to at most ${Math.max(1, CURSOR_MAX - serverAlias.length)} chars for a server registered as "${serverAlias}".`,
123
+ }));
124
+ },
125
+ },
126
+ ];
127
+ /** Produce a safe replacement name: API charset, starting with a letter, bounded length. */
128
+ export function suggest(name, max) {
129
+ let s = name.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/_+/g, "_").replace(/^[^A-Za-z]+/, "");
130
+ if (!s)
131
+ s = "tool";
132
+ if (s.length > max)
133
+ s = s.slice(0, max).replace(/[_-]+$/, "");
134
+ return s;
135
+ }
@@ -0,0 +1,2 @@
1
+ import type { Rule } from "../types.js";
2
+ export declare const schemaRules: Rule[];