Skip to main content
Glama
kobaltgit

MCP Typography Audit Server

by kobaltgit

MCP Typography Server Banner

MCP Typography Audit Server

Сервер протокола Model Context Protocol (MCP), позволяющий AI-агентам (Claude, Cursor, Windsurf и др.) выполнять полиграфический аудит вёрстки и проверять вёрстку с книжным выравниванием текста по алгоритму Кнута — Пласса (как в издательской системе $\mathrm{\TeX}$).

Ядро проекта: Вся логика высокоточной веб-типографики, переносов и микровыравнивания базируется на библиотеке Justif от Lyall Cooper. Данный MCP-сервер переносит её возможности в автономную среду headless-браузера Playwright для работы с AI-агентами.


📖 Возможности

  • Книжная типографика для агента: Реализация алгоритма Кнута — Пласса (Knuth-Plass line breaking) устраняет построчные «реки» пробелов, выравнивает полосу набора, включает микротипографику и висячую пунктуацию.

  • Поддержка переносов (Hyphenation): Корректные переносы длинных слов по слогам (включая русский язык ru и английский en-us).

  • Визуальная обратная связь (Vision-in-the-loop): Сервер отдаёт скриншот страницы прямо в формате MCP image/png. Мультимодальные модели (Claude 3.5/3.7, GPT-4o) могут визуально оценить вёрстку и скорректировать CSS.

  • Анализ разметки: Автоматический перехват ошибок JavaScript в консоли браузера, проверка наличия обязательного атрибута lang и тест адаптивности под разную ширину контейнера.


Related MCP server: bettercss

🛠️ Установка и сборка

1. Клонирование и установка зависимостей

git clone https://github.com/kobaltgit/mcp-typography-server.git
cd mcp-typography-server

# Установка NPM-зависимостей
npm install

# Установка браузера Chromium для Playwright (обязательно)
npx playwright install chromium

2. Сборка проекта

npm run build

Команда компилирует TypeScript в исполняемый JavaScript-файл в папке dist/index.js.


🧪 Тестирование сервера

Вариант 1. Интерактивная проверка через MCP Inspector

MCP Inspector — официальный веб-интерфейс для отладки MCP-инструментов.

  1. Запустите инспектор из корня проекта:

    npx @modelcontextprotocol/inspector node dist/index.js
  2. Откройте в браузере ссылку, которую выведет терминал (вида http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=...).

  3. В интерфейсе:

    • Убедитесь, что статус соединения — Connected (зелёный индикатор).

    • Перейдите во вкладку Tools и нажмите List Tools.

    • Выберите инструмент audit_typography.

  4. Заполните тестовые поля:

    • lang: ru

    • width: 700

    • html:

      <h2>Проверка типографики Кнута — Пласса</h2>
      <p>
        «Качественный набор текста — это баланс между формой и смыслом», — писали классики графического дизайна.
        В обычном браузере стандартное выравнивание по ширине часто создает неприятные белые пустоты («реки в наборе»),
        которые сильно утомляют глаз читателя.
      </p>
      <p>
        Библиотека Justif применяет алгоритм из типографской системы TeX. Сложные составные слова,
        такие как <em>высококвалифицированный</em>, <em>сельскохозяйственный</em> или
        <em>достопримечательность</em>, делятся строго по правилам русской орфографии.
      </p>
  5. Нажмите Run Tool. В окне появится отчёт по разметке и скриншот отрендеренной страницы с идеальным выравниванием.


Вариант 2. Автоматический тест через скрипт (test.js)

Запустите тестовый клиент в терминале:

node test.js

Скрипт подключится к серверу через stdio, выполнит тестовый запрос и сохранит результат в файл test-result.png в корне проекта.


🔌 Подключение к AI-клиентам

1. Claude Desktop

Откройте файл конфигурации:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

Добавьте конфигурацию сервера:

macOS / Linux:

{
  "mcpServers": {
    "typography-auditor": {
      "command": "node",
      "args": [
        "/абсолютный/путь/к/mcp-typography-server/dist/index.js"
      ]
    }
  }
}

Windows:

(Обратите внимание на экранирование обратных слэшей \\):

{
  "mcpServers": {
    "typography-auditor": {
      "command": "node",
      "args": [
        "C:\\path\\to\\mcp-typography-server\\dist\\index.js"
      ]
    }
  }
}

2. Cursor / Windsurf

В корне вашего разрабатываемого веб-проекта создайте или отредактируйте файл .cursor/mcp.json:

{
  "mcpServers": {
    "typography-auditor": {
      "command": "node",
      "args": [
        "/абсолютный/путь/к/mcp-typography-server/dist/index.js"
      ]
    }
  }
}

🤖 Пример использования с агентом

После подключения инструмента агенту доступен тул audit_typography.

