Skip to main content
Glama

compress_tool

Compress files into ZIP, TAR, or TAR.GZ formats or extract compressed archives using this file compression tool.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYesAction type: compress or extract
sourcePathYesAbsolute path to source file/directory
destinationPathYesAbsolute path to destination file/directory
formatYesCompression format: zip, tar, tar.gz

Implementation Reference

  • Main handler function that executes the compress or extract logic based on input parameters, dispatching to helper functions.
    export default async (request: any) => {
        try {
            const { action, sourcePath, destinationPath, format } = request.params.arguments;
    
            if (!fs.existsSync(sourcePath)) {
                throw new Error(`Source path does not exist: ${sourcePath}`);
            }
    
            const destDir = path.dirname(destinationPath);
            if (!fs.existsSync(destDir)) {
                // For extraction, we can create the directory. For compression, it must exist.
                if (action === 'compress') {
                    throw new Error(`Destination directory does not exist: ${destDir}`);
                }
            }
    
            if (action === 'compress') {
                if (format === 'zip') {
                    await compressZip(sourcePath, destinationPath);
                } else if (format === 'tar') {
                    await compressTar(sourcePath, destinationPath, false);
                } else if (format === 'tar.gz') {
                    await compressTar(sourcePath, destinationPath, true);
                }
            } else if (action === 'extract') {
                await fse.ensureDir(destinationPath); // Ensure destination directory exists for extraction
                if (format === 'zip') {
                    await extractZip(sourcePath, destinationPath);
                } else if (format === 'tar' || format === 'tar.gz') {
                    await extractTar(sourcePath, destinationPath, format === 'tar.gz');
                }
            }
    
            return {
                content: [{
                    type: "text",
                    text: JSON.stringify({
                        status: "success",
                        operation: `${action} completed`,
                        source: sourcePath,
                        destination: destinationPath
                    }, null, 2)
                }]
            };
    
        } catch (error: any) {
            return {
                content: [{
                    type: "text",
                    text: JSON.stringify({
                        error: error.message,
                        stack: error.stack
                    }, null, 2)
                }],
                isError: true
            };
        }
    };
  • Schema definition for the compress_tool, specifying input parameters and validation.
    export const schema = {
        name: "compress_tool",
        description: "Compress/extract files (zip, tar, tar.gz)",
        type: "object",
        properties: {
            action: {
                type: "string",
                description: "Action type: compress or extract",
                enum: ["compress", "extract"],
            },
            sourcePath: {
                type: "string",
                description: "Absolute path to source file/directory",
            },
            destinationPath: {
                type: "string",
                description: "Absolute path to destination file/directory",
            },
            format: {
                type: "string",
                description: "Compression format: zip, tar, tar.gz",
                enum: ["zip", "tar", "tar.gz"],
            },
        },
        required: ["action", "sourcePath", "destinationPath", "format"]
    };
  • Dynamic registration of tools by loading modules from src/tools directory. Uses filename (e.g., compress_tool.ts) as tool name, imports default handler and schema, and registers in handlers map.
    export async function loadTools(reload: boolean = false): Promise<{ [key: string]: (request: ToolRequest) => Promise<ToolResponse> }> {
      // 如果是初始加载且已加载,则直接返回
      if (!reload && isLoaded) return;
    
      // 如果是重新加载,则重置状态
      if (reload) {
        for (const tool of tools) {
          await tool?.destroy?.();
          delete handlers[tool.name];
        }
        tools.length = 0;
        isLoaded = false;
      }
    
      // 获取所有工具文件
      const toolFiles = fs.readdirSync(toolsDir).filter(file => file.endsWith('.js') || file.endsWith('.ts'));
    
      // 加载每个工具
      for (const file of toolFiles) {
        const toolPath = path.join(toolsDir, file);
        try {
          // 如果是重新加载,清除模块缓存
          if (reload) clearModuleCache(toolPath);
    
          // 导入模块,重新加载时添加时间戳防止缓存
          const importPath = 'file://' + toolPath + (reload ? `?update=${Date.now()}` : '');
          const { default: tool, schema, destroy } = await import(importPath);
          const toolName = path.parse(toolPath).name;
    
          // 注册工具
          tools.push({
            name: toolName,
            description: tool.description,
            inputSchema: schema,
            destroy: destroy
          });
    
          // 注册处理函数
          handlers[toolName] = async (request: ToolRequest) => { return await tool(request); };
        } catch (error) {
          console.error(`Failed to ${reload ? 'reload' : 'load'} tool ${file}:`, error);
        }
      }
    
      isLoaded = true;
      if (reload) console.log(`Successfully reloaded ${tools.length} tools`);
    
      return handlers;
    }

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/xiaoguomeiyitian/ToolBox'

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