mcp-hfspace

repository·main·Indexed 18 days ago

https://github.com/evalstate/mcp-hfspace

An MCP (Model Context Protocol) server that connects LLM clients, such as Claude Desktop, to Hugging Face Spaces and Gradio spaces. It enables capabilities including image generation, vision tasks, text-to-speech, and chat by bridging the client to hosted AI models. The server supports dynamic tool generation from Gradio API endpoints, file handling via a configurable working directory, and semantic search for Hugging Face Spaces.

Tokens
4K
Snippets
9
Records
14
Agent score
64%

What's inside mcp-hfspace

  1. How file handling works in Claude Desktop Mode

    main

    The server operates in Claude Desktop Mode by default to optimize the user experience in the Claude Desktop client.

    • Images: Returned directly in the tool responses so Claude can use its vision capabilities.
    • Other Files (Audio, etc.): Saved to the configured WORK_DIR, and the file path is returned as a message.
    • Inputting Files:
      • To upload a file to Claude's context, use the Paperclip Attachment button.
      • To have the MCP server send a file directly to a Space (e.g., for vision models), simply specify the filename (which must exist in the WORK_DIR) in your prompt.
    • URLs: You can provide URLs as inputs; the server will fetch the content and pass it to the Space.
    • Available Resources: The server provides a prompt listing available files and mime types in the working directory, which helps Claude manage files.
  2. Install mcp-hfspace for Claude Desktop

    main

    To use mcp-hfspace with Claude Desktop, you must have Node.js installed. Add the server configuration to your claude_desktop_config.json file.

    File Locations:

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

    Requirements:

    • Claude Desktop version 0.78 or greater.
    • Node.js installed on your system.
    {
      "mcpServers": {
        "mcp-hfspace": {
          "command": "npx",
          "args": [
            "-y",
            "@llmindset/mcp-hfspace"
          ]
        }
      }
    }
  3. Configure mcp-hfspace arguments and environment variables

    main

    You can customize the behavior of mcp-hfspace using command-line arguments or environment variables.

    Working Directory

    By default, the server uses the current working directory for file uploads/downloads, which can be problematic on Windows or macOS. It is highly recommended to set a specific directory using --work-dir or the MCP_HF_WORK_DIR environment variable.

    Hugging Face Token

    To access private spaces, provide your Hugging Face token using the --hf-token argument or the HF_TOKEN environment variable.

    Claude Desktop Mode

    In the default Claude Desktop Mode, images are returned in tool responses and other files are saved to the working directory with their paths returned. To disable this and return content as embedded Base64 encoded resources, use --desktop-mode=false or set CLAUDE_DESKTOP_MODE=false.

    Specifying API Endpoints

    If you need a specific endpoint within a space, append it to the space name (e.g., space/name/endpoint).

    {
      "mcpServers": {
        "mcp-hfspace": {
          "command": "npx",
          "args": [
            "-y",
            "@llmindset/mcp-hfspace",
            "--work-dir=/Users/evalstate/mcp-store",
            "--hf-token=hf_...",
            "shuttleai/shuttle-jaguar",
            "styletts2/styletts2",
            "Qwen/QVQ-72B-preview"
          ]
        }
      }
    }
  4. Troubleshoot mcp-hfspace issues

    main

    Common Issues

    • ZeroGPU Quotas: If you encounter errors or long waits, you may have exhausted your Hugging Face ZeroGPU quota. Try again later or duplicate the space to your own account.
    • Timeouts: Claude Desktop has a hard timeout of approximately 60 seconds. Large or heavy jobs (especially on ZeroGPU) might timeout. Even if a timeout occurs, check your WORK_DIR; the server may have successfully saved the result.
    • Unsupported Endpoints: Endpoints that use unnamed parameters are currently unsupported.
    • Claude Desktop Errors: Claude Desktop 0.75 and earlier may not respond well to MCP errors. Use the @modelcontextprotocol/inspector for better diagnostics.

    Tips for Success

    • Private Spaces: Using an HF_TOKEN allows you to access private spaces and dedicated hardware, which avoids ZeroGPU quotas.
    • Working Directory: Always set a dedicated --work-dir to avoid permission issues on macOS or unexpected paths on Windows.
  5. Convert Gradio API parameters to MCP Tool schemas

    main

    The convertParameter function transforms a Gradio ApiParameter into an MCP-compatible ParameterSchema.

    Key Conversion Behaviors:

    • File Inputs: If isFileParameter is true, the type is set to "string" and the description is specialized based on the component (e.g., "Accepts: Image file URL, file path, file name, or resource identifier" for Image components).
    • Chat History: If the parameter name is "history" and the component is "Chatbot", the type is forced to "array" with a specific description explaining the [user_message, assistant_message] structure.
    • Number Constraints: For number types, it parses the description for constraints like "between X and Y" or "min: X"/"max: Y" to populate minimum and maximum fields.
    • Literal Types (Enums): If the python_type.type starts with "Literal[", it extracts the comma-separated values to populate the enum field in the schema.
    • Defaults and Examples: If parameter_has_default is true, the default key is added. If example_input is present, it is added to an examples array.

    Return Shape

    Returns an object compatible with Tool["inputSchema"]["properties"] containing type, description, and optional enum, default, examples, minimum, or maximum keys.

  6. Convert a full Gradio API endpoint to an MCP JSON Schema

    main

    The convertApiToSchema function converts an entire Gradio ApiEndpoint into a single JSON Schema object used for MCP tool definitions.

    Process:

    1. Iterates through all endpoint.parameters.
    2. Determines a property name for each parameter using parameter_name, then label, or a fallback "Unnamed Parameter X".
    3. Calls convertParameter for each parameter to build the properties object.
    4. Identifies required fields: any parameter where parameter_has_default is false is added to the required array.

    Output Format

    Returns an object with the following structure:

    {
      "type": "object",
      "properties": { "paramName": { ...parameterSchema } },
      "required": [ "paramName1", "paramName2" ]
    }
    // Example conceptual usage:
    const mcpInputSchema = convertApiToSchema(gradioEndpoint);
    // Resulting schema is ready for use in an MCP Tool definition.
  7. Identify file parameters in Gradio API

    main

    The isFileParameter function determines if a Gradio API parameter should be treated as a file input. It returns true if the parameter meets any of the following criteria:

    • python_type.type is exactly "filepath".
    • type is "Blob | File | Buffer".
    • component is "Image".
    • component is "Audio".

    This is used to ensure the MCP tool schema correctly identifies inputs that require file paths or URLs rather than raw text.

    import { isFileParameter } from './gradio_convert';
    
    // Example usage logic:
    const isFile = isFileParameter(someApiParameter);
  8. Configure the mcp-hfspace server via CLI arguments and environment variables

    main

    The mcp-hfspace server can be configured using command-line arguments or environment variables. If arguments are provided, they take precedence over environment variables.

    Configuration Options

    OptionCLI FlagEnv VarTypeDescription
    Claude Desktop Mode--desktop-modeCLAUDE_DESKTOP_MODEbooleanEnables/disables Claude Desktop mode. Defaults to true unless CLAUDE_DESKTOP_MODE is set to "false"
    Work Directory--work-dirMCP_HF_WORK_DIRstringThe directory used for file handling. Defaults to current working directory if not specified
    Hugging Face Token--hf-tokenHF_TOKENstringYour Hugging Face API token for authenticated access
    Debug Mode--debugN/AbooleanEnables debug logging. Defaults to false
    Space Paths(Positional)N/Astring[]One or more Hugging Face Space paths (e.g., user/space-name). If no positional arguments are provided, it defaults to black-forest-labs/FLUX.1-schnell

    Usage Example

    To run the server with a specific work directory, a Hugging Face token, and a specific Space path:

    node dist/index.js --work-dir ./my-files --hf-token hf_abc123 user/my-space
    # Example command line invocation
    node dist/index.js --work-dir ./my-files --hf-token hf_abc123 user/my-space
  9. Understand the Gradio API structure and parameters

    main

    The Gradio API is structured around endpoints that define how to interact with a hosted Gradio space. An ApiStructure contains two types of endpoints: named_endpoints (accessible by a specific name) and unnamed_endpoints (accessed by index).

    Each ApiEndpoint defines the input parameters required and the returns object describing the output. Parameters include metadata such as label, type, component (the Gradio UI component type), and python_type which specifies the underlying Python data type and description.

    export interface ApiStructure {
      named_endpoints: Record<string, ApiEndpoint>;
      unnamed_endpoints: Record<string, ApiEndpoint>;
    }
    
    export interface ApiEndpoint {
      parameters: ApiParameter[];
      returns: ApiReturn[];
      type: {
        generator: boolean;
        cancel: boolean;
      };
    }
    
    export interface ApiParameter {
      label: string;
      parameter_name?: string;
      parameter_has_default?: boolean;
      parameter_default?: unknown;
      type: string;
      python_type: {
        type: string;
        description?: string;
      };
      component: string;
      example_input?: string;
      description?: string;
    }
    
    export interface ApiReturn {
      label: string;
      type: string;
      python_type: {
        type: string;
        description: string;
      };
      component: string;
    }
  10. Available Resources in mcp-hfspace

    main

    The server supports the MCP Resources capability, allowing clients to discover and read files managed by the WorkingDirectory.

    List Resources

    Clients can call list_resources to get a list of supported resources. Each resource includes:

    • uri
    • name
    • mimetype

    Read Resource

    Clients can call read_resource using a specific uri to retrieve the content of a resource.

  11. Available Tools in mcp-hfspace

    main

    The mcp-hfspace server provides several built-in tools to interact with Hugging Face Spaces and local files. In addition to tools dynamically generated from configured Hugging Face Spaces (via EndpointWrapper), the following tools are always available:

    available-files

    Returns a markdown table of available files and resources. Use this tool when the user refers to ambiguous resources like "the most recent image" or "the audio". The table includes resource uri, name, size, last modified, and mime type.

    search-spaces

    Performs a semantic search to find specific endpoints on the Hugging Face Spaces service.

    • Arguments:
      • query (string): The semantic search term (e.g., a 3-7 word description of a task).
    • Returns: A markdown table of search results.
    ### Tool Definitions
    
    | Name | Description | Arguments |
    | :--- | :--- | :--- |
    | `available-files` | A list of available file and resources... returns 'resource uri', 'name', 'size', 'last modified' and 'mime type' in a markdown table | `{}` |
    | `search-spaces` | Use semantic search to find an endpoint on the `Hugging Face Spaces` service... | `{ "query": "string" }` |
  12. Available Prompts in mcp-hfspace

    main

    The server exposes prompts that can be used to guide the LLM. These include a built-in prompt and prompts dynamically generated from configured Hugging Face Spaces:

    Available Resources

    Provides a list of available resources by generating a text-based table of the current working directory's contents.

    Space-Specific Prompts

    Each configured Hugging Face Space endpoint may provide its own prompt templates via promptDefinition().