Skip to main content
Glama

Inspect PDF Fonts

inspect_fonts
Read-onlyIdempotent

List all fonts in a PDF with properties like name, type, encoding, and embedded status. Identify font usage per page to verify PDF compliance or troubleshoot font issues.

Instructions

List all fonts used in a PDF document with their properties.

Args:

  • file_path (string): Absolute path to a local PDF file

  • response_format ('markdown' | 'json'): Output format (default: 'markdown')

Returns: Font name, type (TrueType, Type1, CIDFont, etc.), encoding, embedded/subset status, and pages where each font is used.

Examples:

  • Check if all fonts are embedded (required for PDF/A, PDF/X)

  • Identify font types and encodings

  • Find which pages use specific fonts

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesAbsolute path to a local PDF file (e.g., "/path/to/document.pdf")
response_formatNoOutput format: "markdown" for human-readable, "json" for structured datamarkdown

Implementation Reference

  • The tool registration function (handler) for 'inspect_fonts'. Calls analyzeFontsWithPdfLib to get font data, builds a FontsAnalysis object, and returns results in Markdown or JSON format.
    export function registerInspectFonts(server: McpServer): void {
      server.registerTool(
        'inspect_fonts',
        {
          title: 'Inspect PDF Fonts',
          description: `List all fonts used in a PDF document with their properties.
    
    Args:
      - file_path (string): Absolute path to a local PDF file
      - response_format ('markdown' | 'json'): Output format (default: 'markdown')
    
    Returns:
      Font name, type (TrueType, Type1, CIDFont, etc.), encoding, embedded/subset status, and pages where each font is used.
    
    Examples:
      - Check if all fonts are embedded (required for PDF/A, PDF/X)
      - Identify font types and encodings
      - Find which pages use specific fonts`,
          inputSchema: InspectFontsSchema,
          annotations: {
            readOnlyHint: true,
            destructiveHint: false,
            idempotentHint: true,
            openWorldHint: false,
          },
        },
        async (params: InspectFontsInput) => {
          try {
            const result = await analyzeFontsWithPdfLib(params.file_path);
            const fonts = Array.from(result.fontMap.values());
    
            const analysis: FontsAnalysis = {
              fonts,
              totalFontCount: fonts.length,
              embeddedCount: fonts.filter((f) => f.isEmbedded).length,
              subsetCount: fonts.filter((f) => f.isSubset).length,
              pagesScanned: result.pagesScanned,
              ...(result.note ? { note: result.note } : {}),
            };
    
            const raw =
              params.response_format === ResponseFormat.JSON
                ? JSON.stringify(analysis, null, 2)
                : formatFontsMarkdown(analysis);
    
            const { text } = truncateIfNeeded(raw);
            return { content: [{ type: 'text' as const, text }] };
          } catch (error) {
            const err = handleStructuredError(error);
            return {
              content: [{ type: 'text' as const, text: JSON.stringify(err, null, 2) }],
              isError: true,
            };
          }
        },
      );
    }
  • Zod schema for inspect_fonts input: requires file_path and optional response_format.
    export const InspectFontsSchema = z
      .object({
        file_path: FilePathSchema,
        response_format: ResponseFormatSchema,
      })
      .strict();
  • TypeScript type inferred from the Zod schema for inspect_fonts input.
    export type InspectFontsInput = z.infer<typeof InspectFontsSchema>;
  • TypeScript interface for individual font information (name, type, encoding, embedded/subset status, pages).
    export interface FontInfo {
      name: string;
      type: string;
      encoding: string | null;
      isEmbedded: boolean;
      isSubset: boolean;
      pagesUsed: number[];
    }
  • TypeScript interface for the full font analysis result returned by the handler.
    export interface FontsAnalysis {
      fonts: FontInfo[];
      totalFontCount: number;
      embeddedCount: number;
      subsetCount: number;
      pagesScanned: number;
      /**
       * Optional human-readable note describing partial / fallback results.
       * Set when fonts could not be enumerated via pdf-lib (e.g. Linearized PDFs
       * whose page tree cannot be fully resolved).
       */
      note?: string;
    }
  • Import of the registerInspectFonts function in the central tool registration index.
    import { registerInspectFonts } from './tier2/inspect-fonts.js';
  • Registration call for inspect_fonts in the registerAllTools function.
    registerInspectFonts(server);
  • Core helper that uses pdf-lib to extract font information from every page of the PDF, including font name, subtype, encoding, embedded status, subset detection, and page usage.
    export async function analyzeFontsWithPdfLib(filePath: string): Promise<FontAnalysisResult> {
      return withSuppressedPdfLibLogs(() => analyzeFontsWithPdfLibImpl(filePath));
    }
    
    async function analyzeFontsWithPdfLibImpl(filePath: string): Promise<FontAnalysisResult> {
      const doc = await loadWithPdfLib(filePath);
      const fontMap = new Map<string, FontInfo>();
      const pages = trySilently(() => doc.getPages()) ?? [];
    
      if (pages.length === 0) {
        return {
          fontMap,
          pagesScanned: 0,
          note:
            'pdf-lib could not enumerate the page tree (typical of Linearized PDFs); ' +
            'fonts could not be analyzed. Consider regenerating the PDF without linearization.',
        };
      }
    
      for (let pageIdx = 0; pageIdx < pages.length; pageIdx++) {
        const pageNum = pageIdx + 1;
        const pageNode = pages[pageIdx].node;
        const resources = trySilently(() => pageNode.Resources());
        if (!resources) continue;
    
        const fontDict = trySilently(() => resources.lookupMaybe(PDFName.of('Font'), PDFDict));
        if (!fontDict) continue;
    
        for (const [fontNameObj, fontRefOrDict] of fontDict.entries()) {
          const fontKey = fontNameObj.decodeText();
    
          // Resolve to actual font dictionary
          let actualFont: PDFDict | undefined;
          if (fontRefOrDict instanceof PDFRef) {
            const resolved = doc.context.lookup(fontRefOrDict);
            if (resolved instanceof PDFDict) {
              actualFont = resolved;
            }
          } else if (fontRefOrDict instanceof PDFDict) {
            actualFont = fontRefOrDict;
          }
    
          if (!actualFont) continue;
    
          // Extract font properties
          const subtypeObj = actualFont.lookupMaybe(PDFName.of('Subtype'), PDFName);
          const baseFontObj = actualFont.lookupMaybe(PDFName.of('BaseFont'), PDFName);
          const encodingObj = actualFont.get(PDFName.of('Encoding'));
    
          const baseFontName = baseFontObj?.decodeText() ?? fontKey;
          const subtype = subtypeObj?.decodeText() ?? 'Unknown';
          const encoding = encodingObj instanceof PDFName ? encodingObj.decodeText() : null;
    
          // Check if font is embedded (has FontDescriptor with FontFile/FontFile2/FontFile3)
          let isEmbedded = false;
          const descriptorRef = actualFont.get(PDFName.of('FontDescriptor'));
          if (descriptorRef) {
            let descriptor: PDFDict | undefined;
            if (descriptorRef instanceof PDFRef) {
              const resolved = doc.context.lookup(descriptorRef);
              if (resolved instanceof PDFDict) descriptor = resolved;
            } else if (descriptorRef instanceof PDFDict) {
              descriptor = descriptorRef;
            }
            if (descriptor) {
              isEmbedded =
                descriptor.has(PDFName.of('FontFile')) ||
                descriptor.has(PDFName.of('FontFile2')) ||
                descriptor.has(PDFName.of('FontFile3'));
            }
          }
    
          // Check if subset (name starts with 6 uppercase + '+')
          const isSubset = /^[A-Z]{6}\+/.test(baseFontName);
    
          const existing = fontMap.get(baseFontName);
          if (existing) {
            if (!existing.pagesUsed.includes(pageNum)) {
              existing.pagesUsed.push(pageNum);
            }
          } else {
            fontMap.set(baseFontName, {
              name: baseFontName,
              type: subtype,
              encoding,
              isEmbedded,
              isSubset,
              pagesUsed: [pageNum],
            });
          }
        }
      }
    
      return { fontMap, pagesScanned: pages.length };
    }
  • Helper that formats the FontsAnalysis object into a Markdown table with summary stats and per-font details.
    export function formatFontsMarkdown(analysis: FontsAnalysis): string {
      const lines: string[] = ['# Font Analysis', ''];
    
      lines.push(`- **Total Fonts**: ${analysis.totalFontCount}`);
      lines.push(`- **Embedded**: ${analysis.embeddedCount}`);
      lines.push(`- **Subset**: ${analysis.subsetCount}`);
      lines.push(`- **Pages Scanned**: ${analysis.pagesScanned}`);
    
      if (analysis.fonts.length === 0) {
        lines.push('', 'No fonts found in this document.');
        if (analysis.note) {
          lines.push('', '## Note', '', `> ${analysis.note}`);
        }
        return lines.join('\n');
      }
    
      lines.push('', '## Font Details', '');
      lines.push('| Name | Type | Encoding | Embedded | Subset | Pages |', '|---|---|---|---|---|---|');
      for (const f of analysis.fonts) {
        const pages =
          f.pagesUsed.length > 5 ? `${f.pagesUsed.slice(0, 5).join(',')}...` : f.pagesUsed.join(',');
        lines.push(
          `| ${f.name} | ${f.type} | ${f.encoding ?? '-'} | ${f.isEmbedded ? 'Yes' : 'No'} | ${f.isSubset ? 'Yes' : 'No'} | ${pages} |`,
        );
      }
    
      if (analysis.note) {
        lines.push('', '## Note', '', `> ${analysis.note}`);
      }
    
      return lines.join('\n');
    }
Behavior4/5

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

Annotations indicate read-only, non-destructive, idempotent behavior. Description adds value by detailing what properties are returned (name, type, encoding, embedded/subset status, pages), which is beyond annotation scope. No contradiction.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with summary, Args, Returns, Examples. Front-loaded with clear purpose. Each section is concise and informative, though the examples could be slightly tighter.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no output schema, description adequately covers return data. Context of multiple siblings is addressed by specific use-case examples. Sufficient for an agent to understand tool purpose and output.

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?

Schema coverage is 100%, so baseline 3. Description largely repeats schema for file_path and response_format, but the Returns section explains the output structure, adding some semantic value beyond schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool lists all fonts in a PDF with properties. It provides specific verb ('List') and resource ('fonts used in a PDF document'), and distinguishes from sibling tools (e.g., extract_tables, read_text) by targeting a unique aspect of PDF content.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Examples explicitly state when to use: checking font embedding for PDF/A/X compliance, identifying font types/encodings, finding pages using specific fonts. While no explicit exclusions or alternatives are given, the examples give clear context for typical use cases relative to siblings.

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/shuji-bonji/pdf-reader-mcp'

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