### Example MCP Tool Call Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md This is an example of how to call an MCP tool, specifying the tool's name and its arguments. ```json { "name": "flux-1-schnell-predict", "arguments": { "prompt": "a cat sitting on a bench", "steps": 20 } } ``` -------------------------------- ### Initial Configuration and Setup Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/mcp-server.md Parses configuration, initializes a semantic search instance, and sets the working directory. The WorkingDirectory is initialized with the parsed configuration. ```typescript const config = parseConfig(); const semanticSearch = new SemanticSearch(); process.chdir(config.workDir); const workingDir = new WorkingDirectory( config.workDir, config.claudeDesktopMode, ); ``` -------------------------------- ### Audio Converter Usage Example (Claude Desktop Mode) Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/content-converter.md Shows an example of using the audioConverter in Claude Desktop mode, which returns text content with a notification about the audio file's location. ```typescript // Claude Desktop mode const content = await converter.audioConverter(...); // { // type: "resource", // resource: { // uri: "file:///path/to/2024-12-09_tool_audio_a1b2c.wav", // mimetype: "text/plain", // text: "Your audio was successfully created..." // } // } ``` -------------------------------- ### Example Output of generateResourceTable Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md This example shows the markdown-formatted table generated by the `generateResourceTable` function. It includes columns for Resource URI, Name, MIME Type, Size, and Last Modified. It also provides guidance on using the Resource URI for tool parameters. ```markdown The following resources are available for tool calls: | Resource URI | Name | MIME Type | Size | Last Modified | |--------------|------|-----------|------|---------------| | file:./image.png | image.png | image/png | 1.5 MB | 2024-12-09T10:30:00.000Z | | file:./data.json | data.json | application/json | 250.0 B | 2024-12-09T09:15:00.000Z | Prefer using the Resource URI for tool parameters which require a file input. URLs are also accepted. ``` -------------------------------- ### EndpointPath Examples Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/types.md Illustrates how endpoint strings are parsed into the EndpointPath interface, showing examples for both string and numeric endpoint identifiers. ```typescript // Parsed from "owner/space/endpoint-name" { owner: "owner", space: "space", endpoint: "/endpoint-name", mcpToolName: "space-endpoint-name", mcpDisplayName: "space endpoint /endpoint-name" } ``` ```typescript // Parsed from "owner/space/0" { owner: "owner", space: "space", endpoint: 0, mcpToolName: "space-0", mcpDisplayName: "space endpoint /0" } ``` -------------------------------- ### Example Usage of MIME Type Matching Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/mime-types.md Provides an example of how to implement a check for wildcard MIME type matching. This logic determines if a given MIME type matches a supported wildcard pattern. ```typescript const supportedType = "image/*"; const testMimeType = "image/png"; const isMatch = supportedType.includes("/*") ? testMimeType.split("/")[0] === supportedType.split("/")[0] : supportedType === testMimeType; // true ``` -------------------------------- ### Example File Naming Convention Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Generated files follow a specific naming convention including the date, tool name, a prefix, a random ID, and the file extension. ```text YYYY-MM-DD_toolname_prefix_randomid.extension ``` ```text 2024-12-09_flux-predict_image_a1b2c.png ``` -------------------------------- ### Initialize and Create Endpoint Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/common-patterns.md Sets up the server by parsing configuration, setting the working directory, and creating an endpoint wrapper for a given space. This pattern is used for initial server setup. ```typescript import { EndpointWrapper } from './endpoint_wrapper.js'; import { WorkingDirectory } from './working_directory.js'; import { parseConfig } from './config.js'; async function initializeEndpoint() { // Parse configuration from CLI const config = parseConfig(); // Set working directory process.chdir(config.workDir); // Initialize working directory const workingDir = new WorkingDirectory( config.workDir, config.claudeDesktopMode ); // Create endpoint wrapper for space const endpoint = await EndpointWrapper.createEndpoint( 'black-forest-labs/FLUX.1-schnell', workingDir ); // Get tool definition for MCP const toolDef = endpoint.toolDefinition(); console.log(`Created tool: ${toolDef.name}`); return endpoint; } ``` -------------------------------- ### Initialize and Start MCP Server Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/common-patterns.md This snippet demonstrates how to initialize an MCP server with its name, version, and capabilities. It also shows how to set up request handlers for different request types and connect the server to a stdio transport. Use this pattern when you need to launch an MCP server that communicates over standard input/output. ```typescript import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; async function startServer() { // Create server const server = new Server( { name: 'mcp-hfspace', version: '0.5.4' }, { capabilities: { tools: {}, prompts: {}, resources: { list: true } } } ); // Set up request handlers server.setRequestHandler(ListToolsRequestSchema, async () => { // Return available tools }); server.setRequestHandler(CallToolRequestSchema, async (request) => { // Handle tool calls }); // Start server const transport = new StdioServerTransport(); await server.connect(transport); console.log('MCP server started on stdio transport'); } // Main startServer().catch(error => { console.error('Server error:', error); process.exit(1); }); ``` -------------------------------- ### Create and Use ProgressNotifier Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/progress-and-search.md Example demonstrating how to create a ProgressNotifier instance using `createProgressNotifier` and subsequently use its `notify` method to send progress updates. ```typescript import { createProgressNotifier } from './progress_notifier.js'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; const server = new Server({...}, {...}); const notifier = createProgressNotifier(server); // Later, in handler await notifier.notify(status, 'progress-token-123'); ``` -------------------------------- ### Number Constraint Extraction Examples Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/gradio-conversion.md Demonstrates various string patterns recognized for extracting minimum and maximum constraints for number parameters. Matching is case-insensitive. ```plaintext "between 0 and 100" → minimum: 0, maximum: 100 "min: 10, max: 50" → minimum: 10, maximum: 50 "minimum=5 maximum=10" → minimum: 5, maximum: 10 "min. 1 max. 100" → minimum: 1, maximum: 100 ``` -------------------------------- ### Environment Variable and CLI Argument Priority Example Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/configuration.md Demonstrates how environment variables and CLI arguments are resolved, with CLI arguments taking precedence over environment variables for the same setting. ```bash # Environment variable set export MCP_HF_WORK_DIR=/env/path export HF_TOKEN=hf_env_token # CLI invocation with partial overrides npx @llmindset/mcp-hfspace --work-dir=/cli/path # Result: # workDir: /cli/path (from CLI) # hfToken: hf_env_token (from environment, CLI not provided) ``` -------------------------------- ### Audio Converter Usage Example (Other Modes) Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/content-converter.md Illustrates the output of the audioConverter in modes other than Claude Desktop, returning an embedded resource with base64 audio data and MIME type. ```typescript // Other modes const content = await converter.audioConverter(...); // { // type: "resource", // resource: { // uri: "file:///path/to/2024-12-09_tool_audio_a1b2c.wav", // mimeType: "audio/wav", // blob: "//NExAAj2OA..." // } // } ``` -------------------------------- ### Setup Server with Multiple Hugging Face Spaces Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/common-patterns.md Configure a server to load and manage multiple Hugging Face spaces as endpoints. This pattern is useful for creating a unified API gateway to various models or services. ```typescript import { EndpointWrapper } from './endpoint_wrapper.js'; import { WorkingDirectory } from './working_directory.js'; async function setupMultipleSpaces() { const workingDir = new WorkingDirectory('/home/user/mcp-files', true); const spaces = [ 'black-forest-labs/FLUX.1-schnell', 'Qwen/Qwen2.5-72B-Instruct/model_chat', 'parler-tts/parler_tts' ]; const endpoints = new Map(); const errors = []; for (const spacePath of spaces) { try { const endpoint = await EndpointWrapper.createEndpoint( spacePath, workingDir ); const toolName = endpoint.toolDefinition().name; endpoints.set(toolName, endpoint); console.log(`✓ Loaded: ${spacePath} as ${toolName}`); } catch (error) { const message = error instanceof Error ? error.message : String(error); errors.push(`✗ Failed to load ${spacePath}: ${message}`); } } if (errors.length > 0) { console.warn('Load errors:'); errors.forEach(e => console.warn(` ${e}`)); } console.log(`\nTotal endpoints loaded: ${endpoints.size}`); return endpoints; } ``` -------------------------------- ### Install mcp-hfspace via NPM Source: https://github.com/evalstate/mcp-hfspace/blob/main/README.md Add the mcp-hfspace package to your Claude Desktop configuration. Ensure you are using Claude Desktop version 0.78 or greater. ```json "mcp-hfspace": { "command": "npx", "args": [ "-y", "@llmindset/mcp-hfspace" ] } ``` -------------------------------- ### Image Converter Usage Example Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/content-converter.md Demonstrates how to use the imageConverter to process a resource URL and retrieve image content, including its base64 data and MIME type. ```typescript const content = await converter.imageConverter( { label: "Image", component: "Image" }, { url: "https://example.com/result.png" }, endpointPath ); // { // type: "image", // data: "iVBORw0KGgoAAAANSUhEU...", // mimeType: "image/png" // } ``` -------------------------------- ### Start MCP Server with StdioTransport Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/mcp-server.md Initiates the MCP server using StdioServerTransport for communication over standard input/output. The server connects to the transport and begins listening for requests. Errors during startup are logged to stderr and result in a non-zero exit code. ```typescript async function main() { const transport = new StdioServerTransport(); await server.connect(transport); } main().catch((error) => { console.error("Server error:", error); process.exit(1); }); ``` -------------------------------- ### Documentation Categories Overview Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/MANIFEST.md This section categorizes the documentation files into logical groups such as Core References, API References, Utilities, and Examples. This helps users navigate and find relevant information quickly. ```markdown **Core References (3 files)** - overview.md: Architecture and dependencies - configuration.md: Setup and configuration - types.md: Type definitions **API References (6 files)** - endpoint-wrapper.md: Tool endpoint handling - working-directory.md: File operations - gradio-conversion.md: Parameter conversion - content-converter.md: Response conversion - progress-and-search.md: Notifications and discovery - mcp-server.md: Server implementation **Utilities & Reference (2 files)** - mime-types.md: MIME type utilities - quick-reference.md: Quick lookups **Examples & Navigation (3 files)** - common-patterns.md: 15 usage patterns - README.md: Master index - INDEX.md: Documentation statistics ``` -------------------------------- ### Get Supported Resources Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Retrieves an array of ResourceFile objects for all files currently supported by Claude Desktop mode within the working directory. ```typescript async getSupportedResources(): Promise ``` ```typescript const resources = await workDir.getSupportedResources(); // [ResourceFile, ResourceFile, ...] ``` -------------------------------- ### Get Prompt Template Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/endpoint-wrapper.md Generates a prompt template with parameter guidance, using provided argument values or placeholders. It includes default values in hints if available. ```typescript async getPromptTemplate( args?: Record ): Promise ``` ```typescript const result = await wrapper.getPromptTemplate({ prompt: "a cat" }); // { // description: "Use the FLUX.1-schnell endpoint /predict", // messages: [{ // role: "user", // content: { // type: "text", // text: "Using the FLUX.1-schnell endpoint /predict:\n\nprompt: a cat\nsteps: [Provide Number of steps - default: 20]" // } // }] // } ``` -------------------------------- ### Get Prompt Definition Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/endpoint-wrapper.md Provides the tool's prompt definition, including its name, description, and argument requirements. This is used by MCP to generate input templates for users. ```typescript promptDefinition(): PromptDefinition ``` ```typescript const def = wrapper.promptDefinition(); // { // name: "flux-predict", // description: "Use the FLUX.1-schnell endpoint /predict", // arguments: [ // { name: "prompt", description: "Text prompt", required: true }, // { name: "steps", description: "Number of steps", required: false } // ] // } ``` -------------------------------- ### Initialize WorkingDirectory Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Instantiate the WorkingDirectory class with the path to the working directory and an optional flag for Claude Desktop mode. ```typescript import { WorkingDirectory } from './working_directory.js'; const workDir = new WorkingDirectory('/Users/user/mcp-files', true); ``` -------------------------------- ### Manage Files with WorkingDirectory Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Initialize a WorkingDirectory, list files, save new files with generated filenames, and validate existing file paths. ```typescript // Initialize const workDir = new WorkingDirectory('/path/to/dir', true); // List files const files = await workDir.listFiles(); // Save file const filename = await workDir.generateFilename('output', 'png', 'toolname'); await workDir.saveFile(arrayBuffer, filename); // Validate path const validated = await workDir.validatePath('image.png'); // Get resource table const table = await workDir.generateResourceTable(); ``` -------------------------------- ### ApiParameter Interface Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/types.md Defines the structure for an API parameter, including its display label, type information, Gradio component, and optional default values or examples. ```APIDOC ## ApiParameter ### Description Represents a single parameter within a Gradio API endpoint. ### Fields - **label** (string) - Required - Display name for the parameter. - **parameter_name** (string) - Optional - Unique identifier for the parameter (optional if using label). - **parameter_has_default** (boolean) - Optional - Whether the parameter has a default value. - **parameter_default** (unknown) - Optional - Default value if parameter_has_default is true. - **type** (string) - Required - Type string from Gradio (e.g., "string", "number", "Blob \| File \| Buffer"). - **python_type** (object) - Required - Python type metadata with type string and optional description. - **type** (string) - Required - Python type representation. - **description** (string) - Optional - Description of the Python type. - **component** (string) - Required - Gradio component type (e.g., "Textbox", "Image", "Audio", "Chatbot"). - **example_input** (string) - Optional - Example value for the parameter. - **description** (string) - Optional - User-facing description of the parameter. ``` -------------------------------- ### Get Tool Definition Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/endpoint-wrapper.md Generates an MCP tool definition object for the endpoint. This allows the endpoint to be exposed and called as a tool within the MCP framework. ```typescript toolDefinition(): ToolDefinition ``` ```typescript const def = wrapper.toolDefinition(); // { // name: "FLUX_1_schnell-predict", // description: "Call the FLUX.1-schnell endpoint /predict", // inputSchema: { // type: "object", // properties: { /* parameter schemas */ }, // required: ["prompt"] // } // } ``` -------------------------------- ### Project File Structure Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/MANIFEST.md This snippet shows the directory structure of the generated documentation files. It helps in understanding where each documentation module is located. ```tree output/ ├── MANIFEST.md (This file - verification and manifest) ├── INDEX.md (Documentation index and statistics) ├── README.md (Master navigation and overview) │ ├── overview.md (Project identity and structure) ├── configuration.md (Configuration options and setup) ├── types.md (Type definitions and interfaces) │ ├── endpoint-wrapper.md (EndpointWrapper class API) ├── working-directory.md (WorkingDirectory class API) ├── gradio-conversion.md (Parameter conversion functions) ├── content-converter.md (Response format conversion) ├── progress-and-search.md (Progress notifications and search) ├── mcp-server.md (MCP server implementation) │ ├── mime-types.md (MIME type utilities) ├── quick-reference.md (Quick lookup and patterns) └── common-patterns.md (15 real-world usage patterns) ``` -------------------------------- ### MCP Server Initialization Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/mcp-server.md Creates a new MCP server instance with specified name, version, and capabilities. The server is configured to support tools, prompts, and resource listing. ```typescript const server = new Server( { name: "mcp-hfspace", version: VERSION, }, { capabilities: { tools: {}, prompts: {}, resources: { list: true, }, }, }, ); ``` -------------------------------- ### WorkingDirectory Constructor Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Initializes a new instance of the WorkingDirectory class. It takes the absolute path to the working directory and an optional boolean to enable Claude Desktop optimizations. ```APIDOC ## Constructor WorkingDirectory ### Description Initializes a new instance of the WorkingDirectory class. ### Parameters #### Path Parameters - **directory** (string) - Required - Absolute path to the working directory - **claudeDesktopMode** (boolean) - Optional - Whether optimizations for Claude Desktop should be applied. Defaults to false. ### Request Example ```typescript import { WorkingDirectory } from './working_directory.js'; const workDir = new WorkingDirectory('/Users/user/mcp-files', true); ``` ### Constants - **MAX_RESOURCE_SIZE**: 2 MB (2097152 bytes) — Maximum supported file size in Claude Desktop mode ``` -------------------------------- ### Define an API Parameter Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/types.md Defines the structure for a single API parameter, including its display label, type, Gradio component, and optional default values or example inputs. ```typescript 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; } ``` -------------------------------- ### Get File URL Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Converts a filename or path into a file:// URL format, resolving it relative to the working directory if necessary. Uses Node.js's pathToFileURL. ```typescript getFileUrl(filename: string): string // file:///Users/user/mcp-files/image.png ``` ```typescript const url = workDir.getFileUrl('image.png'); ``` -------------------------------- ### Initialize GradioConverter Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/content-converter.md Instantiate the GradioConverter with a WorkingDirectory manager. This is required for file operations during conversion. ```typescript import { GradioConverter } from './content_converter.js'; import { WorkingDirectory } from './working_directory.js'; const workingDir = new WorkingDirectory('/tmp/mcp-files', true); const converter = new GradioConverter(workingDir); ``` -------------------------------- ### Literal Type Enum Extraction Examples Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/gradio-conversion.md Shows how string representations of Python Literal types are converted into JSON schema enum arrays. All enum values are returned as strings. ```plaintext "Literal['A', 'B', 'C']" → enum: ["A", "B", "C"] 'Literal["x", "y"]' → enum: ["x", "y"] "Literal[1, 2, 3]" → enum: ["1", "2", "3"] ``` -------------------------------- ### getPromptTemplate Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/endpoint-wrapper.md Generates a prompt template with parameter guidance, optionally pre-filled with provided argument values. ```APIDOC ## getPromptTemplate ### Description Generates a user-facing prompt template that includes the endpoint description and formatted parameter fields. It can utilize pre-filled argument values or generate placeholders and hints for missing parameters. ### Method `async getPromptTemplate(args?: Record): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **args** (Record) - Optional - Pre-filled argument values for the prompt. ### Request Example ```typescript const result = await wrapper.getPromptTemplate({ prompt: "a cat" }); ``` ### Response #### Success Response (200) * **GetPromptResult** - An object containing the prompt description and an array of message objects. #### Response Example ```json { "description": "Use the FLUX.1-schnell endpoint /predict", "messages": [{ "role": "user", "content": { "type": "text", "text": "Using the FLUX.1-schnell endpoint /predict:\n\nprompt: a cat\nsteps: [Provide Number of steps - default: 20]" } }] } ``` ``` -------------------------------- ### List and Display Resources in Working Directory Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/common-patterns.md Use this pattern to retrieve and display a list of supported resources within a specified working directory. It can output the resources as a formatted table or process them programmatically. ```typescript import { WorkingDirectory } from './working_directory.js'; async function displayResources() { const workingDir = new WorkingDirectory('/path/to/workdir', true); // Get list of supported resources const resources = await workingDir.getSupportedResources(); // Display as table const table = await workingDir.generateResourceTable(); console.log(table); // Or process programmatically for (const resource of resources) { console.log(`${resource.name}: ${resource.mimeType} (${resource.size} bytes)`); } } ``` -------------------------------- ### Get Resource File Metadata Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Retrieves metadata for a given file entry, including its URI, name, MIME type, size, and last modified date. Requires a Dirent object obtained from listFiles(). ```typescript async getResourceFile(file: Dirent): Promise // { uri: "file:./image.png", name: "image.png", mimeType: "image/png", size: 15234, lastModified: Date(...) } ``` ```typescript const entries = await workDir.listFiles(); const file = entries[0]; const resource = await workDir.getResourceFile(file); ``` -------------------------------- ### Launch mcp-hfspace Server Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/overview.md Launches the mcp-hfspace server using npx. Specify options and space paths as needed. ```bash npx @llmindset/mcp-hfspace [options] [space-paths...] ``` -------------------------------- ### getSupportedResources Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Retrieves a list of all files in the directory that are supported by the Claude Desktop mode. ```APIDOC ## getSupportedResources() ### Description Lists all files within the current directory that are deemed supported by the Claude Desktop mode. ### Method `getSupportedResources` ### Parameters None ### Returns Promise - An array of `ResourceFile` objects representing the supported files. ### Behavior 1. Lists all files in the directory. 2. Filters files using the `isSupportedFile()` method. 3. Constructs a `ResourceFile` object for each supported file. 4. Returns the array of `ResourceFile` objects. ### Example ```typescript const resources = await workDir.getSupportedResources(); // [ResourceFile, ResourceFile, ...] ``` ``` -------------------------------- ### createEndpoint Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/endpoint-wrapper.md Creates and initializes an EndpointWrapper instance. It automatically connects to the specified Gradio space, discovers the API structure, and selects the most appropriate endpoint to use, falling back to preferred names or the first available endpoint if necessary. ```APIDOC ## createEndpoint(configuredPath: string, workingDir: WorkingDirectory) ### Description Creates and initializes an EndpointWrapper instance. It automatically connects to the specified Gradio space, discovers the API structure, and selects the most appropriate endpoint to use, falling back to preferred names or the first available endpoint if necessary. ### Parameters #### Path Parameters - **configuredPath** (string) - Required - Space path in format "owner/space" or "owner/space/endpoint" - **workingDir** (WorkingDirectory) - Required - Working directory for file operations ### Returns Promise — Initialized wrapper for the discovered endpoint ### Throws Error if space path format is invalid or no valid endpoints found ### Example ```typescript import { WorkingDirectory } from './working_directory.js'; import { EndpointWrapper } from './endpoint_wrapper.js'; const workingDir = new WorkingDirectory('/tmp/mcp-files', true); // Auto-detect best endpoint const wrapper1 = await EndpointWrapper.createEndpoint( 'black-forest-labs/FLUX.1-schnell', workingDir ); // Use specific endpoint const wrapper2 = await EndpointWrapper.createEndpoint( 'Qwen/Qwen2.5-72B-Instruct/model_chat', workingDir ); ``` ``` -------------------------------- ### Configure MCP Server in Claude Desktop Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/configuration.md Add this JSON configuration to your `claude_desktop_config.json` file to define MCP server settings, including the command to run and its arguments. ```json { "mcpServers": { "mcp-hfspace": { "command": "npx", "args": [ "-y", "@llmindset/mcp-hfspace", "--work-dir=/Users/yourname/mcp-files", "shuttleai/shuttle-3.1-aesthetic", "black-forest-labs/FLUX.1-schnell", "Qwen/Qwen2.5-72B-Instruct" ] } } } ``` -------------------------------- ### Basic CLI Invocation Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/configuration.md Basic command to run the tool with a custom working directory. Uses the default space path. ```bash npx @llmindset/mcp-hfspace --work-dir=/tmp/mcp-files ``` -------------------------------- ### Create Working Directory on Linux Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Use this command to create a dedicated working directory for files on Linux. It's common practice to place such directories in the user's home directory. ```bash # Create working directory mkdir -p ~/.mcp-files ``` -------------------------------- ### Run MCP HFSpace CLI Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Execute the MCP HFSpace CLI with default settings or specify a custom working directory and multiple Hugging Face spaces. ```bash # Default with FLUX image generator npx @llmindset/mcp-hfspace ``` ```bash # With custom working directory npx @llmindset/mcp-hfspace --work-dir=/home/user/mcp-files ``` ```bash # With multiple spaces npx @llmindset/mcp-hfspace \ shuttleai/shuttle-3.1-aesthetic \ black-forest-labs/FLUX.1-schnell \ Qwen/Qwen2.5-72B-Instruct ``` -------------------------------- ### Module to Documentation File Mapping Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/MANIFEST.md This table maps source modules to their generated documentation files, indicating the coverage achieved. A checkmark signifies 100% coverage. ```markdown | Source Module | Output File | |---------------|-------------| | src/config.ts | configuration.md | | src/endpoint_wrapper.ts | endpoint-wrapper.md | | src/working_directory.ts | working-directory.md | | src/gradio_api.ts | types.md | | src/gradio_convert.ts | gradio-conversion.md | | src/content_converter.ts | content-converter.md | | src/progress_notifier.ts | progress-and-search.md | | src/semantic_search.ts | progress-and-search.md | | src/mime_types.ts | mime-types.md | | src/index.ts | mcp-server.md | | src/types.ts | types.md | ``` -------------------------------- ### Multiple Spaces and Custom Directory Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/configuration.md Invokes the tool with multiple space paths and a custom working directory. Useful for processing several spaces concurrently. ```bash npx @llmindset/mcp-hfspace \ --work-dir=/Users/user/mcp-files \ shuttleai/shuttle-3.1-aesthetic \ black-forest-labs/FLUX.1-schnell \ Qwen/Qwen2.5-72B-Instruct ``` -------------------------------- ### Configure mcp-hfspace with Working Directory and Multiple Models Source: https://github.com/evalstate/mcp-hfspace/blob/main/README.md Configure mcp-hfspace to use a specific working directory for file handling and to connect to multiple Hugging Face Spaces for different functionalities (image generation, vision, text-to-speech). ```json "mcp-hfspace": { "command": "npx", "args": [ "-y", "@llmindset/mcp-hfspace", "--work-dir=/Users/evalstate/mcp-store", "shuttleai/shuttle-jaguar", "styletts2/styletts2", "Qwen/QVQ-72B-preview" ] } ``` -------------------------------- ### Parse and Validate Server Configuration Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/common-patterns.md This pattern loads and validates server configuration, ensuring the working directory exists and space paths are correctly formatted. It logs the loaded configuration details. ```typescript import { parseConfig, Config } from './config.js'; function validateConfig(config: Config): boolean { // Check working directory exists const fs = require('fs'); if (!fs.existsSync(config.workDir)) { throw new Error(`Working directory does not exist: ${config.workDir}`); } // Validate space paths if (config.spacePaths.length === 0) { throw new Error('No spaces configured'); } for (const spacePath of config.spacePaths) { const parts = spacePath.split('/'); if (parts.length < 2 || parts.length > 3) { throw new Error(`Invalid space path: ${spacePath}`); } } // Log configuration console.log(`Configuration loaded:`); console.log(` Work Dir: ${config.workDir}`); console.log(` Spaces: ${config.spacePaths.join(', ')}`); console.log(` Claude Desktop Mode: ${config.claudeDesktopMode}`); console.log(` Debug: ${config.debug}`); return true; } // Usage const config = parseConfig(); validateConfig(config); ``` -------------------------------- ### Private Space with Token and Endpoint Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/configuration.md Configures the tool for a private space using a Hugging Face token, a specific working directory, and enables desktop mode. Use this for accessing private repositories or specific endpoints. ```bash npx @llmindset/mcp-hfspace \ --hf-token=hf_your_token_here \ --work-dir=/data/mcp \ --desktop-mode=true \ your-org/private-space/model_chat ``` -------------------------------- ### Generate Prompt with Available Resources Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/mcp-server.md This helper function generates a prompt containing a table of available resources. It's used to provide Claude with a list of files that can be utilized in tool calls. ```typescript async function availableResourcesPrompt() { const tableText = await workingDir.generateResourceTable(); return { messages: [ { role: "user", content: { type: "text", text: tableText, }, }, ], }; } ``` -------------------------------- ### MCP HFSpace CLI Configuration Options Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Understand the available command-line flags for configuring the MCP HFSpace CLI, including working directory, Hugging Face token, and debug mode. ```bash --work-dir=/path # Working directory for files --hf-token=hf_xxxxx # Hugging Face token --desktop-mode=false # Disable Claude Desktop optimizations --debug # Enable debug logging ``` -------------------------------- ### Create Working Directory on Windows Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Use this command to create a dedicated working directory for files on Windows. The APPDATA environment variable points to a user-specific application data folder. ```cmd # Create working directory mkdir %APPDATA%\mcp-files ``` -------------------------------- ### ListResourcesRequestSchema Handler Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/mcp-server.md Handles requests to list supported resources. It retrieves resources from the working directory and formats them for MCP usage. ```APIDOC ## ListResourcesRequestSchema Handler ### Description Handles requests to list supported resources. It retrieves resources from the working directory and formats them for MCP usage. ### Method POST (inferred from setRequestHandler) ### Endpoint /listResources (inferred from ListResourcesRequestSchema) ### Parameters #### Request Body None explicitly defined, but the handler processes a request object. ### Response #### Success Response (200) - **resources** (array) - Array of MCP resource format objects, each containing: - **uri** (string) - The unique identifier for the resource. - **name** (string) - The display name of the resource. - **mimetype** (string) - The MIME type of the resource. ### Response Example ```json { "resources": [ { "uri": "file:///path/to/resource1.txt", "name": "Resource 1", "mimetype": "text/plain" } ] } ``` ``` -------------------------------- ### MCP HFSpace Server Configuration Source: https://github.com/evalstate/mcp-hfspace/blob/main/README.md Configuration for Claude Desktop to connect to the MCP HFSpace server. Ensure to replace placeholders with your actual token and desired paths/spaces. ```json { "mcpServers": { "mcp-hfspace": { "command": "npx" "args": [ "-y", "@llmindset/mcp-hfspace", "--work-dir=~/mcp-files/ or x:/temp/mcp-files/", "--HF_TOKEN=HF_{optional token}" "Qwen/Qwen2-72B-Instruct", "black-forest-labs/FLUX.1-schnell", "space/example/specific-endpint" (... and so on) ] } } } ``` -------------------------------- ### Perform Semantic Search Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Initialize SemanticSearch, search for relevant spaces based on a query, and format the search results into markdown. ```typescript // Initialize const search = new SemanticSearch(); // Search for spaces const results = await search.search('image generation'); // Format results const markdown = search.formatSearchResults(results); ``` -------------------------------- ### GradioConverter Constructor Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/content-converter.md Initializes the GradioConverter with a working directory. It sets up internal registries for handling various Gradio component types. ```APIDOC ## GradioConverter Constructor ### Description Initializes the GradioConverter with a working directory. It sets up internal registries for handling various Gradio component types. ### Signature ```typescript constructor(workingDir: WorkingDirectory) ``` ### Parameters #### Path Parameters - **workingDir** (WorkingDirectory) - Required - Working directory manager for file operations ### Example ```typescript import { GradioConverter } from './content_converter.js'; import { WorkingDirectory } from './working_directory.js'; const workingDir = new WorkingDirectory('/tmp/mcp-files', true); const converter = new GradioConverter(workingDir); ``` ``` -------------------------------- ### Parse and Access Configuration Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Parse the application configuration and access its values such as working directory, space paths, Claude Desktop mode, and Hugging Face token. ```typescript // Parse configuration const config = parseConfig(); // Access config values console.log(config.workDir); console.log(config.spacePaths); console.log(config.claudeDesktopMode); console.log(config.hfToken); ``` -------------------------------- ### Create Working Directory on macOS Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Use this command to create a dedicated working directory for files on macOS. It's recommended to place this in a separate location from your home directory for better organization and performance. ```bash # Create working directory mkdir -p ~/mcp-files ``` -------------------------------- ### generateResourceTable() Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Generates a markdown-formatted table of available resources in the current directory. It lists files, creates ResourceFile objects, and compiles a table with resource details. ```APIDOC ## generateResourceTable() ### Description Generates a markdown-formatted table of available resources in the current directory. It lists files, creates ResourceFile objects, and compiles a table with resource details. ### Method ```typescript async generateResourceTable(): Promise ``` ### Parameters None ### Returns Promise — A markdown-formatted table of available resources, or "No resources available." if the directory is empty. ### Example Output ```markdown The following resources are available for tool calls: | Resource URI | Name | MIME Type | Size | Last Modified | |--------------|------|-----------|------|---------------| | file:./image.png | image.png | image/png | 1.5 MB | 2024-12-09T10:30:00.000Z | | file:./data.json | data.json | application/json | 250.0 B | 2024-12-09T09:15:00.000Z | Prefer using the Resource URI for tool parameters which require a file input. URLs are also accepted. ``` ``` -------------------------------- ### List Files Recursively Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Asynchronously list all files and directories within the working directory, including subdirectories. Returns an array of Dirent objects. ```typescript const entries = await workDir.listFiles(true); // [Dirent, Dirent, ...] ``` -------------------------------- ### isFileSizeSupported(size: number) Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Checks if a given file size in bytes is supported, specifically if it is less than or equal to 2 MB, which is the limit for Claude Desktop mode. ```APIDOC ## isFileSizeSupported(size: number) ### Description Checks if a file size is supported for Claude Desktop mode, returning true if the size is less than or equal to 2 MB. ### Method ```typescript isFileSizeSupported(size: number): boolean ``` ### Parameters #### Path Parameters - **size** (number) - Required - File size in bytes ### Returns boolean — true if size <= 2 MB, false otherwise ### Purpose Checks if file is small enough for Claude Desktop mode support ### Example ```typescript workDir.isFileSizeSupported(1000000); // true workDir.isFileSizeSupported(3000000); // false ``` ``` -------------------------------- ### Claude Desktop Config on Linux Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Specifies the configuration file path for Claude Desktop on Linux. This path is standard for user-specific configuration files. ```bash # Claude Desktop config location (if using Desktop) ~/.config/Claude/claude_desktop_config.json ``` -------------------------------- ### Debug Mode for Troubleshooting Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/configuration.md Enables debug mode for troubleshooting issues. This command includes a custom working directory and a sample space. ```bash npx @llmindset/mcp-hfspace \ --debug \ --work-dir=/tmp/debug \ example/space ``` -------------------------------- ### Space Path Formats Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md These are the supported formats for specifying Hugging Face Spaces. You can use a general owner/space format, specify an endpoint by name, or by index. ```shell owner/space # Auto-select best endpoint ``` ```shell owner/space/endpoint # Use specific endpoint by name ``` ```shell owner/space/0 # Use specific endpoint by index ``` -------------------------------- ### Handle ListResourcesRequestSchema Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/mcp-server.md This request handler retrieves supported resources from the working directory and maps them to the MCP resource format. It returns the resource list or throws an error if the operation fails. ```typescript server.setRequestHandler(ListResourcesRequestSchema, async () => { try { const resources = await workingDir.getSupportedResources(); return { resources: resources.map((resource) => ({ uri: resource.uri, name: resource.name, mimetype: resource.mimeType, })), }; } catch (error) { if (error instanceof Error) { throw new Error(`Failed to list resources: ${error.message}`); } throw error; } }); ``` -------------------------------- ### MIME Type Wildcard Patterns Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/mime-types.md Demonstrates common wildcard patterns used for matching MIME types. These patterns allow for broad matching of related types. ```typescript "text/*" // Matches: text/plain, text/html, text/markdown, etc. ``` ```typescript "image/*" // Matches: image/png, image/jpeg, image/webp, etc. ``` ```typescript "audio/*" // Matches: audio/mp3, audio/wav, audio/ogg, etc. ``` -------------------------------- ### File Path Formats Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md These are the supported formats for specifying file paths. They include relative paths, absolute paths, URLs, and file URIs. ```shell image.png # Relative to working directory ``` ```shell ./data/file.txt # Relative with path ``` ```shell /absolute/path/file # Absolute path ``` ```shell https://example.com/file # URL (passed through) ``` ```shell file:./resource # File URI format ``` -------------------------------- ### promptDefinition Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/endpoint-wrapper.md Retrieves the prompt definition for the tool, including its name, description, and argument specifications, used by MCP for parameter input templates. ```APIDOC ## promptDefinition ### Description Retrieves the prompt definition for the tool, which includes the tool's name, a descriptive endpoint usage string, and definitions for its arguments. This is used by the MCP system to generate user input templates. ### Method `promptDefinition(): PromptDefinition` ### Parameters None ### Returns * **PromptDefinition** - An object containing the tool's name, description, and an array of argument definitions. ### Example ```typescript const def = wrapper.promptDefinition(); // { // name: "flux-predict", // description: "Use the FLUX.1-schnell endpoint /predict", // arguments: [ // { name: "prompt", description: "Text prompt", required: true }, // { name: "steps", description: "Number of steps", required: false } // ] // } ``` ``` -------------------------------- ### Claude Desktop Config on Windows Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Specifies the configuration file path for Claude Desktop on Windows. This path is relative to the user's APPDATA directory. ```cmd # Claude Desktop config %APPDATA%\Claude\claude_desktop_config.json ``` -------------------------------- ### Map File Extensions to MIME Types Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/content-converter.md Maps common file extensions to their corresponding MIME types. For unknown formats, it returns 'application/{extension}'. ```typescript const getMimeTypeFromOriginalName = (origName: string): string | null ``` -------------------------------- ### isSupportedFile Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/working-directory.md Checks if a given file is supported by the Claude Desktop mode. It considers Claude Desktop mode status, file size limits, and MIME type compatibility. ```APIDOC ## isSupportedFile(filename: string) ### Description Determines if a file is supported in Claude Desktop mode. This check includes file size limitations and MIME type validation. ### Method `isSupportedFile` ### Parameters #### Path Parameters - **filename** (string) - Required - The name or path of the file to check. ### Returns Promise - `true` if the file is supported, `false` otherwise. ### Behavior 1. If not in Claude Desktop mode, returns `true`. 2. Checks file size against `MAX_RESOURCE_SIZE`. 3. Gets MIME type using the `mime` library. 4. Returns `true` if the MIME type is text-based or present in `claudeSupportedMimeTypes`. 5. Supports wildcard MIME types (e.g., "image/*"). ### Example ```typescript await workDir.isSupportedFile('image.png'); // true await workDir.isSupportedFile('large.zip'); // false (if >2MB) await workDir.isSupportedFile('video.mp4'); // false (not supported) ``` ``` -------------------------------- ### Create Endpoint Wrapper Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/endpoint-wrapper.md Creates and initializes an EndpointWrapper instance. This static method handles endpoint discovery and connection to the Gradio space. ```typescript static async createEndpoint( configuredPath: string, workingDir: WorkingDirectory ): Promise ``` ```typescript import { WorkingDirectory } from './working_directory.js'; import { EndpointWrapper } from './endpoint_wrapper.js'; const workingDir = new WorkingDirectory('/tmp/mcp-files', true); // Auto-detect best endpoint const wrapper1 = await EndpointWrapper.createEndpoint( 'black-forest-labs/FLUX.1-schnell', workingDir ); // Use specific endpoint const wrapper2 = await EndpointWrapper.createEndpoint( 'Qwen/Qwen2.5-72B-Instruct/model_chat', workingDir ); ``` -------------------------------- ### Create and Call Endpoint with EndpointWrapper Source: https://github.com/evalstate/mcp-hfspace/blob/main/_autodocs/quick-reference.md Use the EndpointWrapper class to create an endpoint connection, retrieve its tool definition, and make calls to it. ```typescript // Create endpoint const wrapper = await EndpointWrapper.createEndpoint( 'owner/space/endpoint', workingDir ); // Get tool definition for MCP const toolDef = wrapper.toolDefinition(); // Call endpoint const result = await wrapper.call(request, server); // Get prompt template const prompt = await wrapper.getPromptTemplate({ arg1: 'value' }); ```