Skip to main content
Glama
anirbanbasu

smt-sudoku-mcp

by anirbanbasu

Python 3.13+ pytest PyPI GitHub commits since latest release CodeQL Advanced OpenSSF Scorecard License: MIT

╭─╮╭┬╮╶┬╴   ╭─╮╷ ╷╶┬╮╭─╮╷╭ ╷ ╷
╰─╮│││ │    ╰─╮│ │ │││ │├┴╮│ │
╰─╯╵ ╵ ╵    ╰─╯╰─╯╶┴╯╰─╯╵ ╵╰─╯

smt-sudoku-mcp

Теперь ваши агенты могут уверенно играть в судоку!

MCP-сервер, демонстрирующий мощь решения задач по модулю теорий (SMT) с помощью Z3 на классической задаче удовлетворения ограничений — судоку.

Судоку естественным образом отображается на примитивы SMT: генерация головоломки означает поиск модели, удовлетворяющей ограничениям судоку, а затем доказательство того, что уменьшенный набор подсказок по-прежнему имеет единственное решение; проверка сетки означает проверку тех же ограничений на заданных значениях ячеек; решение головоломки означает поиск модели или доказательство её отсутствия.

Инструменты

Все четыре инструмента не имеют состояния: каждый вызов явно принимает и/или возвращает полную сетку, без какого-либо состояния на стороне сервера.

Сетка судоку представляется как {"rows": [[...9 ints...], ...9 rows...]}, где каждая ячейка равна 1-9 для заданной цифры или 0 для пустой ячейки. Любой результат инструмента, который называет конкретную ячейку (конфликт), сообщает row/col с индексацией от 1, что соответствует общепринятому описанию ячеек судоку в тексте (строка 1, столбец 1 — верхняя левая ячейка).

generate_sudoku_puzzle

Генерирует новую судоку-головоломку с единственным решением.

  • Вход: difficulty — одно из "easy", "medium" или "hard" (по умолчанию "medium"), соответствующее приблизительному целевому количеству подсказок.

  • Выход: {"puzzle": <grid>, "difficulty": <str>, "givens": <int>} — givens — фактическое количество заполненных ячеек, которое может быть немного выше целевого, если удаление дополнительных ячеек нарушило бы единственность.

validate_partial_sudoku_solution

Проверяет, свободна ли частично заполненная сетка от конфликтов, и если да, можно ли её ещё завершить.

  • Вход: grid — частичная сетка (0 для пустых ячеек).

  • Выход: {"has_conflicts": <bool>, "conflicts": [<cell>, ...], "is_completable": <bool | null>} — is_completable равен null при наличии конфликтов, поскольку вопрос о завершимости не имеет смысла, пока они не разрешены.

validate_full_sudoku_solution

Проверяет, является ли полностью заполненная сетка правильным решением судоку.

  • Вход: grid — ожидается, что в ней нет пустых ячеек.

  • Выход: {"is_valid": <bool>, "has_empty_cells": <bool>, "conflicts": [<cell>, ...]}.

solve_sudoku_puzzle

Решает нерешённую сетку или сообщает, почему её невозможно решить.

  • Вход: grid — частичная сетка для решения (0 для пустых ячеек).

  • Выход: {"status": "satisfiable" | "conflicting_givens" | "unsatisfiable", "solution": <grid | null>, "conflicts": [<cell>, ...]}. conflicts заполняется только когда status равен "conflicting_givens" (две заданные ячейки напрямую нарушают правило строки/столбца/блока); "unsatisfiable" означает, что заданные ячейки попарно не конфликтуют, но завершение не существует.

Related MCP server: MCP Solver

Установка

Требуется Python 3.13+. Пакет опубликован на PyPI.

Самый простой способ запустить его — с помощью uvx, который при первом использовании загружает пакет во временное окружение и не требует отдельного шага установки:

uvx smt-sudoku-mcp

В качестве альтернативы установите его с помощью pip (или uv pip) и запустите установленный консольный скрипт напрямую:

pip install smt-sudoku-mcp
smt-sudoku-mcp

