CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

trysac/mcp-schema-lint

Lint a saved MCP tools/list JSON file for invalid tool names, weak descriptions, untyped input schema parameters and token bloat. Use when reviewing, auditing or fixing MCP tool definitions before release or in CI.

Quality

97%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

lint_tools.pyscripts/

#!/usr/bin/env python3
"""Lint a saved MCP tools/list document. Python standard library only.

Usage: lint_tools.py FILE [--format text|json] [--strict]
                          [--config FILE] [--max-tool-tokens N]

Reads one local JSON file. It makes no network calls and does not connect to
any server. Exit codes: 0 clean, 1 errors (or warnings with --strict),
2 unreadable file, invalid JSON, invalid configuration or usage error.
"""

import json
import math
import os
import re
import sys

MAX_INPUT_CHARS = 5 * 1024 * 1024
MAX_TOOLS = 1000
MAX_FINDINGS = 10000
MAX_DEPTH = 64
MAX_LABEL = 200
MAX_SEGMENT = 256
NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,128}\Z")
PORTABLE_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}\Z")
GENERIC = {"does stuff", "tool", "helper", "todo"}
TYPED_KEYS = ["type", "enum", "const", "$ref", "anyOf", "oneOf", "allOf"]
COMBINATORS = ["anyOf", "oneOf", "allOf"]

RULES = [
    ("name-format", "error"),
    ("name-portability", "warning"),
    ("name-duplicate", "error"),
    ("description-missing", "error"),
    ("description-quality", "warning"),
    ("schema-root", "error"),
    ("required-undefined", "error"),
    ("param-type-missing", "warning"),
    ("param-description-missing", "warning"),
    ("size-budget", "warning"),
]

HINT_NAME = "Use 1-128 characters from A-Z, a-z, 0-9, _, - and ."
HINT_DUP = "Give every tool a unique name."
HINT_DESC = "Describe what the tool does and when to call it."
HINT_QUALITY = "Say what the tool does, its inputs and when to use it."
HINT_ROOT = "Declare inputSchema as a JSON Schema with type object."
HINT_REQ = "Add the property to properties or drop it from required."
HINT_TYPE = "Add a type, enum, const or $ref to the parameter."
HINT_PARAM = "Add a description that tells the model what to pass."
HINT_SIZE = "Shorten descriptions and schemas, or split the tools."


class LintInputError(Exception):
    def __init__(self, code, message):
        super().__init__(message)
        self.code = code


def utf16_len(text):
    return len(text.encode("utf-16-le", "surrogatepass")) // 2


def js_json(value):
    """Compact JSON like JavaScript JSON.stringify."""
    return json.dumps(value, separators=(",", ":"), ensure_ascii=False)


def estimate(value):
    """Token estimate used by the library: ceil(JSON length / 4)."""
    return math.ceil(utf16_len(js_json(value)) / 4)


def trunc(text, limit):
    return text if utf16_len(text) <= limit else text[: limit - 1] + "…"


def quote(text):
    return trunc(js_json(trunc(text, 40)), 80)


def seg(key):
    return trunc(key, MAX_SEGMENT).replace("~", "~0").replace("/", "~1")


def sort_key(text):
    return text.encode("utf-16-be", "surrogatepass")


def is_obj(value):
    return isinstance(value, dict)


def suggest(name, bad, limit):
    fixed = bad.sub("_", name)[:limit]
    return fixed if fixed else "tool"


def settings(config):
    levels = dict(RULES)
    rules = config.get("rules") or {}
    for rule_id, level in rules.items():
        if rule_id not in levels:
            raise LintInputError("UNKNOWN_RULE", "unknown rule " + quote(rule_id))
        if level not in ("error", "warning", "off"):
            raise LintInputError("UNKNOWN_RULE", "invalid level for rule " + quote(rule_id))
        levels[rule_id] = level

    def num(key, default):
        value = config.get(key, default)
        bad = isinstance(value, bool) or not isinstance(value, (int, float))
        if bad or not math.isfinite(value) or value < 0:
            raise ValueError(key + " must be a non-negative number")
        return value

    return {
        "min_desc": num("minDescriptionChars", 20),
        "max_tool": num("maxToolTokens", 800),
        "max_total": num("maxTotalTokens", 8000),
        "levels": levels,
    }


