Skip to main content
Glama
Skywalker-Harrison

Soduku Solver MCP Server

solve-sudoku-text

Solve Sudoku puzzles by inputting text representations. Enter puzzle data in text format to receive the completed solution.

Instructions

Solve a Sudoku puzzle from text input

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
puzzleYesThe Sudoku puzzle in text format

Implementation Reference

  • Handler function for the 'solve-sudoku-text' tool. Parses the puzzle text, solves it using solveSudoku, stores original and solved grids, and returns formatted text output.
    elif name == "solve-sudoku-text":
        puzzle_text = arguments.get("puzzle")
        
        if not puzzle_text:
            raise ValueError("Missing puzzle")
            
        try:
            # Parse the puzzle
            grid = parse_sudoku_text(puzzle_text)
            
            # Make a copy of the grid to solve
            original_grid = [row[:] for row in grid]
            
            # Solve the puzzle
            if solveSudoku(grid):
                # Store both the original and solved puzzles
                timestamp = asyncio.get_event_loop().time()
                puzzle_name = f"puzzle_{int(timestamp)}"
                sudoku_puzzles[puzzle_name] = original_grid
                sudoku_puzzles[f"{puzzle_name}_solved"] = grid
                
                # Notify clients that resources have changed
                await server.request_context.session.send_resource_list_changed()
                
                # Return formatted solution
                original_formatted = format_sudoku_grid(original_grid)
                solution_formatted = format_sudoku_grid(grid)
                
                return [
                    types.TextContent(
                        type="text",
                        text=f"Original Sudoku puzzle:\n\n{original_formatted}\n\nSolution:\n\n{solution_formatted}",
                    )
                ]
            else:
                return [
                    types.TextContent(
                        type="text",
                        text=f"No solution found for the given Sudoku puzzle",
                    )
                ]
        except ValueError as e:
            return [
                types.TextContent(
                    type="text",
                    text=f"Error parsing Sudoku puzzle: {str(e)}",
                )
            ]
  • JSON Schema definition for the 'solve-sudoku-text' tool input, requiring a 'puzzle' string.
    types.Tool(
        name="solve-sudoku-text",
        description="Solve a Sudoku puzzle from text input",
        inputSchema={
            "type": "object",
            "properties": {
                "puzzle": {"type": "string", "description": "The Sudoku puzzle in text format"},
            },
            "required": ["puzzle"],
        },
    )
  • Main solveSudoku function that initializes bitmasks and calls the recursive solver. Core logic for solving Sudoku puzzles.
    def solveSudoku(mat):
        """
        Solve a Sudoku puzzle.
        
        Args:
            mat: The Sudoku grid (9x9 matrix) with 0s for empty cells
            
        Returns:
            bool: True if solved successfully, False otherwise
        """
        n = len(mat)
        row = [0] * n
        col = [0] * n
        box = [0] * n
    
        # Set the bits in bitmasks for values that are initially present
        for i in range(n):
            for j in range(n):
                if mat[i][j] != 0:
                    row[i] |= (1 << mat[i][j])
                    col[j] |= (1 << mat[i][j])
                    box[(i // 3) * 3 + j // 3] |= (1 << mat[i][j])
    
        return sudokuSolverRec(mat, 0, 0, row, col, box)
  • Parses text input into a 9x9 Sudoku grid, handling single line or multi-line formats with validation.
    def parse_sudoku_text(text):
        """
        Parse a Sudoku puzzle from text input.
        
        The input can be in various formats:
        - Space or comma-separated values (0 or . for empty cells)
        - Multiple lines representing rows
        
        Args:
            text: String containing the Sudoku puzzle
            
        Returns:
            list: 9x9 matrix representing the Sudoku puzzle
        """
        # Initialize an empty 9x9 grid
        grid = []
        
        # Split the input into lines
        lines = [line.strip() for line in text.strip().split('\n') if line.strip()]
        
        # If we have a single line, try to parse it as a flat representation
        if len(lines) == 1:
            # Replace common separators with spaces
            flat = lines[0].replace(',', ' ').replace(';', ' ')
            # Replace dots with zeros
            flat = flat.replace('.', '0')
            # Split by whitespace and filter out empty strings
            values = [v for v in flat.split() if v]
            
            # Check if we have enough values
            if len(values) != 81:
                raise ValueError(f"Expected 81 values for a 9x9 Sudoku, got {len(values)}")
            
            # Create the 9x9 grid
            for i in range(9):
                row = []
                for j in range(9):
                    cell = values[i * 9 + j]
                    try:
                        row.append(int(cell))
                    except ValueError:
                        raise ValueError(f"Invalid Sudoku value: {cell}")
                grid.append(row)
        else:
            # Parse multiple lines
            for line in lines:
                if not line.strip():
                    continue
                    
                # Replace dots with zeros and remove other common separators
                line = line.replace('.', '0').replace(',', ' ').replace(';', ' ')
                # Split and filter
                values = [v for v in line.split() if v]
                
                row = []
                for cell in values:
                    try:
                        row.append(int(cell))
                    except ValueError:
                        raise ValueError(f"Invalid Sudoku value: {cell}")
                
                if row:
                    grid.append(row)
        
        # Validate the grid dimensions
        if len(grid) != 9:
            raise ValueError(f"Expected 9 rows for Sudoku, got {len(grid)}")
        
        for i, row in enumerate(grid):
            if len(row) != 9:
                raise ValueError(f"Expected 9 columns in row {i}, got {len(row)}")
        
        # Validate the values (0-9 only)
        for i in range(9):
            for j in range(9):
                if not 0 <= grid[i][j] <= 9:
                    raise ValueError(f"Invalid value {grid[i][j]} at position ({i}, {j})")
        
        return grid
  • Formats the Sudoku grid as a readable string with borders.
    def format_sudoku_grid(grid):
        """
        Format a Sudoku grid for display.
        
        Args:
            grid: 9x9 Sudoku grid
            
        Returns:
            str: Formatted string representation of the grid
        """
        result = []
        
        horizontal_line = "+-------+-------+-------+"
        
        for i in range(9):
            if i % 3 == 0:
                result.append(horizontal_line)
            
            row = "| "
            for j in range(9):
                row += str(grid[i][j]) + " "
                if (j + 1) % 3 == 0:
                    row += "| "
                    
            result.append(row)
            
        result.append(horizontal_line)
        
        return "\n".join(result) 
  • The tool is registered in the list_tools handler by including it in the returned list of tools.
    return [
        types.Tool(
            name="add-note",
            description="Add a new note",
            inputSchema={
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "content": {"type": "string"},
                },
                "required": ["name", "content"],
            },
        ),
        types.Tool(
            name="add-sudoku",
            description="Add a new Sudoku puzzle",
            inputSchema={
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "puzzle": {"type": "string", "description": "The Sudoku puzzle in text format"},
                },
                "required": ["name", "puzzle"],
            },
        ),
        types.Tool(
            name="solve-sudoku",
            description="Solve a Sudoku puzzle",
            inputSchema={
                "type": "object",
                "properties": {
                    "name": {"type": "string", "description": "Name of the puzzle to solve"},
                },
                "required": ["name"],
            },
        ),
        types.Tool(
            name="solve-sudoku-text",
            description="Solve a Sudoku puzzle from text input",
            inputSchema={
                "type": "object",
                "properties": {
                    "puzzle": {"type": "string", "description": "The Sudoku puzzle in text format"},
                },
                "required": ["puzzle"],
            },
        )
    ]