Чтобы работать с исходным кодом, а не с опубликованным пакетом, см. раздел Разработка ниже.

Использование с MCP-клиентом

Этот сервер по умолчанию работает с MCP через stdio, поэтому любой MCP-клиент, который может запустить подпроцесс, может использовать его без дополнительной настройки. Установите SMT_SUDOKU_MCP_TRANSPORT=streamable-http, если клиенту нужно обращаться к отдельному HTTP-сервису; см. Конфигурация.

Claude Code

claude mcp add smt-sudoku -- uvx smt-sudoku-mcp

Claude Desktop

Добавьте запись в разделе Настройки → Разработчик → Изменить конфигурацию (claude_desktop_config.json):

{
  "mcpServers": {
    "smt-sudoku": {
      "command": "uvx",
      "args": ["smt-sudoku-mcp"]
    }
  }
}

Другие MCP-клиенты и агентные фреймворки

Любой клиент, принимающий сырое определение MCP-сервера — Cursor, Windsurf, VS Code или пользовательский агент на основе MCP SDK — может использовать ту же пару command/args: uvx и ["smt-sudoku-mcp"]. Для streamable-http запустите сервер отдельно с SMT_SUDOKU_MCP_TRANSPORT=streamable-http uvx smt-sudoku-mcp и укажите клиенту адрес http://<host>:<port>/mcp вместо команды для запуска.

После подключения агент может вызывать четыре указанных выше инструмента так же, как и любой другой. Например, просьба агенту «сгенерировать сложную судоку-головоломку, затем решить её и проверить решение» приведёт к последовательному вызову generate_sudoku_puzzle, solve_sudoku_puzzle и validate_full_sudoku_solution без дополнительных указаний, поскольку описания и схемы каждого инструмента достаточны для того, чтобы агент сам спланировал последовательность.

Конфигурация

Переменные окружения, все необязательные:

Переменная

По умолчанию

Описание

SMT_SUDOKU_MCP_TRANSPORT

stdio

stdio или streamable-http

SMT_SUDOKU_MCP_HOST

127.0.0.1

Хост для привязки, только streamable-http

SMT_SUDOKU_MCP_PORT

8000

Порт для привязки, только streamable-http

SMT_SUDOKU_MCP_ALLOWED_ORIGINS

(none)

Разрешённые источники браузера через запятую, только streamable-http

Разработка

Чтобы запустить сервер из исходников вместо опубликованного пакета, используйте uv:

uv sync
uv run smt-sudoku-mcp

См. AGENTS.md с заметками по архитектуре и полным набором команд разработки (just -l).

Вклад

Приветствуются сообщения об ошибках и pull request'ы.

Лицензия

MIT.

Available Tools

4 tools
generate_sudoku_puzzleGenerate Sudoku PuzzleA

Generate a new, uniquely-solvable Sudoku puzzle at the given difficulty.

NameRequiredDescriptionDefault
difficultyNomedium

Output Schema

NameRequiredDescription
givensYesActual number of filled cells in the generated puzzle
puzzleYesA 9x9 Sudoku grid; 0 marks an empty cell.
difficultyYes

TDQS

A4.1/5.0
Behavior4/5

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

No annotations are provided, so the description carries the behavioral disclosure burden. It does disclose two important behaviors: the generated puzzle is 'new' (freshly generated) and 'uniquely-solvable' (guaranteed to have a single solution). It does not explain the exact output shape, but the presence of an output schema reduces the need for that detail.

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?

The description is a single sentence with no filler. It front-loads the core action and then adds the essential constraints ('uniquely-solvable', 'at the given difficulty'), making it concise and scannable.

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

Completeness5/5

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

For a simple one-optional-parameter generator with an output schema present, the description is complete enough. It states what is generated, the key quality guarantee, and the input dimension. The solve/validate siblings are clearly outside this tool's scope.

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?

The schema has 0% descriptive coverage, so the description must compensate. It references 'difficulty' and correctly ties it to the generated puzzle's difficulty, but it does not elaborate on the enum values or the default of medium. The self-explanatory enum in the schema does most of the clarifying work.

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

Purpose5/5

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