def assert_depth(root):
    stack = [(root, 1)]
    while stack:
        value, depth = stack.pop()
        if not isinstance(value, (dict, list)):
            continue
        if depth > MAX_DEPTH:
            raise LintInputError("TOO_DEEP", "input is nested deeper than 64 levels")
        kids = list(value.values()) if isinstance(value, dict) else value
        for kid in kids:
            if isinstance(kid, (dict, list)):
                stack.append((kid, depth + 1))


def extract(data):
    assert_depth(data)
    if utf16_len(js_json(data)) > MAX_INPUT_CHARS:
        raise LintInputError("TOO_LARGE", "input is larger than 5 MiB")
    base = ""
    tools = None
    if isinstance(data, list):
        tools = data
    elif is_obj(data):
        tools = data.get("tools")
        base = "/tools"
    if not isinstance(tools, list):
        raise LintInputError(
            "NOT_A_TOOLS_LIST", "expected a tools array or an object with a tools array"
        )
    if len(tools) > MAX_TOOLS:
        raise LintInputError("TOO_LARGE", "too many tools, the limit is 1000")
    for entry in tools:
        if not is_obj(entry):
            raise LintInputError("NOT_A_TOOLS_LIST", "every tool must be a JSON object")
    return tools, base


def make_add(levels, tool, out):
    def add(rule, path, message, hint):
        level = levels.get(rule, "off")
        if level == "off":
            return
        out.append(
            {
                "ruleId": rule,
                "severity": level,
                "tool": tool,
                "path": path,
                "message": message,
                "suggestion": hint,
            }
        )

    return add


def check_name(name, ctx):
    add, path = ctx["add"], ctx["path"] + "/name"
    if not isinstance(name, str):
        add("name-format", path, "name is missing or not a string", HINT_NAME)
        return
    q = quote(name)
    if not NAME_RE.match(name) or utf16_len(name) > 128:
        fix = quote(suggest(name, re.compile(r"[^A-Za-z0-9_.-]"), 128))
        add(
            "name-format",
            path,
            "name " + q + " must be 1-128 characters from A-Z a-z 0-9 _ - .",
            "Rename it, for example to " + fix + ".",
        )
    if not PORTABLE_RE.match(name):
        fix = quote(suggest(name, re.compile(r"[^a-zA-Z0-9_-]"), 64))
        add(
            "name-portability",
            path,
            "name " + q + " does not match ^[a-zA-Z0-9_-]{1,64}$",
            "Anthropic and OpenAI APIs need names like " + fix + ".",
        )
    first = ctx["seen"].get(name)
    if first is None:
        ctx["seen"][name] = ctx["index"]
        return
    add("name-duplicate", path, "name " + q + " is already used by tool " + str(first), HINT_DUP)


def check_description(name, desc, ctx):
    add, path = ctx["add"], ctx["path"] + "/description"
    if not isinstance(desc, str) or desc.strip() == "":
        add("description-missing", path, "description is missing or empty", HINT_DESC)
        return
    text = desc.strip().lower()
    minimum = ctx["min_desc"]
    reason = ""
    if isinstance(name, str) and text == name.lower():
        reason = "description only repeats the tool name"
    elif text.rstrip(".!") in GENERIC:
        reason = "description is a generic phrase"
    elif utf16_len(text) < minimum * 2 and len(text) < minimum:
        reason = "description is shorter than %s characters" % fmt_num(minimum)
    if reason:
        add("description-quality", path, reason, HINT_QUALITY)


def fmt_num(value):
    return str(int(value)) if float(value).is_integer() else str(value)


def declared(schema):
    names = set()
    sources = [schema]
    for key in COMBINATORS:
        branches = schema.get(key)
        if isinstance(branches, list):
            sources.extend(branches)
    for source in sources:
        props = source.get("properties") if is_obj(source) else None
        if is_obj(props):
            names.update(props.keys())
    return names


def check_required(schema, path, add):
    required = schema.get("required")
    if not isinstance(required, list):
        return
    known = declared(schema)
    for i, entry in enumerate(required):
        where = "%s/required/%d" % (path, i)
        if not isinstance(entry, str):
            add("required-undefined", where, "required entry is not a string", HINT_REQ)
        elif entry not in known:
            add("required-undefined", where, "required property " + quote(entry) + " is not declared", HINT_REQ)


