Skip to main content
Glama

extract_svg

Extract SVG components from React/TypeScript/JavaScript files into individual .svg files, preserving SVG structure and removing React-specific code.

Instructions

Extract SVG components from React/TypeScript/JavaScript files into individual .svg files. This tool will preserve the SVG structure and attributes while removing React-specific code. By default, the source file will be replaced with "MIGRATED TO " and a warning message after successful extraction, making it easy to track where the SVGs were moved to. This behaviour can be disabled by setting the DISABLE_SOURCE_REPLACEMENT environment variable to 'true'. The warning message can be customized by setting the WARNING_MESSAGE environment variable.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourcePathYesPath to the source file containing SVG components
targetDirYesDirectory where the SVG files should be written

Implementation Reference

  • src/index.ts:80-97 (registration)
    Registration of the 'extract_svg' tool with its name, description, and inputSchema (requiring sourcePath and targetDir)
    {
      name: 'extract_svg',
      description: 'Extract SVG components from React/TypeScript/JavaScript files into individual .svg files. This tool will preserve the SVG structure and attributes while removing React-specific code. By default, the source file will be replaced with "MIGRATED TO <target absolute path>" and a warning message after successful extraction, making it easy to track where the SVGs were moved to. This behaviour can be disabled by setting the DISABLE_SOURCE_REPLACEMENT environment variable to \'true\'. The warning message can be customized by setting the WARNING_MESSAGE environment variable.',
      inputSchema: {
        type: 'object',
        properties: {
          sourcePath: {
            type: 'string',
            description: 'Path to the source file containing SVG components',
          },
          targetDir: {
            type: 'string',
            description: 'Directory where the SVG files should be written',
          },
        },
        required: ['sourcePath', 'targetDir'],
      },
    },
  • Handler for the 'extract_svg' tool: reads the source file, calls extractSvgs() to parse the AST, writes each SVG to a .svg file in targetDir, and optionally replaces the source file with a migration message
    } else if (request.params.name === 'extract_svg') {
      const { targetDir } = request.params.arguments as { targetDir: string };
      const svgs = await this.extractSvgs(sourceCode);
    
      // Create target directory if it doesn't exist
      await fs.mkdir(targetDir, { recursive: true });
    
      // Write each SVG to a separate file
      for (const svg of svgs) {
        const filePath = path.join(targetDir, `${svg.name}.svg`);
        await fs.writeFile(filePath, svg.content, 'utf-8');
      }
    
      // Replace source file content with migration message if not disabled
      if (!DISABLE_SOURCE_REPLACEMENT) {
        const absoluteTargetDir = path.resolve(targetDir);
        await fs.writeFile(
          sourcePath,
          `MIGRATED TO ${absoluteTargetDir}${WARNING_MESSAGE}`,
          'utf-8'
        );
      }
    
      return {
        content: [
          {
            type: 'text',
            text: `Successfully extracted ${svgs.length} SVG components to ${path.resolve(targetDir)}${
              !DISABLE_SOURCE_REPLACEMENT ? `. Source file replaced with "MIGRATED TO ${path.resolve(targetDir)}"` : ''
            }`,
          },
        ],
      };
  • extractSvgs() helper: parses source code with @babel/parser (TypeScript + JSX), traverses the AST to find arrow function variables returning JSX, and collects SVGs with their names and content
    private async extractSvgs(sourceCode: string): Promise<SvgExtraction[]> {
      const ast = parser.parse(sourceCode, {
        sourceType: 'module',
        plugins: ['typescript', 'jsx'],
      });
    
      const svgs: SvgExtraction[] = [];
    
      traverse(ast, {
        VariableDeclaration(path: NodePath<t.VariableDeclaration>) {
          const declaration = path.node.declarations[0];
          if (t.isVariableDeclarator(declaration) &&
              t.isIdentifier(declaration.id) &&
              t.isArrowFunctionExpression(declaration.init)) {
    
            // Look for JSX in the arrow function body
            const body = declaration.init.body;
            if (t.isJSXElement(body)) {
              const svgContent = this.extractSvgContent(body);
              if (svgContent) {
                svgs.push({
                  name: declaration.id.name,
                  content: svgContent
                });
              }
            }
          }
        }
      });
    
      return svgs;
    }
  • extractSvgContent() helper: converts a JSXElement (if it's an <svg> element) into an SVG string by extracting attributes and child elements, removing React-specific JSX wrappers
    private extractSvgContent(jsxElement: t.JSXElement): string | null {
      // Check if this is an SVG element
      if (t.isJSXIdentifier(jsxElement.openingElement.name) &&
          jsxElement.openingElement.name.name.toLowerCase() === 'svg') {
    
        // Convert JSX attributes to string
        const attributes = jsxElement.openingElement.attributes
          .map(attr => {
            if (t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name)) {
              const name = attr.name.name;
              if (t.isStringLiteral(attr.value)) {
                return `${name}="${attr.value.value}"`;
              } else if (t.isJSXExpressionContainer(attr.value) &&
                        t.isStringLiteral(attr.value.expression)) {
                return `${name}="${attr.value.expression.value}"`;
              }
            }
            return '';
          })
          .filter(Boolean)
          .join(' ');
    
        // Convert children to string
        const children = jsxElement.children
          .map(child => {
            if (t.isJSXElement(child)) {
              const elementName = (child.openingElement.name as t.JSXIdentifier).name;
              const childAttributes = child.openingElement.attributes
                .map(attr => {
                  if (t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name)) {
                    const name = attr.name.name;
                    if (t.isStringLiteral(attr.value)) {
                      return `${name}="${attr.value.value}"`;
                    }
                  }
                  return '';
                })
                .filter(Boolean)
                .join(' ');
    
              return `<${elementName} ${childAttributes}>${child.children
                .map(c => t.isJSXText(c) ? c.value : '')
                .join('')}</${elementName}>`;
            }
            return '';
          })
          .join('\n    ');
    
        return `<svg ${attributes}>\n    ${children}\n</svg>`;
      }
      return null;
    }
  • Input schema for the 'extract_svg' tool defining the expected arguments: sourcePath (string) and targetDir (string), both required
    inputSchema: {
      type: 'object',
      properties: {
        sourcePath: {
          type: 'string',
          description: 'Path to the source file containing SVG components',
        },
        targetDir: {
          type: 'string',
          description: 'Directory where the SVG files should be written',
        },
      },
      required: ['sourcePath', 'targetDir'],
    },
Behavior3/5

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

Discloses key behavior: source file replacement by default and ability to disable/customize via environment variables. With no annotations, the description carries full burden; it could be more comprehensive (e.g., what happens if target directory doesn't exist, handling of multiple SVGs).

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?

Five sentences are well-structured, front-loaded with purpose, then preservation, then default behavior and customization options. No redundant information.

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

Completeness3/5

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

Given no output schema, no annotations, and 2 params, the description is fairly complete but lacks mention of return values or failure modes. Could also note if it handles one or multiple SVGs per file.

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?

Input schema has 100% coverage with clear param descriptions. The description adds minimal extra meaning beyond what schema already provides (e.g., implying sourcePath is a code file). Baseline of 3 is appropriate.

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 verb 'Extract' and the resource 'SVG components from React/TypeScript/JavaScript files' with output to 'individual .svg files'. It distinguishes from the sibling tool 'extract_data' by specifying 'SVG components'.

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?

Provides clear context for when to use (extract SVGs from code files) and details about default source file replacement and environment variables to control behavior. However, it doesn't explicitly mention when not to use or compare with alternatives.

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/sammcj/mcp-data-extractor'

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