The description uses a specific verb ('Generate'), a specific resource ('Sudoku puzzle'), and a key qualifier ('uniquely-solvable'). It is clearly distinguished from the sibling tools validate_partial_sudoku_solution, validate_full_sudoku_solution, and solve_sudoku_puzzle because those are validation/solving operations, not generation.

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

Usage Guidelines3/5

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

The description implies the tool is used when a new Sudoku puzzle is needed, but it does not explicitly state when to choose it over the solve/validate siblings or mention any exclusions. Usage context is clear enough from the verb, but alternative-routing guidance is absent.

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

solve_sudoku_puzzleSolve Sudoku PuzzleA

Solve an unsolved Sudoku grid, or report why it cannot be solved.

NameRequiredDescriptionDefault
gridYesA 9x9 Sudoku grid; 0 marks an empty cell.

Output Schema

NameRequiredDescription
statusYes
solutionYes
conflictsYesPopulated only when status is conflicting_givens

TDQS

A3.8/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. It discloses the primary behavior and the failure-reporting behavior, but does not mention side effects, input validity handling, or what happens if the grid is already solved. It is non-contradictory but minimal.

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?

The description is one tight sentence with no wasted words. The primary purpose is front-loaded, and the failure-reporting behavior is appended without redundancy.

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

Completeness4/5

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

Despite having no annotations, the description adequately defines the tool's contract for a single-parameter operation, and an output schema is available for return-value details. It could be slightly richer on edge cases such as pre-solved or partially invalid grids, but it is largely complete for this tool's complexity.

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?

The input schema already documents the grid parameter thoroughly, including 9x9 shape and 0-for-empty semantics, so schema coverage is 100%. The description adds no parameter-specific detail beyond 'unsolved', which is unnecessary because the schema already defines the structure.

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

Purpose5/5

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

The description clearly states a specific action ('solve') applied to a specific resource ('an unsolved Sudoku grid') and adds a failure-exit behavior ('report why it cannot be solved'). This distinguishes it from the generate and validate siblings based on the core intent.

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

Usage Guidelines3/5

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

The description implies appropriate use for grids that need solving and for diagnosing unsolvability, but it never explicitly contrasts its use with the sibling validation or generation tools. Usage context is reasonably clear, but exclusions and alternative-tool guidance are left to inference.

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

validate_full_sudoku_solutionValidate Full Sudoku SolutionA

Check whether a fully-filled Sudoku grid is a correct solution.

NameRequiredDescriptionDefault
gridYesA 9x9 Sudoku grid; 0 marks an empty cell.

Output Schema

NameRequiredDescription
is_validYes
conflictsYes
has_empty_cellsYes

TDQS

A3.9/5.0
Behavior3/5

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

No annotations are provided, so the description carries the burden of behavioral disclosure. It does communicate that this is a read-only validation check, but it does not explain how empty cells (0) are treated, whether standard Sudoku rules are assumed, or what output is returned. The existence of an output schema mitigates the return-shape gap.

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?

The description is a single sentence with no wasted words, and it front-loads the key constraint ('fully-filled') before the purpose ('correct solution'). This is appropriately concise and easy to parse.

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?

For a single-parameter validator with an output schema, the definition is mostly adequate. However, it does not explicitly state the standard Sudoku rules being validated or clarify how to distinguish this from validate_partial_sudoku_solution, which leaves some ambiguity for an agent deciding between siblings.

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?

The schema already documents the grid parameter thoroughly: 9 rows of 9 cells, digits 1-9, and 0 for empty, giving 100% schema coverage. The description adds the 'fully-filled correct solution' context, but there is a slight tension because the schema explicitly permits empty cells while the description emphasizes a fully-filled grid.

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

Purpose5/5

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

The description states a specific operation ('Check whether') and a specific resource ('a fully-filled Sudoku grid'), and clarifies the goal is verifying a correct solution. The word 'fully-filled' distinguishes it from the partial-validation sibling, so an agent can select it without opening the schema.

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

Usage Guidelines4/5

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

The description makes the intended use clear: call it when you have a complete grid and need to know whether it is a valid solution. It does not explicitly name alternative sibling tools or state when not to use it, so it stops short of full routing guidance.

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

