Skip to main content
Glama

formatResult

Convert scraped data into structured formats like markdown, HTML, or JSON. Save outputs to a specified file or default directory, with optional image inclusion for flexible content formatting.

Instructions

Format scraped data into different structured formats (markdown, HTML, JSON)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dataYesThe scraped data to format
formatYesThe format to convert the data to
includeImagesNoWhether to include images in the formatted output (default: true)
outputNoFile path to save the formatted result. If not provided, will use the default directory.

Implementation Reference

  • Main handler function that formats scraped data into specified format (markdown, HTML, JSON) and handles file saving.
    handler: async (params: FormatResultParams): Promise<{ formatted: string; format: string; savedTo?: string }> => {
      const { data, format, includeImages = true, output } = params;
      
      try {
        let formatted: string;
        
        switch (format) {
          case 'markdown':
            formatted = formatAsMarkdown(data, includeImages);
            break;
          case 'html':
            formatted = formatAsHTML(data, includeImages);
            break;
          case 'json':
            formatted = JSON.stringify(data, null, 2);
            break;
          default:
            throw new Error(`Unsupported format: ${format}`);
        }
        
        // Save to file if output path is provided or use default directory
        let savedTo: string | undefined;
        if (output) {
          savedTo = await saveToFile(formatted, output, format, data);
        } else {
          // Save to default location if no output specified but we have a default dir
          const defaultFilename = generateDefaultFilename(data, format);
          savedTo = await saveToFile(formatted, defaultFilename, format, data);
        }
        
        // For large JSON data, truncate the response to avoid overwhelming the LLM
        if (format === 'json' && formatted.length > 10000) {
          formatted = formatted.substring(0, 10000) + '... (truncated for display, full content saved to file)';
        }
        
        return {
          formatted,
          format,
          ...(savedTo && { savedTo })
        };
      } catch (error) {
        throw new Error(`Failed to format result: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • TypeScript interfaces defining input parameters for the formatResult tool.
    // Format options for the formatResult tool
    export type FormatType = 'markdown' | 'html' | 'json';
    
    export interface FormatResultParams {
      data: ScraperResponse;
      format: FormatType;
      includeImages?: boolean;
      output?: string;  // File path to save the formatted result
    } 
  • src/config.ts:65-71 (registration)
    Registration of the formatResult tool in the main MCP server configuration.
    tools: [
      scrapeFocused,
      scrapeBalanced, 
      scrapeDeep,
      // analyzeUrl,
      formatResult
    ],
  • Helper function to format scraped data as Markdown using json2md library.
    function formatAsMarkdown(data: ScraperResponse, includeImages: boolean): string {
      const mdData: json2md.DataObject[] = [];
      
      // Add title
      mdData.push({ h1: data.title });
      
      // Add metadata if available
      if (data.metadata && Object.keys(data.metadata).length > 0) {
        mdData.push({ h2: 'Metadata' });
        
        const metadataItems: string[] = [];
        for (const [key, value] of Object.entries(data.metadata)) {
          if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
            metadataItems.push(`**${key}**: ${value}`);
          }
        }
        
        if (metadataItems.length > 0) {
          mdData.push({ ul: metadataItems });
        }
      }
      
      // Add content
      mdData.push({ h2: 'Content' });
      if (data.content && data.content.length > 0) {
        data.content.forEach(section => {
          mdData.push({ p: section });
        });
      }
      
      // Add images if requested and available
      if (includeImages && data.images && data.images.length > 0) {
        mdData.push({ h2: 'Images' });
        
        data.images.forEach(image => {
          const alt = image.alt || 'Image';
          mdData.push({ img: { 
            title: alt,
            source: image.url 
          }});
        });
      }
      
      return json2md(mdData);
    }
  • Helper function to save the formatted content to a file, handling paths and directories.
    async function saveToFile(content: string, outputPath: string, format: string, data: ScraperResponse): Promise<string> {
      try {
        // Check if outputPath is absolute or relative
        let resolvedPath = outputPath;
        
        // If the path is not absolute, use the default output directory
        if (!path.isAbsolute(outputPath)) {
          resolvedPath = path.join(config.serverOptions.defaultOutputDir, outputPath);
        }
        
        // If only a directory is provided (no filename), generate a filename
        const stats = await fs.stat(resolvedPath).catch(() => null);
        if (stats && stats.isDirectory()) {
          resolvedPath = path.join(resolvedPath, generateDefaultFilename(data, format));
        } else if (!path.extname(resolvedPath)) {
          // If no extension, add one based on format
          const extension = format === 'markdown' ? '.md' : 
                            format === 'html' ? '.html' : '.json';
          resolvedPath = `${resolvedPath}${extension}`;
        }
        
        // Ensure the directory exists
        const dir = path.dirname(resolvedPath);
        await fs.mkdir(dir, { recursive: true });
        
        // Write the content to the file
        await fs.writeFile(resolvedPath, content, 'utf-8');
        return resolvedPath;
      } catch (error) {
        throw new Error(`Failed to save formatted result: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states the transformation action but lacks critical behavioral details: whether this is a read-only operation, if it modifies input data, what permissions are needed, how errors are handled, or what the output looks like. The description mentions file saving capability but doesn't clarify default behavior or error conditions.

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 perfectly concise - a single sentence that efficiently communicates the core functionality without unnecessary words. It's front-loaded with the essential information and wastes no space on redundant details.

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?

For a tool with 4 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain the relationship with sibling scraping tools, doesn't describe what the formatted output looks like, and provides minimal behavioral context. The tool appears to be part of a scraping workflow, but the description doesn't position it within that context.

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?

With 100% schema description coverage, the baseline is 3. The description doesn't add meaningful parameter semantics beyond what's already in the schema - it mentions 'format' options but the schema already documents the enum values. No additional context about parameter interactions or usage patterns is provided.

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: 'Format scraped data into different structured formats (markdown, HTML, JSON)'. It specifies the verb ('format'), resource ('scraped data'), and target formats. However, it doesn't explicitly differentiate from sibling scraping tools, which are data collection tools rather than formatting tools.

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. It doesn't mention prerequisites (e.g., needing scraped data first), nor does it explain how this tool relates to the sibling scraping tools (scrapeBalanced, scrapeDeep, scrapeFocused) that presumably produce the data this tool formats.

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

Related 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/pinkpixel-dev/prysm-mcp-server'

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