{"version":3,"sources":["../src/utils/logger.ts","../src/server.ts","../src/config.ts","../src/utils/error.ts","../src/utils/error-handler.ts","../src/utils/tool-factory.ts","../src/utils/client-factory.ts","../src/tools/scrape.ts","../src/tools/map.ts","../src/index.ts"],"names":["logger_default","pino","createServer","options","port","tools","transportType","version","server","FastMCP","isRunning","tool","args","context","err","UserError","transportConfig","PACKAGE_VERSION","ServerConfigSchema","z","ApiConfigSchema","ConfigSchema","loadConfig","config","error","formattedErrors","formatErrorMessage","message","isNetworkError","isTimeoutError","ValidationError","handleError","contextStr","createTool","name","description","schema","execute","params","typedParams","createTextResponse","text","createJsonResponse","data","clientInstance","getClient","FirecrawlClient","scrapeToolSchema","scrapeTool","scrapeParams","result","mapToolSchema","mapTool","sitemapResult","urls","responseText","url","index","banner","main","setupShutdownHandlers"],"mappings":";;AAOA,IAAOA,CAAQC,CAAAA,kBAAAA,GCsBR,SAASC,CAAAA,CAAaC,CAAmC,CAAA,CAC9D,IAAMC,CAAAA,CAAOD,EAAQ,IAAQ,EAAA,IAAA,CACvBE,CAAQF,CAAAA,CAAAA,CAAQ,KAChBG,CAAAA,CAAAA,CAAgBH,EAAQ,aAAiB,EAAA,OAAA,CACzCI,EAAUJ,CAAQ,CAAA,OAAA,EAAW,QAG7BK,CAAS,CAAA,IAAIC,eAAQ,CAAA,CACzB,IAAM,CAAA,sBAAA,CACN,QAASF,CACX,CAAC,CAGGG,CAAAA,CAAAA,CAAY,KAGhB,CAAA,IAAA,IAAWC,KAAQN,CACjBG,CAAAA,CAAAA,CAAO,OAAQ,CAAA,CACb,IAAMG,CAAAA,CAAAA,CAAK,KACX,WAAaA,CAAAA,CAAAA,CAAK,YAClB,UAAYA,CAAAA,CAAAA,CAAK,WACjB,OAAS,CAAA,MAAOC,CAAeC,CAAAA,CAAAA,GAAY,CACzC,GAAI,CACF,OAAAb,CAAAA,CAAO,IAAK,CAAA,CAAA,gBAAA,EAAmBW,CAAK,CAAA,IAAI,GAAI,CAAE,QAAA,CAA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firecrawl Simple MCP server\n */\n\nimport pino from 'pino';\n\n// Export Pino directly for use in other files\nexport default pino();\n","/**\n * Simplified FastMCP server implementation for Firecrawl Simple\n */\n\nimport { FastMCP, UserError, Tool } from 'fastmcp';\nimport logger from './utils/logger';\n\n/**\n * Server options for the Firecrawl MCP server\n */\nexport interface ServerOptions {\n  tools: Tool<undefined>[];\n  port?: number;\n  transportType?: 'stdio' | 'sse';\n  version?: string;\n}\n\n/**\n * MCP Server interface\n */\nexport interface McpServer {\n  start: () => Promise<void>;\n  stop: () => Promise<void>;\n  getPort: () => number;\n}\n\n/**\n * Create an MCP server using FastMCP\n */\nexport function createServer(options: ServerOptions): McpServer {\n  const port = options.port ?? 3003;\n  const tools = options.tools;\n  const transportType = options.transportType ?? 'stdio';\n  const version = options.version ?? '1.0.0';\n\n  // Create the FastMCP server\n  const server = new FastMCP({\n    name: 'Firecrawl Simple MCP',\n    version: version as `${number}.${number}.${number}`,\n  });\n\n  // Track if the server is running\n  let isRunning = false;\n\n  // Register all tools - directly using FastMCP Tool type\n  for (const tool of tools) {\n    server.addTool({\n      name: tool.name,\n      description: tool.description,\n      parameters: tool.parameters,\n      execute: async (args: unknown, context) => {\n        try {\n          logger.info(`Executing tool: ${tool.name}`, { toolName: tool.name });\n          // Pass both args and context to the tool's execute function\n          return await tool.execute(args, context);\n        } catch (err: unknown) {\n          // If it's already a UserError, just rethrow it\n          if (err instanceof UserError) {\n            throw err;\n          }\n\n          // Log the error\n          logger.error(`Error executing tool ${tool.name}`, err, { toolName: tool.name });\n\n          // Rethrow the error\n          throw err;\n        }\n      },\n    });\n  }\n\n  return {\n    /**\n     * Start the server\n     */\n    start: async () => {\n      if (isRunning) {\n        logger.warn('Server is already running');\n        return;\n      }\n\n      try {\n        // Configure transport based on options\n        const transportConfig =\n          transportType === 'sse'\n            ? {\n                transportType: 'sse' as const,\n                sse: {\n                  endpoint: '/sse' as `/${string}`,\n                  port: port,\n                },\n              }\n            : { transportType: 'stdio' as const };\n\n        // Start the server with configured transport\n        await server.start(transportConfig);\n        isRunning = true;\n\n        logger.info(`MCP Server started successfully with ${transportType} transport`, {\n          transportType,\n        });\n        if (transportType === 'sse') {\n          logger.info(`Server listening on port ${String(port)}`, { port });\n        }\n      } catch (err: unknown) {\n        logger.error('Failed to start MCP Server', err);\n        throw new Error(`Server start failed: ${err instanceof Error ? err.message : String(err)}`);\n      }\n    },\n\n    /**\n     * Stop the server\n     */\n    stop: async () => {\n      if (!isRunning) {\n        logger.warn('Server is not running');\n        return;\n      }\n\n      try {\n        await server.stop();\n\n        // Mark server as stopped\n        isRunning = false;\n\n        logger.info('MCP Server stopped');\n      } catch (err: unknown) {\n        logger.error('Failed to stop MCP Server', err);\n        throw new Error(`Server stop failed: ${err instanceof Error ? err.message : String(err)}`);\n      }\n    },\n\n    /**\n     * Get the server port\n     */\n    getPort: () => {\n      return port;\n    },\n  };\n}\n","/**\n * Simplified configuration module for the Firecrawl Simple MCP server\n */\n\nimport { z } from 'zod';\nimport logger from './utils/logger';\n\n// The version is injected at build time by esbuild define\n// This approach doesn't rely on filesystem access at runtime\n// At build time, esbuild replaces process.env.PACKAGE_VERSION with the actual version string\n// When used as a dependency, this will be the version that was published\nconst PACKAGE_VERSION = process.env.PACKAGE_VERSION ?? '1.0.0';\n\n/**\n * Server configuration schema\n */\nexport const ServerConfigSchema = z.object({\n  port: z.number().int().positive().default(3003),\n  transportType: z.enum(['stdio', 'sse']).default('stdio'),\n  logLevel: z.enum(['DEBUG', 'INFO', 'WARN', 'ERROR']).default('INFO'),\n});\n\n/**\n * API configuration schema\n */\nexport const ApiConfigSchema = z.object({\n  url: z.string().url().default('http://localhost:3002/v1'),\n  key: z.string().optional(),\n  timeout: z.number().int().positive().default(30000),\n});\n\n/**\n * Complete configuration schema\n */\nexport const ConfigSchema = z.object({\n  version: z.string().default('1.0.0'),\n  api: ApiConfigSchema,\n  server: ServerConfigSchema,\n});\n\n/**\n * Configuration type\n */\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/**\n * Load configuration from environment variables with validation\n */\nexport function loadConfig(): Config {\n  try {\n    // Create a configuration object from environment variables\n    const config = {\n      // Version is injected at build time by esbuild define\n      version: PACKAGE_VERSION,\n      api: {\n        url: process.env.FIRECRAWL_API_URL ?? 'http://localhost:3002/v1',\n        key: process.env.FIRECRAWL_API_KEY,\n        timeout: parseInt(process.env.FIRECRAWL_API_TIMEOUT ?? '30000', 10),\n      },\n      server: {\n        port: parseInt(process.env.FIRECRAWL_SERVER_PORT ?? '3003', 10),\n        transportType: (process.env.FIRECRAWL_TRANSPORT_TYPE ?? 'stdio') as 'stdio' | 'sse',\n        logLevel: (process.env.FIRECRAWL_LOG_LEVEL ?? 'INFO') as\n          | 'DEBUG'\n          | 'INFO'\n          | 'WARN'\n          | 'ERROR',\n      },\n    };\n\n    // Validate the configuration using Zod\n    return ConfigSchema.parse(config);\n  } catch (error) {\n    if (error instanceof z.ZodError) {\n      // Provide more helpful error messages for configuration issues\n      const formattedErrors = error.errors\n        .map(err => {\n          const path = err.path.join('.');\n          return `  - ${path}: ${err.message}`;\n        })\n        .join('\\n');\n\n      logger.error({ err: error }, `Configuration validation errors:\\n${formattedErrors}`);\n    } else {\n      logger.error(\n        { err: error },\n        'Configuration error: ' + (error instanceof Error ? error.message : String(error)),\n      );\n    }\n\n    // Fall back to default configuration\n    logger.info('Using default configuration');\n    return ConfigSchema.parse({});\n  }\n}\n\n// Export the validated configuration\nexport const config = loadConfig();\n","/**\n * Simplified error handling utilities for the Firecrawl Simple MCP server\n */\nimport { UserError } from 'fastmcp';\nimport logger from './logger';\n\n/**\n * Error types that can be handled\n */\nexport enum ErrorType {\n  VALIDATION = 'validation',\n  API = 'api',\n  NETWORK = 'network',\n  TIMEOUT = 'timeout',\n  UNKNOWN = 'unknown',\n}\n\n/**\n * Format an error for MCP response\n * @param error The error to format\n * @returns Formatted error message\n */\nexport function formatErrorMessage(error: unknown): string {\n  if (error instanceof Error) {\n    const message = error.message;\n\n    // Check for specific error types based on message content\n    if (message.toLowerCase().includes('validation')) {\n      return `Validation Error: ${message}`;\n    }\n\n    if (message.toLowerCase().includes('api')) {\n      return `API Error: ${message}`;\n    }\n\n    if (isNetworkError(error)) {\n      return `Network Error: ${message}. Please check your connection and try again.`;\n    }\n\n    if (isTimeoutError(error)) {\n      return `Timeout Error: ${message}. Please try again with a longer timeout or a simpler request.`;\n    }\n\n    return `Error: ${message}`;\n  }\n\n  return 'An unknown error occurred';\n}\n\n/**\n * Create a UserError from any error type\n * @param error The original error\n * @param context Additional context for the error\n * @returns A UserError instance\n */\nexport function createUserError(\n  error: unknown,\n  context?: { toolName?: string; operation?: string },\n): UserError {\n  const message = formatErrorMessage(error);\n  const contextStr = context\n    ? `${context.toolName ? ` in ${context.toolName}` : ''}${context.operation ? ` during ${context.operation}` : ''}`\n    : '';\n\n  // Log the error with context\n  logger.error({ err: error, ...context }, `Error${contextStr}`);\n\n  // Return a UserError that FastMCP can handle properly\n  return new UserError(message);\n}\n\n/**\n * Check if an error is a network error\n */\nfunction isNetworkError(error: Error): boolean {\n  const message = error.message.toLowerCase();\n  return (\n    message.includes('econnrefused') ||\n    message.includes('econnreset') ||\n    message.includes('socket hang up') ||\n    message.includes('network')\n  );\n}\n\n/**\n * Check if an error is a timeout error\n */\nfunction isTimeoutError(error: Error): boolean {\n  const message = error.message.toLowerCase();\n  return (\n    message.includes('timeout') || message.includes('timed out') || message.includes('etimedout')\n  );\n}\n\n/**\n * Custom error class for validation errors\n */\nexport class ValidationError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = 'ValidationError';\n  }\n}\n","/**\n * Simplified error handling for the Firecrawl Simple MCP server\n */\n\nimport { ContentResult } from 'fastmcp';\nimport { formatErrorMessage } from './error';\nimport logger from './logger';\n\n/**\n * Handle errors in MCP tools consistently\n * @param error The error to handle\n * @param context The error context\n * @returns A formatted MCP tool response with error information\n */\nexport function handleError(\n  error: unknown,\n  context: { toolName: string; operation?: string; input?: unknown },\n): ContentResult {\n  // Log the error with context\n  const contextStr = context.operation ? ` during ${context.operation}` : '';\n  logger.error(`Error in ${context.toolName}${contextStr}`, error, {\n    toolName: context.toolName,\n    operation: context.operation,\n    input: context.input,\n  });\n\n  // Format the error message\n  const errorMessage = formatErrorMessage(error);\n\n  // Return a standardized error response\n  return {\n    content: [\n      {\n        type: 'text',\n        text: errorMessage,\n      },\n    ],\n    isError: true,\n  };\n}\n","/**\n * Tool factory for creating MCP tools with consistent patterns\n */\n\nimport { z } from 'zod';\nimport { ContentResult, Tool, ToolParameters } from 'fastmcp';\nimport { handleError } from './error-handler';\nimport logger from './logger';\n\n/**\n * Options for creating a tool\n */\nexport interface CreateToolOptions<T> {\n  name: string;\n  description: string;\n  schema: z.ZodType<T>;\n  execute: (params: T) => Promise<ContentResult>;\n}\n\n/**\n * Create an MCP tool with consistent error handling and logging\n * @param options Tool creation options\n * @returns An MCP tool definition\n */\nexport function createTool<T>({\n  name,\n  description,\n  schema,\n  execute,\n}: CreateToolOptions<T>): Tool<undefined> {\n  return {\n    name,\n    description,\n    parameters: schema as unknown as ToolParameters,\n    execute: async (params: unknown): Promise<ContentResult> => {\n      try {\n        // Parse and validate params with Zod\n        const typedParams = schema.parse(params);\n        logger.info({ params: typedParams }, `Executing ${name} tool`);\n\n        // Execute the tool-specific logic\n        return await execute(typedParams);\n      } catch (error) {\n        // Handle errors consistently\n        return handleError(error, {\n          toolName: name,\n          operation: 'execution',\n        });\n      }\n    },\n  };\n}\n\n/**\n * Create a text response for MCP\n * @param text The text content\n * @returns An MCP tool response\n */\nexport function createTextResponse(text: string): ContentResult {\n  return {\n    content: [\n      {\n        type: 'text',\n        text,\n      },\n    ],\n    isError: false,\n  };\n}\n\n/**\n * Create a JSON response for MCP\n * @param data The data to format as JSON\n * @returns An MCP tool response\n */\nexport function createJsonResponse(data: unknown): ContentResult {\n  return createTextResponse(JSON.stringify(data, null, 2));\n}\n","/**\n * Client factory for creating and reusing FirecrawlClient instances\n */\n\nimport { FirecrawlClient } from 'firecrawl-simple-client';\nimport { config } from '../config';\nimport logger from './logger';\n\n// Singleton instance of the client\nlet clientInstance: FirecrawlClient | null = null;\n\n/**\n * Get a FirecrawlClient instance\n * This factory ensures we only create one client instance per process\n * @returns A FirecrawlClient instance\n */\nexport function getClient(): FirecrawlClient {\n  if (!clientInstance) {\n    logger.debug('Creating new FirecrawlClient instance');\n    // Create a new client with the configuration from config.ts\n    clientInstance = new FirecrawlClient({\n      apiUrl: config.api.url,\n      apiKey: config.api.key,\n    });\n  }\n\n  return clientInstance;\n}\n\n/**\n * Reset the client instance\n * Useful for testing or when configuration changes\n */\nexport function resetClient(): void {\n  clientInstance = null;\n}\n","/**\n * Firecrawl MCP Tool: Scrape content from a URL with JavaScript rendering support.\n *\n * Defines the schema and implementation for the `firecrawl_scrape` tool,\n * which retrieves webpage content in various formats, optionally including\n * specific HTML tags, custom headers, and JavaScript execution delay.\n */\n\nimport { z } from 'zod';\nimport { ContentResult } from 'fastmcp';\nimport { createTool, createJsonResponse } from '../utils/tool-factory';\nimport { getClient } from '../utils/client-factory';\nimport { ValidationError } from '../utils/error';\n\n/**\n * Schema for the `firecrawl_scrape` tool input parameters.\n */\nexport const scrapeToolSchema = z.object({\n  url: z.string().url().describe('The URL to scrape (required)'),\n  formats: z\n    .array(z.enum(['markdown', 'rawHtml', 'screenshot']))\n    .optional()\n    .default(['markdown'])\n    .describe('Formats to include in the output'),\n  includeTags: z\n    .array(z.string())\n    .optional()\n    .describe('HTML tags to include in the scraped result'),\n  excludeTags: z\n    .array(z.string())\n    .optional()\n    .describe('HTML tags to exclude from the scraped result'),\n  headers: z.record(z.string()).optional().describe('Custom HTTP headers to send with the request'),\n  waitFor: z\n    .number()\n    .optional()\n    .describe('Milliseconds to wait for JavaScript execution before scraping'),\n  timeout: z.number().optional().default(30000).describe('Request timeout in milliseconds'),\n});\n\n/**\n * The `firecrawl_scrape` MCP tool.\n *\n * Scrapes content from a URL with optional JavaScript rendering delay,\n * custom headers, and output formats.\n */\nexport const scrapeTool = createTool({\n  name: 'firecrawl_scrape',\n  description: 'Scrape content from a URL with JavaScript rendering support',\n  schema: scrapeToolSchema,\n  /**\n   * Executes the scrape operation.\n   *\n   * @param params - Validated input matching `scrapeToolSchema`\n   * @returns A promise resolving to the scraped content wrapped as a ContentResult\n   * @throws ValidationError if scraping fails or returns no result\n   */\n  async execute(params): Promise<ContentResult> {\n    // Prepare parameters for the underlying client\n    const scrapeParams = {\n      url: params.url,\n      formats: params.formats,\n      waitFor: params.waitFor,\n      timeout: params.timeout,\n      includeTags: params.includeTags,\n      excludeTags: params.excludeTags,\n      headers: params.headers,\n    };\n\n    const client = getClient();\n    const result = await client.scrapeWebpage(scrapeParams);\n\n    if (!result) {\n      throw new ValidationError('Failed to scrape webpage: No result returned');\n    }\n\n    return createJsonResponse(result);\n  },\n});\n","/**\n * MCP tool for mapping a site\n */\n\nimport { z } from 'zod';\nimport { ContentResult } from 'fastmcp';\nimport { createTool, createTextResponse } from '../utils/tool-factory';\nimport { getClient } from '../utils/client-factory';\nimport { ValidationError } from '../utils/error';\n\n/**\n * Zod schema defining the input parameters for the firecrawl_map tool.\n *\n * Parameters:\n * - url (string, required): The starting URL for sitemap generation.\n * - search (string, optional): A search query to filter or guide the mapping.\n * - ignoreSitemap (boolean, optional, default=true): Whether to ignore the site's existing sitemap.xml.\n * - includeSubdomains (boolean, optional, default=false): Whether to include subdomains in the crawl.\n * - limit (number, optional, default=5000): Maximum number of URLs to return.\n */\nexport const mapToolSchema = z.object({\n  url: z.string().url().describe('The URL to start mapping from (required)'),\n  search: z.string().optional().describe('Search query to use for mapping'),\n  ignoreSitemap: z\n    .boolean()\n    .optional()\n    .default(true)\n    .describe(\"Whether to ignore the website's sitemap\"),\n  includeSubdomains: z\n    .boolean()\n    .optional()\n    .default(false)\n    .describe('Include subdomains of the website'),\n  limit: z.number().optional().default(5000).describe('Maximum number of links to return'),\n});\n\n/**\n * The result returned from the sitemap generation client call.\n */\nexport interface SitemapResult {\n  success: boolean;\n  links?: string[];\n}\n\n/**\n * MCP tool definition for generating a sitemap of a website.\n *\n * This tool uses the Firecrawl client to crawl a website starting from the provided URL,\n * optionally filtering with a search query, and returns a list of discovered URLs formatted as markdown.\n *\n * The tool parameters are validated against `mapToolSchema`.\n * The response contains a markdown-formatted list of URLs or a message if no URLs were found.\n *\n * Throws:\n * - ValidationError if the sitemap generation fails or returns an invalid result.\n */\nexport const mapTool = createTool({\n  name: 'firecrawl_map',\n  description: 'Generate a sitemap of a given site',\n  schema: mapToolSchema,\n  execute: async (params): Promise<ContentResult> => {\n    // Get client and execute operation\n    const client = getClient();\n    const result = await client.generateSitemap({\n      url: params.url,\n      search: params.search,\n      ignoreSitemap: params.ignoreSitemap,\n      includeSubdomains: params.includeSubdomains,\n      limit: params.limit,\n    });\n\n    if (!result || typeof result !== 'object' || !('success' in result)) {\n      throw new ValidationError('Invalid sitemap result: missing success flag');\n    }\n\n    if (!result.success) {\n      throw new ValidationError('Sitemap generation failed');\n    }\n\n    const sitemapResult = result as SitemapResult;\n    const urls: string[] = Array.isArray(sitemapResult.links) ? sitemapResult.links : [];\n\n    // Format the response as markdown\n    let responseText = `# Sitemap for ${params.url}\\n\\n`;\n\n    if (urls.length === 0) {\n      responseText += 'No URLs found in the sitemap.\\n';\n    } else {\n      responseText += `Found ${String(urls.length)} URLs:\\n\\n`;\n      urls.forEach((url: string, index: number) => {\n        responseText += `${String(index + 1)}. ${url}\\n`;\n      });\n    }\n\n    const response = createTextResponse(responseText);\n    return response;\n  },\n});\n","#!/usr/bin/env node\n\n/**\n * Firecrawl Simple MCP Server\n *\n * A Model Context Protocol (MCP) server for Firecrawl Simple\n */\n\nimport { createServer } from './server';\nimport { config } from './config';\nimport logger from './utils/logger';\n\nimport { scrapeTool } from './tools/scrape';\nimport { mapTool } from './tools/map';\n\n// Banner\nconst banner = `\n╔═══════════════════════════════════════════════════════════╗\n║                                                           ║\n║   Firecrawl Simple MCP Server                             ║\n║   Web scraping capabilities for LLMs via MCP              ║\n║                                                           ║\n╚═══════════════════════════════════════════════════════════╝\n`;\n\n/**\n * Main function to start the MCP server\n */\nasync function main() {\n  // Logger is already initialized with configuration\n\n  logger.info(banner);\n  logger.info('Starting Firecrawl Simple MCP Server');\n  logger.info({ apiUrl: config.api.url }, `API URL: ${config.api.url}`);\n  logger.info({ version: config.version }, `Version: ${config.version}`);\n\n  // Define the MCP tools\n  const tools = [scrapeTool, mapTool];\n\n  // Create and start the MCP server with configuration\n  const server = createServer({\n    tools,\n    port: config.server.port,\n    transportType: config.server.transportType,\n    version: config.version,\n  });\n\n  // Set up graceful shutdown handlers\n  setupShutdownHandlers(server);\n\n  // Start the server\n  try {\n    await server.start();\n\n    logger.info('MCP Server started successfully');\n    logger.info('Available tools:');\n    tools.forEach(tool => {\n      logger.info(\n        { toolName: tool.name },\n        `- ${tool.name}: ${tool.description ?? 'No description'}`,\n      );\n    });\n  } catch (err) {\n    logger.error({ err }, 'Failed to start MCP Server');\n    process.exit(1);\n  }\n}\n\n/**\n * Set up handlers for graceful shutdown\n */\nfunction setupShutdownHandlers(server: { stop: () => Promise<void> }) {\n  // Handle graceful shutdown\n  process.on('SIGINT', () => {\n    logger.info('Shutting down MCP Server...');\n    void server\n      .stop()\n      .then(() => {\n        process.exit(0);\n      })\n      .catch((err: unknown) => {\n        logger.error({ err }, 'Error during shutdown');\n        process.exit(1);\n      });\n  });\n\n  process.on('SIGTERM', () => {\n    logger.info('Shutting down MCP Server...');\n    void server\n      .stop()\n      .then(() => {\n        process.exit(0);\n      })\n      .catch((err: unknown) => {\n        logger.error({ err }, 'Error during shutdown');\n        process.exit(1);\n      });\n  });\n}\n\n// Start the server\nmain().catch((err: unknown) => {\n  logger.error({ err }, 'Unhandled error');\n  process.exit(1);\n});\n"]}