validate_partial_sudoku_solutionValidate Partial Sudoku SolutionA

Check whether a partially-filled Sudoku grid is conflict-free and still completable.

NameRequiredDescriptionDefault
gridYesA 9x9 Sudoku grid; 0 marks an empty cell.

Output Schema

NameRequiredDescription
conflictsYes
empty_cellsYesEvery still-empty cell in the grid, regardless of has_conflicts
has_conflictsYes
is_completableYesWhether the grid can still be completed; None when has_conflicts is True, since completability is not a meaningful question until conflicts are resolved
empty_cells_countYesNumber of still-empty cells, i.e. len(empty_cells)

TDQS

A4/5.0
Behavior3/5

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

With no annotations provided, the description carries the behavioral burden. It discloses the checking criteria (conflict-free, still completable) but does not clarify what 'completable' means (existence of at least one completion vs. uniqueness) or how invalid inputs are handled.

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?

The single sentence is concise and front-loaded with the action and key constraints. Every word contributes to understanding what the tool does.

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

Completeness4/5

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

For a single-parameter tool with a rich schema and output schema present, the description is largely complete. The only notable gap is not defining the semantics of 'still completable' or the exact nature of conflict checking.

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 coverage is 100%, with the grid and row structures already documented including '0 marks an empty cell.' The description adds only the 'partially-filled' framing, which is useful but not necessary beyond the schema, so the baseline score applies.

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

Purpose5/5

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

The description states a specific verb ('Check whether') and resource ('a partially-filled Sudoku grid'), with explicit criteria: conflict-free and still completable. It clearly distinguishes itself from validate_full_sudoku_solution by focusing on partial grids.

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

Usage Guidelines4/5

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

The description clearly signals use for partially-filled grids, which differentiates it from validate_full_sudoku_solution and from generation/solving siblings. However, it does not explicitly name alternatives or state when not to use 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. 4 tool updatesv0.3.0
    • First observedgenerate_sudoku_puzzle
    • First observedsolve_sudoku_puzzle
    • First observedvalidate_full_sudoku_solution
    • First observedvalidate_partial_sudoku_solution

TDQS

A4.2/5.0

Scored across 4 tools

Disambiguation5/5

Each tool has a clear, non-overlapping purpose: generating puzzles, validating partial solutions, validating complete solutions, and solving puzzles. There is no ambiguity about which tool to use for a given task.

Naming Consistency5/5

All tool names follow a consistent verb_noun snake_case pattern. The two validation tools share the same verb and differ only by the qualifier 'partial' or 'full', which is intuitive and predictable.

Tool Count5/5

Four tools is a well-scoped set for a Sudoku-specific server. Each tool addresses a distinct core operation without unnecessary bloat or redundancy.

Completeness5/5

The tool surface covers the full Sudoku workflow: puzzle generation, solving, and validation of both in-progress and completed grids. No significant missing operations exist for the stated domain.

Maintenance

ActivityMaintained
ResponsivenessUnresponsive

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables solving Constraint Satisfaction Problems (CSP) like N-Queens, graph coloring, and Sudoku, as well as Linear Programming optimization problems through both MCP tools and HTTP API endpoints.
    2
    MIT
  • A
    license
    Not graded
    quality
    Not graded
    maintenance
    An MCP server that enables Large Language Models to interactively create, edit, and solve constraint models using backends like MiniZinc, Z3, PySAT, and Clingo. It bridges natural language with symbolic reasoning for solving complex logical, SAT, SMT, and optimization problems.
    MIT
  • F
    license
    A
    quality
    D
    maintenance
    Enables solving constraint satisfaction problems, mathematical equations, and logic puzzles using the Z3 SMT solver through natural language.
    1
    3
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    MCP server for puzzle generation: word search generator, crossword generator, and sudoku generator + solver, with printable PDF worksheets, themed word banks, and verifiable LLM evals. Works with Claude Desktop, Cursor, Windsurf, and any Model Context Protocol client. From the makers of puzzletide.com.
    21 npm
    MIT