Skip to main content
Glama

import_collection

Import API requests from collection files. Auto-detect .atm/ directory or specify a file path.

Instructions

Importa requests desde .atm/collection.json o un archivo específico. Auto-detecta .atm/ en el proyecto.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileNoRuta al archivo (default: busca en .atm/collection.json)
tagNoTag adicional para aplicar a todos los requests importados
overwriteNoSobreescribir requests existentes con el mismo nombre (default: false)

Implementation Reference

  • The handler function for the import_collection tool. Reads a collection.json file, validates its format, iterates over SavedRequest entries, optionally skips existing ones or overwrites, adds an extra tag if provided, and saves each request via storage.saveCollection().
    async (params) => {
      try {
        // Auto-detect file
        const filePath = await findFile(params.file, 'collection.json')
        if (!filePath) {
          return {
            content: [
              {
                type: 'text' as const,
                text: 'No se encontró collection.json. Busqué en .atm/ y en el directorio actual.\nEspecifica la ruta con el parámetro "file".',
              },
            ],
            isError: true,
          }
        }
    
        const raw = await readFile(filePath, 'utf-8')
        const bundle = JSON.parse(raw)
    
        if (bundle._format !== 'api-testing-mcp' || !Array.isArray(bundle.requests)) {
          return {
            content: [
              {
                type: 'text' as const,
                text: 'Error: El archivo no es un export nativo válido. Verifica que fue generado con export_collection.',
              },
            ],
            isError: true,
          }
        }
    
        const overwrite = params.overwrite ?? false
        const extraTag = params.tag
        let imported = 0
        let skipped = 0
        const errors: string[] = []
    
        for (const req of bundle.requests as SavedRequest[]) {
          try {
            if (!req.name || !req.request) {
              errors.push(`Request sin nombre o configuración — omitido`)
              continue
            }
    
            if (!overwrite) {
              const existing = await storage.getCollection(req.name)
              if (existing) {
                skipped++
                continue
              }
            }
    
            // Add extra tag if provided
            if (extraTag) {
              const tags = req.tags ?? []
              if (!tags.includes(extraTag)) tags.push(extraTag)
              req.tags = tags
            }
    
            // Update timestamp
            req.updatedAt = new Date().toISOString()
    
            await storage.saveCollection(req)
            imported++
          } catch (err) {
            const msg = err instanceof Error ? err.message : String(err)
            errors.push(`${req.name ?? 'unknown'}: ${msg}`)
          }
        }
    
        const lines: string[] = [
          `Colección importada: ${imported} requests guardados (desde ${filePath}).`,
        ]
        if (skipped > 0) lines.push(`${skipped} requests omitidos (ya existían, usa overwrite: true para sobreescribir).`)
        if (errors.length > 0) {
          lines.push(`${errors.length} errores:`)
          for (const e of errors) lines.push(`  - ${e}`)
        }
    
        return {
          content: [{ type: 'text' as const, text: lines.join('\n') }],
        }
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error)
        return {
          content: [{ type: 'text' as const, text: `Error: ${message}` }],
          isError: true,
        }
      }
    },
  • Zod schema for tool inputs: file (optional string), tag (optional string), overwrite (optional boolean).
      file: z
        .string()
        .optional()
        .describe('Ruta al archivo (default: busca en .atm/collection.json)'),
      tag: z
        .string()
        .optional()
        .describe('Tag adicional para aplicar a todos los requests importados'),
      overwrite: z
        .boolean()
        .optional()
        .describe('Sobreescribir requests existentes con el mismo nombre (default: false)'),
    },
  • Registration of the 'import_collection' tool on the MCP server with name, description, input schema, and handler callback.
    server.tool(
      'import_collection',
      'Importa requests desde .atm/collection.json o un archivo específico. Auto-detecta .atm/ en el proyecto.',
      {
        file: z
          .string()
          .optional()
          .describe('Ruta al archivo (default: busca en .atm/collection.json)'),
        tag: z
          .string()
          .optional()
          .describe('Tag adicional para aplicar a todos los requests importados'),
        overwrite: z
          .boolean()
          .optional()
          .describe('Sobreescribir requests existentes con el mismo nombre (default: false)'),
      },
      async (params) => {
        try {
          // Auto-detect file
          const filePath = await findFile(params.file, 'collection.json')
          if (!filePath) {
            return {
              content: [
                {
                  type: 'text' as const,
                  text: 'No se encontró collection.json. Busqué en .atm/ y en el directorio actual.\nEspecifica la ruta con el parámetro "file".',
                },
              ],
              isError: true,
            }
          }
    
          const raw = await readFile(filePath, 'utf-8')
          const bundle = JSON.parse(raw)
    
          if (bundle._format !== 'api-testing-mcp' || !Array.isArray(bundle.requests)) {
            return {
              content: [
                {
                  type: 'text' as const,
                  text: 'Error: El archivo no es un export nativo válido. Verifica que fue generado con export_collection.',
                },
              ],
              isError: true,
            }
          }
    
          const overwrite = params.overwrite ?? false
          const extraTag = params.tag
          let imported = 0
          let skipped = 0
          const errors: string[] = []
    
          for (const req of bundle.requests as SavedRequest[]) {
            try {
              if (!req.name || !req.request) {
                errors.push(`Request sin nombre o configuración — omitido`)
                continue
              }
    
              if (!overwrite) {
                const existing = await storage.getCollection(req.name)
                if (existing) {
                  skipped++
                  continue
                }
              }
    
              // Add extra tag if provided
              if (extraTag) {
                const tags = req.tags ?? []
                if (!tags.includes(extraTag)) tags.push(extraTag)
                req.tags = tags
              }
    
              // Update timestamp
              req.updatedAt = new Date().toISOString()
    
              await storage.saveCollection(req)
              imported++
            } catch (err) {
              const msg = err instanceof Error ? err.message : String(err)
              errors.push(`${req.name ?? 'unknown'}: ${msg}`)
            }
          }
    
          const lines: string[] = [
            `Colección importada: ${imported} requests guardados (desde ${filePath}).`,
          ]
          if (skipped > 0) lines.push(`${skipped} requests omitidos (ya existían, usa overwrite: true para sobreescribir).`)
          if (errors.length > 0) {
            lines.push(`${errors.length} errores:`)
            for (const e of errors) lines.push(`  - ${e}`)
          }
    
          return {
            content: [{ type: 'text' as const, text: lines.join('\n') }],
          }
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error)
          return {
            content: [{ type: 'text' as const, text: `Error: ${message}` }],
            isError: true,
          }
        }
      },
    )
  • Helper function findFile used by import_collection to auto-detect the collection.json file path (checks .atm/ subdirectory and current working directory).
    async function findFile(explicit: string | undefined, fileName: string): Promise<string | null> {
      if (explicit) return explicit
    
      const candidates = [
        join(process.cwd(), '.atm', fileName),
        join(process.cwd(), fileName),
      ]
    
      for (const candidate of candidates) {
        try {
          await access(candidate)
          return candidate
        } catch {
          // Not found, try next
        }
      }
    
      return null
    }
Behavior3/5

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

No annotations provided. Description covers basic import and auto-detection but omits details like overwrite behavior (though 'overwrite' param exists in schema), merge rules, or what happens to existing collections. Does not mention mutation or 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.

Conciseness5/5

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

Two sentences, no redundant words. Focused and efficient.

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?

No output schema and no description of return value or errors. For a tool with 3 params and no annotations, it leaves gaps: not specifying what happens after import (e.g., success indicator, returned data). Adequate but not fully complete.

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 parameter descriptions. The description adds context about auto-detection for the 'file' parameter but adds little beyond schema. 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?

The description clearly states it imports requests from .atm/collection.json or a specific file, with auto-detection. This differentiates it from sibling tools like import_environment or import_postman_collection.

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

Usage Guidelines3/5

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

No explicit guidance on when to use this tool versus alternatives (e.g., import_environment, import_postman_collection). The description implies it is for importing request collections but lacks context for appropriate use cases.

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/cocaxcode/api-testing-mcp'

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