def check_param(schema, path, add):
    if schema is True:
        add("param-type-missing", path, "schema is true, so the parameter accepts any value", HINT_TYPE)
        return
    if schema is False:
        return
    if not is_obj(schema):
        add("param-type-missing", path, "parameter schema is not an object", HINT_TYPE)
        return
    if not any(key in schema for key in TYPED_KEYS):
        add("param-type-missing", path, "parameter declares no type, enum, const, $ref or combinator", HINT_TYPE)
    desc = schema.get("description")
    if not isinstance(desc, str) or desc.strip() == "":
        add("param-description-missing", path, "parameter has no description", HINT_PARAM)


def push_children(schema, path, stack):
    props = schema.get("properties")
    if is_obj(props):
        for key, value in props.items():
            stack.append((value, "%s/properties/%s" % (path, seg(key)), "param"))
    if "items" in schema:
        items = schema["items"]
        if isinstance(items, list):
            for i, value in enumerate(items):
                stack.append((value, "%s/items/%d" % (path, i), "param"))
        else:
            stack.append((items, path + "/items", "param"))
    prefix = schema.get("prefixItems")
    if isinstance(prefix, list):
        for i, value in enumerate(prefix):
            stack.append((value, "%s/prefixItems/%d" % (path, i), "param"))
    for key in COMBINATORS:
        branches = schema.get(key)
        if isinstance(branches, list):
            for i, value in enumerate(branches):
                stack.append((value, "%s/%s/%d" % (path, key, i), "other"))
    defs = schema.get("$defs")
    if is_obj(defs):
        for key, value in defs.items():
            stack.append((value, "%s/$defs/%s" % (path, seg(key)), "other"))


def walk(root, root_path, add):
    stack = [(root, root_path, "root")]
    while stack:
        schema, path, kind = stack.pop()
        if kind == "param":
            check_param(schema, path, add)
        if not is_obj(schema):
            continue
        if kind != "other":
            check_required(schema, path, add)
        push_children(schema, path, stack)


def check_schema(schema, ctx):
    add, path = ctx["add"], ctx["path"] + "/inputSchema"
    if schema is None and "inputSchema" not in ctx["tool"]:
        add("schema-root", path, "inputSchema is missing", HINT_ROOT)
        return
    if not is_obj(schema):
        add("schema-root", path, "inputSchema is not a JSON Schema object", HINT_ROOT)
        return
    if schema.get("type") != "object":
        add("schema-root", path, "inputSchema must have type object", HINT_ROOT)
    walk(schema, path, add)


def label_of(name, index):
    return trunc(name, MAX_LABEL) if isinstance(name, str) else "tools[%d]" % index


def finding_order(item):
    return (sort_key(item["path"]), sort_key(item["ruleId"]))


def lint_tools(data, config=None):
    st = settings(config or {})
    tools, base = extract(data)
    kept = []
    per_tool = {}
    counts = {"error": 0, "warning": 0, "all": 0}

    def flush(items):
        items.sort(key=finding_order)
        for item in items:
            counts["all"] += 1
            counts[item["severity"]] += 1
            if len(kept) < MAX_FINDINGS:
                kept.append(item)

    total = estimate(tools)
    if total > st["max_total"]:
        items = []
        make_add(st["levels"], "(all tools)", items)(
            "size-budget",
            base,
            "tool list is about %d tokens, budget is %s" % (total, fmt_num(st["max_total"])),
            HINT_SIZE,
        )
        flush(items)
    seen = {}
    for i, tool in enumerate(tools):
        label = label_of(tool.get("name"), i)
        items = []
        ctx = {
            "add": make_add(st["levels"], label, items),
            "path": "%s/%d" % (base, i),
            "index": i,
            "seen": seen,
            "min_desc": st["min_desc"],
            "tool": tool,
        }
        check_name(tool.get("name"), ctx)
        check_description(tool.get("name"), tool.get("description"), ctx)
        check_schema(tool.get("inputSchema"), ctx)
        tokens = estimate(tool)
        per_tool[label] = per_tool.get(label, 0) + tokens
        if tokens > st["max_tool"]:
            ctx["add"](
                "size-budget",
                ctx["path"],
                "tool is about %d tokens, budget is %s" % (tokens, fmt_num(st["max_tool"])),
                HINT_SIZE,
            )
        flush(items)
    return {
        "findings": kept,
        "toolCount": len(tools),
        "estimatedTokens": {"total": total, "perTool": per_tool},
        "errorCount": counts["error"],
        "warningCount": counts["warning"],
        "truncated": counts["all"] > MAX_FINDINGS,
    }


