Skip to main content
Glama
opensubtitles

OpenSubtitles MCP Server

Official

calculate_file_hash

Generate OpenSubtitles hash values from local movie files to enable subtitle matching and downloading through the OpenSubtitles API.

Instructions

Calculate OpenSubtitles hash for local movie files

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesPath to the movie file

Implementation Reference

  • Main handler function implementing the calculate_file_hash tool logic: validates input, checks file accessibility, computes hash using helper, formats response, and handles errors.
    export async function calculateFileHash(args) {
        try {
            // Validate input arguments
            const validatedArgs = HashArgsSchema.parse(args);
            // Resolve and validate file path
            const resolvedPath = resolve(validatedArgs.file_path);
            // Check if file exists and is readable
            try {
                await access(resolvedPath, constants.R_OK);
            }
            catch (error) {
                throw new Error(`File not found or not readable: ${validatedArgs.file_path}`);
            }
            // Calculate the OpenSubtitles hash
            const hashResult = await calculateOpenSubtitlesHash(resolvedPath);
            // Format response
            const response = {
                file_path: validatedArgs.file_path,
                resolved_path: resolvedPath,
                hash: hashResult.hash,
                size: hashResult.size,
                size_mb: Math.round(hashResult.size / 1024 / 1024 * 100) / 100,
                usage_note: "Use this hash with the 'moviehash' parameter in search_subtitles for exact file matching"
            };
            return {
                content: [
                    {
                        type: "text",
                        text: JSON.stringify(response, null, 2),
                    },
                ],
            };
        }
        catch (error) {
            console.error("Calculate file hash error:", error);
            let errorMessage = "Failed to calculate file hash";
            if (error instanceof z.ZodError) {
                errorMessage = `Invalid parameters: ${error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`;
            }
            else if (error instanceof Error) {
                errorMessage = error.message;
            }
            // Provide helpful error messages
            if (errorMessage.includes("not found")) {
                errorMessage += "\n\nMake sure the file path is correct and the file exists.";
            }
            else if (errorMessage.includes("too small")) {
                errorMessage += "\n\nThe file must be at least 128KB for hash calculation.";
            }
            return {
                content: [
                    {
                        type: "text",
                        text: `Error: ${errorMessage}`,
                    },
                ],
            };
        }
    }
  • MCP input schema definition for the calculate_file_hash tool, specifying required file_path parameter.
    inputSchema: {
        type: "object",
        properties: {
            file_path: {
                type: "string",
                description: "Path to the movie file"
            }
        },
        required: ["file_path"],
        additionalProperties: false
    }
  • dist/server.js:146-160 (registration)
    Tool registration in the MCP server's tools array, including name, description, and input schema.
    {
        name: "calculate_file_hash",
        description: "Calculate OpenSubtitles hash for local movie files",
        inputSchema: {
            type: "object",
            properties: {
                file_path: {
                    type: "string",
                    description: "Path to the movie file"
                }
            },
            required: ["file_path"],
            additionalProperties: false
        }
    }
  • Core helper utility that computes the OpenSubtitles-specific hash algorithm using file size and first/last 64KB chunks.
    export async function calculateOpenSubtitlesHash(filePath) {
        try {
            // Get file size
            const stats = await stat(filePath);
            const fileSize = stats.size;
            if (fileSize < 131072) { // 128KB minimum
                throw new Error("File too small for OpenSubtitles hash calculation (minimum 128KB)");
            }
            const chunkSize = 65536; // 64KB
            // Read first 64KB
            const firstChunk = await readChunk(filePath, 0, chunkSize);
            // Read last 64KB
            const lastChunk = await readChunk(filePath, fileSize - chunkSize, chunkSize);
            // Calculate hash using file size as initial value
            let hash = BigInt(fileSize);
            // Add values from first chunk
            for (let i = 0; i < firstChunk.length; i += 8) {
                hash += BigInt(firstChunk.readBigUInt64LE(i));
            }
            // Add values from last chunk
            for (let i = 0; i < lastChunk.length; i += 8) {
                hash += BigInt(lastChunk.readBigUInt64LE(i));
            }
            // Convert to 16-character hex string
            const hashHex = (hash & BigInt("0xFFFFFFFFFFFFFFFF")).toString(16).padStart(16, '0');
            return {
                hash: hashHex,
                size: fileSize,
            };
        }
        catch (error) {
            if (error instanceof Error) {
                throw new Error(`Failed to calculate hash: ${error.message}`);
            }
            throw new Error("Failed to calculate hash: Unknown error");
        }
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'calculate' but doesn't specify if this is a read-only operation, what the output format is (e.g., hash string), or any performance considerations like processing time for large files. This leaves significant gaps in understanding the tool's behavior.

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, efficient sentence that directly states the tool's purpose without any wasted words. It is appropriately sized and front-loaded, making it easy to understand at a glance.

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 lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., a hash value), potential errors (e.g., file not found), or how the result might be used with sibling tools. For a tool with no structured behavioral data, this is inadequate.

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 has 100% description coverage, with 'file_path' clearly documented as 'Path to the movie file'. The description adds no additional meaning beyond this, such as file format requirements or path syntax examples, but the schema adequately covers the parameter, meeting the baseline for high coverage.

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 verb 'calculate' and the resource 'OpenSubtitles hash for local movie files', making the purpose specific and understandable. However, it doesn't explicitly differentiate from sibling tools like 'download_subtitle' or 'search_subtitles', which are related but distinct operations.

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, such as whether it's for verifying file integrity or preparing for subtitle searches. It lacks context on prerequisites, like needing a local file, or exclusions, such as not working with remote files.

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/opensubtitles/mcp.opensubtitles.com'

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