Skip to main content
Glama

extract_data

Extract embedded data like i18n translations from source code into a structured JSON file, replacing the original file with a migration warning to track moved data.

Instructions

Extract data content (e.g. i18n translations) from source code to a JSON file. IMPORTANT: When encountering files with data such as i18n content embedded in code, use this tool directly instead of reading the file content first. This tool will programmatically extract all translations into a structured JSON file, preserving nested objects, arrays, template variables, and formatting. This helps keep translations as configuration and prevents filling up the AI context window with translation content. 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 data was 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 data inside code
targetPathYesPath where the resulting JSON file should be written

Implementation Reference

  • The `extractDataContent` method is the core handler that parses source code using Babel, traverses the AST looking for export default declarations that are object expressions, processes nested objects/arrays, and extracts string literal or template literal values into a flat key-value record (e.g., 'key.subkey' format).
    private async extractDataContent(sourceCode: string): Promise<Record<string, string | string[] | Array<Record<string, string | string[]>>>> {
      const ast = parser.parse(sourceCode, {
        sourceType: 'module',
        plugins: ['typescript', 'jsx'],
      });
    
      const result: Record<string, any> = {};
    
      const processValue = (value: t.Node, currentPath: string[]): void => {
        if (t.isStringLiteral(value) || t.isTemplateLiteral(value)) {
          const extractedValue = this.extractStringValue(value);
          if (extractedValue !== null && extractedValue.trim() !== '') {
            result[this.buildKey(currentPath)] = extractedValue;
          }
        } else if (t.isArrayExpression(value)) {
          value.elements.forEach((element, index) => {
            if (!element) return;
    
            if (t.isStringLiteral(element) || t.isTemplateLiteral(element)) {
              const extractedValue = this.extractStringValue(element);
              if (extractedValue !== null && extractedValue.trim() !== '') {
                result[`${this.buildKey(currentPath)}.${index}`] = extractedValue;
              }
            } else if (t.isObjectExpression(element)) {
              processObject(element, [...currentPath, index.toString()]);
            }
          });
        } else if (t.isObjectExpression(value)) {
          processObject(value, currentPath);
        }
      };
    
      const processObject = (obj: t.ObjectExpression, parentPath: string[] = []): void => {
        obj.properties.forEach(prop => {
          if (!t.isObjectProperty(prop)) return;
    
          const key = t.isIdentifier(prop.key) ? prop.key.name :
                     t.isStringLiteral(prop.key) ? prop.key.value : null;
    
          if (!key) return;
    
          const currentPath = [...parentPath, key];
          processValue(prop.value, currentPath);
        });
      };
    
      traverse(ast, {
        ExportDefaultDeclaration(path: NodePath<t.ExportDefaultDeclaration>) {
          const declaration = path.node.declaration;
          if (t.isObjectExpression(declaration)) {
            processObject(declaration);
          }
        }
      });
    
      return result;
    }
  • The `CallToolRequestSchema` handler for 'extract_data': reads the source file, calls `extractDataContent`, writes the result as a JSON file, and optionally replaces the source file with a migration notice.
    if (request.params.name === 'extract_data') {
      const { targetPath } = request.params.arguments as { targetPath: string };
      const dataContent = await this.extractDataContent(sourceCode);
    
      // Create target directory if it doesn't exist
      await fs.mkdir(path.dirname(targetPath), { recursive: true });
    
      // Write extracted content to JSON file
      await fs.writeFile(
        targetPath,
        JSON.stringify(dataContent, null, 2),
        'utf-8'
      );
    
      // Replace source file content with migration message if not disabled
      if (!DISABLE_SOURCE_REPLACEMENT) {
        const absoluteTargetPath = path.resolve(targetPath);
        await fs.writeFile(
          sourcePath,
          `MIGRATED TO ${absoluteTargetPath}${WARNING_MESSAGE}`,
          'utf-8'
        );
      }
    
      return {
        content: [
          {
            type: 'text',
            text: `Successfully extracted ${Object.keys(dataContent).length} data entries to ${path.resolve(targetPath)}${
              !DISABLE_SOURCE_REPLACEMENT ? `. Source file replaced with "MIGRATED TO ${path.resolve(targetPath)}"` : ''
            }`,
          },
        ],
      };
  • src/index.ts:62-79 (registration)
    Tool registration for 'extract_data' in the `ListToolsRequestSchema` handler: defines the tool name, description, and input schema (sourcePath and targetPath required strings).
    {
      name: 'extract_data',
      description: 'Extract data content (e.g. i18n translations) from source code to a JSON file. IMPORTANT: When encountering files with data such as i18n content embedded in code, use this tool directly instead of reading the file content first. This tool will programmatically extract all translations into a structured JSON file, preserving nested objects, arrays, template variables, and formatting. This helps keep translations as configuration and prevents filling up the AI context window with translation content. 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 data was 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 data inside code',
          },
          targetPath: {
            type: 'string',
            description: 'Path where the resulting JSON file should be written',
          },
        },
        required: ['sourcePath', 'targetPath'],
      },
    },
  • The `DataExtraction` interface defining the shape of extracted data entries (key and value strings).
    interface DataExtraction {
      key: string;
      value: string;
    }
  • The `buildKey` helper method that joins path parts with dots (e.g., ['key', 'subkey'] -> 'key.subkey').
    private buildKey(parts: string[]): string {
      return parts.join('.');
    }
Behavior5/5

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

With no annotations, the description fully discloses behavioral traits: it states the source file will be replaced with a 'MIGRATED TO ...' message and that this can be disabled via environment variable. It also mentions customizing the warning message. This gives the agent clear expectations of side effects.

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?

The description is slightly longer but every sentence is purposeful: it explains the core action, usage directive, benefits, side effects, and configuration. It is front-loaded and well-structured, though could be slightly trimmed without losing value.

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 and a tool with side effects, the description covers usage, behavior, and configuration. It explains what happens after extraction (file replacement) and how to control it. It could explicitly mention the return value (the JSON file written) but it is implied.

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% with clear descriptions. The description adds minimal semantic value beyond the schema; it repeats the purpose but does not provide new details about parameter formats or constraints. Baseline 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?

Clearly states it extracts data content (e.g., i18n translations) from source code to a JSON file. The verb 'extract' and resource 'data content from source code to JSON file' are specific, and it distinguishes from sibling 'extract_svg' by focusing on code data rather than SVG.

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 explicit usage guidance: 'When encountering files with data such as i18n content embedded in code, use this tool directly instead of reading the file content first.' It explains why (prevents filling context window) but does not explicitly mention when not to use or 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