def one_line(text):
    out = []
    for ch in text:
        code = ord(ch)
        out.append("?" if code < 32 or code == 127 or code in (0x2028, 0x2029) else ch)
    return "".join(out)


def format_text(report):
    lines = []
    for f in report["findings"]:
        fields = [f["severity"], f["ruleId"], f["tool"], f["path"], f["message"]]
        lines.append(" ".join(one_line(x) for x in fields))
    if report["truncated"]:
        lines.append("output truncated to %d findings" % len(report["findings"]))
    lines.append("%d errors, %d warnings" % (report["errorCount"], report["warningCount"]))
    return "\n".join(lines)


def format_json(report):
    return json.dumps(report, indent=2, ensure_ascii=False)


def read_json(path, what):
    try:
        size = os.stat(path).st_size
    except OSError:
        raise CliError("cannot read " + what)
    if size > MAX_INPUT_CHARS:
        raise LintInputError("TOO_LARGE", what + " is larger than 5 MiB")
    try:
        with open(path, "r", encoding="utf-8") as handle:
            text = handle.read()
    except (OSError, UnicodeDecodeError):
        raise CliError("cannot read " + what)
    try:
        return json.loads(text)
    except ValueError:
        raise CliError(what + " is not valid JSON")


class CliError(Exception):
    def __init__(self, message, usage=False):
        super().__init__(message)
        self.usage = usage


USAGE = (
    "usage: lint_tools.py FILE [--format text|json] [--strict]\n"
    "                     [--config FILE] [--max-tool-tokens N]\n"
)


def parse_args(argv):
    opts = {"file": None, "format": "text", "strict": False, "config": None, "max_tool": None}
    i = 0
    while i < len(argv):
        arg = argv[i]
        if arg == "--strict":
            opts["strict"] = True
        elif arg in ("--format", "--config", "--max-tool-tokens"):
            i += 1
            value = argv[i] if i < len(argv) else None
            if value is None:
                raise CliError(arg + " needs a value", True)
            if arg == "--format":
                if value not in ("text", "json"):
                    raise CliError("--format must be text or json", True)
                opts["format"] = value
            elif arg == "--config":
                opts["config"] = value
            else:
                if not re.match(r"^[0-9]{1,15}\Z", value):
                    raise CliError("--max-tool-tokens needs a whole number", True)
                opts["max_tool"] = int(value)
        elif arg.startswith("-"):
            raise CliError("unknown option " + js_json(arg[:40]), True)
        elif opts["file"] is not None:
            raise CliError("only one FILE is allowed", True)
        else:
            opts["file"] = arg
        i += 1
    if opts["file"] is None:
        raise CliError("missing FILE", True)
    return opts


def load_config(path, max_tool):
    config = {}
    if path is not None:
        raw = read_json(path, "config file")
        if not is_obj(raw):
            raise CliError("config file must hold a JSON object")
        for key in ("minDescriptionChars", "maxToolTokens", "maxTotalTokens"):
            if key in raw:
                config[key] = raw[key]
        if "rules" in raw:
            if not is_obj(raw["rules"]):
                raise CliError("config rules must be a JSON object")
            config["rules"] = raw["rules"]
    if max_tool is not None:
        config["maxToolTokens"] = max_tool
    return config


def main(argv):
    try:
        opts = parse_args(argv)
        config = load_config(opts["config"], opts["max_tool"])
        report = lint_tools(read_json(opts["file"], "input file"), config)
        render = format_json if opts["format"] == "json" else format_text
        sys.stdout.write(render(report) + "\n")
        if report["errorCount"] > 0:
            return 1
        if opts["strict"] and report["warningCount"] > 0:
            return 1
        return 0
    except CliError as error:
        sys.stderr.write("error: %s\n" % error)
        if error.usage:
            sys.stderr.write(USAGE)
        return 2
    except LintInputError as error:
        sys.stderr.write("error: %s: %s\n" % (error.code, error))
        return 2
    except ValueError as error:
        sys.stderr.write("error: %s\n" % error)
        return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

SKILL.md

tile.json