Behavior2/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. While 'solve' implies a computational operation, the description doesn't reveal any behavioral traits such as computational complexity, timeout risks, error handling, or what happens with invalid input. This leaves significant gaps for an agent to understand how the tool behaves.

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 extremely concise (just 6 words) and front-loaded with the core purpose. Every word earns its place, with no wasted verbiage or structural issues.

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

Completeness2/5

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

Given the computational nature of Sudoku solving (which can involve complex algorithms and potential failures), the description is insufficient. With no annotations, no output schema, and minimal behavioral disclosure, an agent lacks crucial context about what the tool returns, how it handles edge cases, or what constitutes valid input beyond the basic parameter documentation.

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 description coverage is 100%, with the single parameter 'puzzle' clearly documented in the schema. The description adds no additional parameter semantics beyond what the schema already provides, so it meets the baseline for adequate but unenhanced parameter documentation.

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 clearly states the tool's purpose with a specific verb ('solve') and resource ('Sudoku puzzle from text input'), making it immediately understandable. However, it doesn't distinguish this tool from its sibling 'solve-sudoku', leaving some ambiguity about when to use each variant.

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?

The description provides no guidance on when to use this tool versus alternatives. With a sibling tool named 'solve-sudoku' (without the '-text' suffix), there's clear ambiguity about which tool to choose for different scenarios, but the description offers no clarification.

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

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Skywalker-Harrison/mcp-soduku'

If you have feedback or need assistance with the MCP directory API, please join our Discord server