Пример промпта:

«Сверстай мне адаптивный блок статьи о пользе чтения на русском языке. Примени алгоритм Justif для выравнивания по ширине. Проверь вёрстку через инструмент audit_typography на ширине 375px (мобилка) и 750px (десктоп). Если на скриншоте увидишь неудачные переносы или разрывы строк — скорректируй стили».

Что произойдёт под капотом:

  1. Агент генерирует HTML/CSS код.

  2. Вызывает audit_typography с кодом статьи.

  3. Сервер через Playwright рендерит страницу, применяет Justif и делает скриншот.

  4. Агент получает скриншот, анализирует его с помощью Vision и отдаёт вам проверенный результат.


🙏 Основа проекта и благодарности (Credits)

Этот MCP-сервер был бы невозможен без проекта:

  • Justif — автор Lyall Cooper. Великолепная реализация алгоритма Кнута — Пласса, микротипографики и оптического выравнивания полей для современного веба.


⚠️ Частые вопросы и отладка

Ошибка

Причина

Решение

Executable doesn't exist at ... playwright

Не скачан браузер Chromium

Выполните команду npx playwright install chromium.

Cannot find name 'process' при сборке

Особенности типизации ES-модулей

Убедитесь, что в src/index.ts добавлен import process from "node:process";, а в tsconfig.json указано "types": ["node"].

Сервер не отвечает или ломается JSON-RPC

Вывод лишнего текста в stdout

В коде сервера для логов используйте только console.error(), так как console.log() ломает канал обмена протокола stdio.


📄 Лицензия

MIT

Available Tools

1 tool
audit_typographyB

Рендерит HTML-код, применяет Justif (алгоритм Кнута-Пласса) и возвращает скриншот с аудитом верстки

ParametersJSON Schema
NameRequiredDescriptionDefault
htmlYesHTML-код страницы или фрагмента статьи
langNoЯзык текста для правил переноса ('ru', 'en-us' и т.д.)ru
widthNoШирина экрана для проверки в пикселях (например, 375 для мобилки, 800 для планшета)

TDQS

B3.3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden and it does disclose a useful processing pipeline (render, justify via Knuth-Plass, screenshot output). However, it omits important behavior: whether submitted HTML/scripts are executed, sandbox/permission requirements, latency, and what form the screenshot takes.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single front-loaded sentence that states the pipeline and the output with no filler. Every clause earns its place and the outcome (screenshot + audit) is stated first.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

There is no output schema, so the description must explain the return value; it states a screenshot with a layout audit is returned, but not the concrete form (URL, base64, image part) or contents of the audit. Combined with no annotations, the definition is adequate but leaves real gaps for an agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents html, lang, and width with examples. The description adds no parameter meaning beyond the schema, so the baseline of 3 applies.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description gives a concrete verb chain and resource: renders HTML, applies the Justif (Knuth-Plass) algorithm, and returns a screenshot with a layout audit. An agent can tell this is a typography/verstka auditing tool, though there are no siblings to differentiate it from.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

There is no explicit guidance on when to use this tool, what prerequisites exist, or what alternatives it competes with. The description is entirely about internal processing rather than the conditions that select this tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 1 tool updatev1.0.0
    • First observedaudit_typography

TDQS

B3.4/5.0

Scored across 1 tool

Disambiguation5/5

With only a single tool in the set, there is no possibility of confusing it with another tool. Its purpose (render HTML, apply Knuth-Plass justification, return a layout audit screenshot) is uniquely identifiable.

Naming Consistency5/5

There is only one tool, so no naming pattern can be violated. The single name 'audit_typography' follows a clean verb_noun convention.

Tool Count2/5

A single tool is too thin for what appears to be an auditing domain — there is no way to configure rendering, retrieve detailed findings, or target specific elements. One monolithic tool that does render+justify+screenshot is under-scoped.

Completeness2/5

The surface offers one all-in-one operation with no companion tools for configuration, structured result retrieval, or targeted checks. Agents needing anything beyond a single screenshot audit (e.g. per-element diagnostics or custom width/font inputs) hit a dead end.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables HTML page analysis, verification, and automated correction using Playwright for rendering and Mistral AI for visual inspection. Captures screenshots, analyzes renders against specifications, and generates fixes for HTML issues.
    2
    -
  • A
    license
    Not graded
    quality
    A
    maintenance
    Enables CSS layout verification and debugging by extracting deterministic, diffable rendered layout from a browser, allowing agents to inspect, explain, and diff CSS changes.
    200
    2
    MIT
  • F
    license
    A
    quality
    C
    maintenance
    Enables AI agents to rapidly drive and inspect real web pages through persistent browser sessions, using accessibility-tree snapshots and DevTools-grade diagnostics to identify and diagnose issues.
    23
    -