Source Map Parser MCP Server
Analizador de mapas de origen
Este proyecto implementa un analizador de mapas de origen basado en WebAssembly que puede mapear los rastros de pila de errores de JavaScript al código fuente y extraer información de contexto relevante. Los desarrolladores pueden mapear fácilmente los rastros de pila de errores de JavaScript al código fuente para una rápida identificación y resolución de problemas. Esta documentación tiene como objetivo ayudar a los desarrolladores a comprender y utilizar mejor esta herramienta.
Integración MCP
Nota: Requiere compatibilidad con Node.js 18+
Opción 1: Ejecutar directamente con NPX
npx -y source-map-parser-mcp@latestOpción 2: Descargar los artefactos de compilación
Descargue la versión correspondiente de los artefactos de compilación desde la página de lanzamiento de GitHub y luego ejecute:
node dist/main.es.jsConfiguración de parámetros de tiempo de ejecución
Los parámetros de tiempo de ejecución del sistema se pueden configurar de forma flexible a través de variables de entorno para satisfacer las necesidades de diferentes escenarios.
SOURCE_MAP_PARSER_RESOURCE_CACHE_MAX_SIZE: Establece el espacio máximo de memoria ocupado por la caché de recursos; el valor predeterminado es 200 MB. Ajustar este valor correctamente puede equilibrar el rendimiento y el uso de memoria.SOURCE_MAP_PARSER_CONTEXT_OFFSET_LINE: Define el número de líneas de código de contexto que se mostrarán alrededor de la ubicación del error; el valor predeterminado es 1 línea. Aumentar este valor proporciona más información de contexto, lo que facilita el diagnóstico del problema.
Ejemplo:
# Set 500MB cache and display 3 lines of context
export SOURCE_MAP_PARSER_RESOURCE_CACHE_MAX_SIZE=500
export SOURCE_MAP_PARSER_CONTEXT_OFFSET_LINE=3
npx -y source-map-parser-mcp@latestRelated MCP server: Error Debugging MCP Server
Descripción general de las funciones
Análisis de pila : analiza la ubicación del código fuente correspondiente según el número de línea, el número de columna y el archivo de mapa de origen proporcionados.
Procesamiento por lotes : admite el análisis de múltiples seguimientos de pila simultáneamente y devuelve resultados por lotes.
Extracción de contexto : extrae el código de contexto para una cantidad específica de líneas para ayudar a los desarrolladores a comprender mejor el entorno donde ocurren los errores.
Descripción de la herramienta de servicio MCP
operating_guide
Obtenga instrucciones de uso del servicio MCP. Proporciona información sobre cómo usarlo mediante chat.
parse_stack
Analizar la información de la pila proporcionando seguimientos de pila y direcciones del mapa de origen.
Ejemplo de solicitud
pilas: información de la pila que incluye el número de línea, el número de columna y la dirección del mapa de origen.
línea: Número de línea, obligatorio.
columna: Número de columna, obligatorio.
sourceMapUrl: Dirección del mapa de origen, obligatoria.
{
"stacks": [
{
"line": 10,
"column": 5,
"sourceMapUrl": "https://example.com/source.map"
}
]
}Ejemplo de respuesta
{
"content": [
{
"type": "text",
"text": "[{\"success\":true,\"token\":{\"line\":10,\"column\":5,\"sourceCode\":[{\"line\":8,\"isStackLine\":false,\"raw\":\"function foo() {\"},{\"line\":9,\"isStackLine\":false,\"raw\":\" console.log('bar');\"},{\"line\":10,\"isStackLine\":true,\"raw\":\" throw new Error('test');\"},{\"line\":11,\"isStackLine\":false,\"raw\":\"}\"}],\"src\":\"index.js\"}}]"
}
]
}Descripción del resultado del análisis
success: indica si el análisis fue exitoso.token: el objeto Token devuelto cuando el análisis es exitoso, que contiene el número de línea del código fuente, el número de columna, el código de contexto y otra información.error: Se devuelve información de error cuando falla el análisis.
Ejemplo de ejecución
Indicador del sistema
Según las necesidades reales, puede usar indicaciones del sistema para guiar al modelo sobre cómo analizar la información de la pila. Por razones de seguridad o rendimiento, algunos equipos podrían no querer exponer los mapas de origen directamente al navegador para su análisis, sino procesar su ruta de carga. Por ejemplo, convertir la ruta bar-special.js a special/bar.js.map . En este caso, puede indicar al modelo que realice la conversión de ruta mediante reglas de indicaciones.
He aquí un ejemplo:
# Error Stack Trace Parsing Rules
When performing source map parsing, please follow these rules:
1. If the URL contains `special`, the file should be parsed into the `special/` directory, while removing `-special` from the filename.
2. All source map files are stored in the following CDN directory:
`https://cdn.jsdelivr.net/gh/MasonChow/source-map-parser-mcp@main/example/`
## Examples
- Source map address for `bar-special.js`:
`https://cdn.jsdelivr.net/gh/MasonChow/source-map-parser-mcp@main/example/special/bar.js.map`Ejemplo de tiempo de ejecución
Pila de errores
Uncaught Error: This is a error
at foo-special.js:49:34832
at ka (foo-special.js:48:83322)
at Vs (foo-special.js:48:98013)
at Et (foo-special.js:48:97897)
at Vs (foo-special.js:48:98749)
at Et (foo-special.js:48:97897)
at Vs (foo-special.js:48:98059)
at sv (foo-special.js:48:110550)
at foo-special.js:48:107925
at MessagePort.Ot (foo-special.js:25:1635)
Preguntas frecuentes
1. Error al cargar el módulo WebAssembly
Si la herramienta devuelve el siguiente mensaje de error, solucione el problema de la siguiente manera:
Error de inicialización del analizador: WebAssembly.instantiate(): tipo de valor no válido 'externref', habilitar con --experimental-wasm-reftypes @+86
Verificar la versión de Node.js : Asegúrate de que la versión de Node.js sea la 18 o superior. Si es inferior a la 18, actualiza Node.js.
Habilitar bandera experimental : si la versión de Node.js es 18+ pero aún tiene problemas, use el siguiente comando para iniciar la herramienta:
npx --node-arg=--experimental-wasm-reftypes -y source-map-parser-mcp@latest
Guía de desarrollo local
1. Instalar dependencias
Asegúrese de que Node.js y npm estén instalados, luego ejecute el siguiente comando para instalar las dependencias del proyecto:
npm install2. Enlace del servicio MCP
Ejecute el siguiente comando para iniciar el servidor MCP:
npx tsx src/main.tsDescripción general de la lógica interna
1. Descripción del archivo principal
stack_parser_js_sdk.js: contenedor de JavaScript para el módulo WebAssembly, que proporciona una funcionalidad básica de análisis de pila.parser.ts: implementación principal del analizador, responsable de inicializar el módulo WebAssembly, recuperar el contenido del mapa fuente y analizar la información de la pila.server.ts: Implementación del servidor MCP, que proporciona la interfaz de la herramientaparse_stackpara llamadas externas.
2. Modificar la lógica de análisis
Para modificar la lógica de análisis, edite el método getSourceToken en el archivo parser.ts .
3. Agregar nuevas herramientas
En el archivo server.ts , se pueden agregar nuevas interfaces de herramientas utilizando el método server.tool .
Notas
Archivos de mapas de origen : asegúrese de que la dirección del archivo de mapas de origen proporcionada sea accesible y que el formato del archivo sea correcto.
Manejo de errores : durante el análisis, pueden encontrarse errores de red, errores de formato de archivo y otros problemas; se recomienda implementar un manejo de errores adecuado al realizar llamadas.
Pautas de contribución
Las contribuciones a través de problemas y solicitudes de extracción son bienvenidas para mejorar este proyecto.
Licencia
Este proyecto está licenciado bajo la Licencia MIT. Consulte el archivo de LICENCIA para más detalles.
Available Tools
3 toolslookup_contextA
Lookup Source Code Context
This tool looks up original source code context for a specific line and column position in compiled/minified code.
Parameters:
line: The line number in the compiled code (1-based)
column: The column number in the compiled code
sourceMapUrl: The URL of the source map file
contextLines (optional): Number of context lines to include before and after the target line (default: 5)
Returns:
A JSON object containing the source code context snippet with file path, target line info, and surrounding context lines
Returns null if the position cannot be mapped
| Name | Required | Description | Default |
|---|---|---|---|
| line | Yes | The line number in the compiled code (1-based) | |
| column | Yes | The column number in the compiled code | |
| sourceMapUrl | Yes | The URL of the source map file | |
| contextLines | No | Number of context lines to include (default: 5) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description bears the full burden. It mentions the return value includes a JSON object or null if unmappable, but does not disclose side effects, authentication needs, or error handling behavior for invalid input or network issues.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise, well-structured with markdown headings and a clear list of parameters. Every sentence adds value, though the parameter descriptions could be omitted since they duplicate the schema.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple lookup tool without output schema, the description adequately covers purpose, parameters, and return behavior including null case. It lacks error scenarios and relation to sibling tools, but is sufficient for basic usage.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% with parameter descriptions. The tool description largely repeats those descriptions but adds the default value for contextLines and includes a Returns section not present in the schema. It adds minimal new meaning beyond the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool looks up original source code context for a specific line and column in compiled code. It identifies the exact action and resource, and implicitly distinguishes from siblings like parse_stack and unpack_sources through its unique focus on source map lookups.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus its siblings (parse_stack, unpack_sources). It doesn't mention any context or prerequisites, leaving the agent without clear decision criteria for tool selection.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
parse_stackA
Parse Error Stack Trace
This tool allows you to parse error stack traces by providing the following:
A downloadable source map URL.
The line and column numbers from the stack trace.
The tool will map the provided stack trace information to the corresponding source code location using the source map. It also supports fetching additional context lines around the error location for better debugging.
Parameters:
stacks: An array of stack trace objects, each containing:
line: The line number in the stack trace.
column: The column number in the stack trace.
sourceMapUrl: The URL of the source map file corresponding to the stack trace.
ctxOffset (optional): The number of additional context lines to include before and after the error location in the source code. Defaults to 5.
Returns:
A JSON object containing the parsed stack trace information, including the mapped source code location and context lines.
If parsing fails, an error message will be returned for the corresponding stack trace.
| Name | Required | Description | Default |
|---|---|---|---|
| stacks | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden. It describes the return format and error handling, but does not disclose any behavioral traits like side effects, rate limits, or authentication requirements. The description is adequate but not rich.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-structured with a header, explanation, parameter list, and return section. It is somewhat verbose but each part contributes to clarity. It is front-loaded with the purpose, making it easy to scan.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the lack of annotations and output schema, the description covers the tool's purpose, parameters, return values, and error behavior. It is missing explicit usage guidelines and a note on sibling differentiation, but overall provides sufficient context for an agent to use the tool effectively.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema provides descriptions for all three fields in stacks, giving high coverage. The description adds value by explaining the optional 'ctxOffset' parameter and its default, which is not present in the schema. This enriches understanding beyond the schema alone.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool parses error stack traces using source maps to map to source code locations. It is specific and distinct from the sibling tools 'lookup_context' and 'unpack_sources', but does not explicitly differentiate itself.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explains what the tool does and its parameters, but it does not provide explicit guidance on when to use this tool versus the siblings or what prerequisites are needed. Usage is implied rather than stated.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
unpack_sourcesA
Unpack Source Map Sources
This tool extracts all source files and their content from a source map.
Parameters:
sourceMapUrl: The URL of the source map file to unpack
Returns:
A JSON object containing:
sources: Object with source file paths as keys and their content as values
sourceRoot: The source root path from the source map
file: The original file name
totalSources: Total number of source files found
| Name | Required | Description | Default |
|---|---|---|---|
| sourceMapUrl | Yes | The URL of the source map file to unpack |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations provided, so description carries full burden. It explains the output format (JSON with sources, sourceRoot, etc.) but does not mention side effects, permissions, error handling, or rate limits. For a read-only tool, this is adequate but minimal.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Very concise: one heading, a brief description, and a bulleted return list. Every sentence adds value. Information is front-loaded and well-organized.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given no output schema, the description fully explains the return format. The single parameter is described. The tool is simple and the description is complete for an agent to understand and invoke it correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% with one parameter, and the description restates 'sourceMapUrl' but adds no extra meaning beyond the schema. However, it does detail the return structure, which adds context. Baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states it extracts all source files and content from a source map, using specific verb 'extract' and resource 'source map sources'. It distinguishes from siblings like 'lookup_context' and 'parse_stack' by focusing on source map unpacking.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance on when to use this tool versus alternatives. Description lacks context about prerequisites, limitations, or when not to use it. Sibling tools are not compared.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v1.0.0- Added
lookup_context - Removed
operating_guide - Added
unpack_sources
2 tool updates
- First observed
operating_guide - First observed
parse_stack
TDQS
Scored across 3 tools
Each tool has a clear, distinct purpose: lookup_context maps a single position to source context, parse_stack processes multiple stack entries, and unpack_sources extracts all source files. There is no overlap or ambiguity between them.
All tool names follow a consistent verb_noun pattern in snake_case: lookup_context, parse_stack, unpack_sources. The naming is predictable and easy to understand.
With 3 tools, the server is focused and each tool serves a core need in source map parsing. While the count is small, it is appropriate for the domain; adding a validation or metadata tool could be beneficial but not necessary.
The toolset covers the primary tasks: single position mapping, stack trace parsing, and source extraction. Minor gaps exist (e.g., no direct source map metadata or validation), but the core functionality is well-covered.
Maintenance
Related MCP Connectors
- WebeyezOAuthcom.webeyez
Session replays, JS errors, funnel drop-offs and revenue-loss diagnostics.
Investigate errors, track deployments, analyze performance, and manage application monitoring
Track errors, manage performance alerts, and configure dashboards and monitors
- BugTapeOAuthai.bugtape
Production bugs with replay, network, console and stack, ranked for your coding agent to fix.
1
Related MCP Servers
- AlicenseAqualityCmaintenanceEnables AI assistants to debug JavaScript and TypeScript applications by connecting to Chrome DevTools Protocol-compatible debuggers, allowing them to set breakpoints, step through code, inspect variables, and evaluate expressions with full source map support.1812 npm2Apache 2.0
- AlicenseNot gradedqualityDmaintenanceProvides intelligent error detection and debugging capabilities across multiple programming languages with real-time monitoring of build, lint, runtime, console, and test errors. Offers AI-enhanced error analysis with automated resolution suggestions and context-aware debugging.MIT
- AlicenseAqualityAmaintenanceEnables AI coding assistants to debug and analyze JavaScript code in web pages through breakpoint debugging, function hooking, network analysis, and runtime inspection of scripts including minified code.241,347 npm2,916Apache 2.0
- FlicenseNot gradedqualityDmaintenanceProvides real-time debugging, code quality monitoring, and performance insights for React/Next.js applications with features including Chrome DevTools integration, breakpoint management, complexity analysis, and live error streaming.8 npm1-