wasm-stack-trace-mapper
Leverages WebAssembly for efficient processing of JavaScript error stack traces, facilitating precise mapping back to original source code positions. Provides batch analysis and contextual code snippet retrieval for superior debugging insight.
Author

MasonChow
Quick Info
Actions
Tags
WebAssembly-Powered Source Map Deobfuscator
🌐 Language Options: English | 简体中文
This utility employs a high-performance WebAssembly core to resolve JavaScript stack traces against their corresponding source maps, pinpointing the exact location in the unminified source. It significantly accelerates root cause analysis by providing immediate access to source code context. This documentation outlines its deployment and utilization.
Model Context Protocol (MCP) Integration
Prerequisite: Node.js runtime version 20 or newer is mandatory.
Method A: Direct Execution via NPX
bash npx -y source-map-parser-mcp@latest
Method B: Local Artifact Execution
Retrieve the compiled assets from the GitHub Release page and execute:
bash node dist/main.es.js
Embedding within a Custom MCP Host
You possess the capability to integrate this tool directly into your proprietary MCP server runtime for tailored functionality.
Installation:
bash npm install source-map-parser-mcp
Minimal TypeScript Server Setup:
ts import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { registerTools, Parser, type ToolsRegistryOptions, } from 'source-map-parser-mcp';
const server = new McpServer( { name: 'your-org.source-map-parser', version: '0.0.1' }, { capabilities: { tools: {} } } );
// Configuration for surrounding context lines, defaults to 1 if not set const options: ToolsRegistryOptions = { contextOffsetLine: Number(process.env.SOURCE_MAP_PARSER_CONTEXT_OFFSET_LINE) || 1, };
registerTools(server, options);
// Initialize as stdio communication endpoint const transport = new StdioServerTransport(); await server.connect(transport);
// Alternative: Direct programmatic use outside of MCP framework const parser = new Parser({ contextOffsetLine: 1 }); // await parser.parseStack({ line: 10, column: 5, sourceMapUrl: 'https://...' }); // await parser.batchParseStack([{ line, column, sourceMapUrl }]);
Distribution Artifacts and Type Definitions
This package furnishes both ECMAScript Modules (ESM) and CommonJS (CJS) formats, alongside a unified TypeScript declaration file.
- Output Locations:
- ESM Entry:
dist/index.es.js - CJS Entry:
dist/index.cjs.js - CLI Launcher:
dist/main.es.js - Type Definitions:
dist/index.d.ts(Singular bundled file)
Local Build Command:
bash npm install npm run build
Incorporating Types in Your Project:
ts import { Parser, registerTools, type ToolsRegistryOptions, } from 'source-map-parser-mcp';
Runtime Parameter Tuning
System behavior is adjustable via standard environment variables to optimize for diverse operational requirements.
SOURCE_MAP_PARSER_RESOURCE_CACHE_MAX_SIZE: Governs the maximum allocated memory for cached resource files (Source Maps); defaults to 200MB. Proper tuning optimizes the performance vs. memory trade-off.SOURCE_MAP_PARSER_CONTEXT_OFFSET_LINE: Specifies the count of surrounding code lines presented alongside the error locus; defaults to 1. Elevating this value furnishes richer context for error investigation.
Configuration Example:
bash
Allocate 500MB cache and request 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@latest
Core Capabilities
- Stack Trace Resolution: Maps error telemetry (line/column) provided against a Source Map URI directly to its original source file coordinates.
- Parallel Processing: Handles multiple stack trace inputs concurrently for batch transformation.
- Contextual Snippet Retrieval: Extracts adjacent source code lines around the error point to establish surrounding execution context.
- Positional Lookup: Allows querying for source context based on specific compiled code coordinates.
- Source Map Inventory: Ability to deconstruct a Source Map and extract all constituent source files and their contents.
MCP Service Tool Definitions
operating_guide
Retrieves comprehensive usage directions for interacting with this MCP service component.
parse_stack
Transforms stack trace entries using associated Source Map metadata.
Input Schema Example
stacks: An array of trace objects detailing location and map pointer.line: Zero-based line index within the mapped file (Mandatory).column: Zero-based column index within the mapped file (Mandatory).sourceMapUrl: URI pointing to the required Source Map file (Mandatory).
{ "stacks": [ { "line": 10, "column": 5, "sourceMapUrl": "https://example.com/source.map" } ] }
Output Schema Example
{ "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\"}}]" } ] }
lookup_context
Retrieves source code context surrounding a specific location within the source file identified by the map.
Input Schema Example
line: Target line number (1-indexed) in the compiled artifact, required.column: Target column number (0-indexed) in the compiled artifact, required.sourceMapUrl: Location of the necessary source map, required.contextLines: Desired count of preceding/succeeding lines (Default: 5), optional.
{ "line": 42, "column": 15, "sourceMapUrl": "https://example.com/app.js.map", "contextLines": 5 }
Output Schema Example
{ "content": [ { "type": "text", "text": "{\"filePath\":\"src/utils.js\",\"targetLine\":25,\"contextLines\":[{\"lineNumber\":23,\"content\":\"function calculateSum(a, b) {\"},{\"lineNumber\":24,\"content\":\" if (a < 0 || b < 0) {\"},{\"lineNumber\":25,\"content\":\" throw new Error('Negative numbers not allowed');\"},{\"lineNumber\":26,\"content\":\" }"},{\"lineNumber\":27,\"content\":\" return a + b;\"}]}" } ] }
unpack_sources
Deconstructs a source map archive to yield the constituent original source files and their mapped content.
Input Schema Example
sourceMapUrl: The external URI pointing to the map file to be dismantled, required.
{ "sourceMapUrl": "https://example.com/bundle.js.map" }
Output Schema Example
{ "content": [ { "type": "text", "text": "{\"sources\":{\"src/index.js\":\"import { utils } from './utils.js';\nconsole.log('Hello World!');\",\"src/utils.js\":\"export const utils = { add: (a, b) => a + b };\"},\"sourceRoot\":\"/\",\"file\":\"bundle.js\",\"totalSources\":2}" } ] }
Result Interpretation
success: A boolean flag indicating successful mapping computation.token: If successful, this object encapsulates the resolved location data, including the source code line/column pointers and surrounding context.error: Detailed error message provided upon mapping failure.
Operational Example: Prompt Engineering for Path Rewriting
System instructions can dictate how URLs are transformed prior to fetching, which is useful when source maps are proxied or restructured for security/performance.
Sample System Directives:
markdown
Source Map Resolution Directives
Apply these transformations when resolving source map URIs:
- Any URI segment containing the substring
specialmust be mapped into a local subdirectory namedspecial/, and the suffix-specialmust be purged from the base filename. - All source map resolution must default to fetching from the following repository root:
https://cdn.jsdelivr.net/gh/MasonChow/source-map-parser-mcp@main/example/
Resolution Examples
- The trace referencing
foo-special.jsshould target the map file at:https://cdn.jsdelivr.net/gh/MasonChow/source-map-parser-mcp@main/example/special/foo.js.map
Runtime Execution Illustration
Observed Stack Trace:
Uncaught Error: System failure detected 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)

Frequently Asked Questions (FAQ)
1. Failure to Initialize WebAssembly Module
If the tool reports an initialization error resembling this:
parser init error: WebAssembly.instantiate(): invalid value type 'externref', enable with --experimental-wasm-reftypes @+86
Troubleshooting steps:
- Node.js Version Check: Verify that your runtime is Node.js version 20 or later. An earlier version necessitates an upgrade.
- Enabling Experimental Flag: If Node.js >= 20 and the error persists, invoke the tool with the required flag: bash npx --node-arg=--experimental-wasm-reftypes -y source-map-parser-mcp@latest
Local Development Workflow
1. Dependency Installation
Ensure Node.js and npm are configured, then execute dependency fetching:
bash npm install
2. Launching the MCP Endpoint
Execute the TypeScript source to initiate the local MCP server listener:
bash npx tsx src/main.ts
Internal Component Summary
-
Core Files Description:
stack_parser_js_sdk.js: Serves as the JavaScript interface layer binding to the compiled WebAssembly parsing engine.parser.ts: Contains the primary logic for initializing the WASM module, managing Source Map fetching, and executing the parsing routines.server.ts: Implements the networking layer for the MCP, registering theparse_stacktool endpoint for external invocation.
-
Logic Modification Point: To adjust the core mapping transformation logic, focus on the
getSourceTokenfunction located withinparser.ts. -
Extending Functionality: New tool interfaces can be exposed to the MCP interface layer by utilizing the
server.toolregistration method withinserver.ts.
Operational Caveats
- Source Map Accessibility: Confirm that the URI provided for the Source Map file is resolvable over the network and adheres to the expected file structure.
- Robust Error Handling: Due to potential network failures or malformed map data, applications consuming this tool should incorporate comprehensive try/catch blocks for request execution.
Community Contribution
We welcome enhancements submitted via Issues or Pull Requests to further refine this repository.
Licensing
This software is distributed under the terms of the MIT License. Review the LICENSE file for specifics.
WIKIPEDIA: XMLHttpRequest (XHR) represents an API implemented as a JavaScript object, designed to facilitate asynchronous HTTP requests between a web client and a remote server. This capability allows browser-based applications to fetch or submit data post-page-load without necessitating a full page refresh. XHR is a foundational element of Ajax methodologies. Before its advent, server interaction heavily relied on traditional page navigation initiated by form submissions or hyperlinks. XMLHttpRequest marked a paradigm shift.
== Historical Evolution ==
The conceptual framework for XMLHttpRequest was first formulated in 2000 by developers associated with Microsoft Outlook. This concept was subsequently integrated into Internet Explorer version 5 (released in 1999). Initially, the functionality did not utilize the canonical XMLHttpRequest identifier; instead, developers instantiated objects via ActiveXObject("Msxml2.XMLHTTP") or ActiveXObject("Microsoft.XMLHTTP"). By the release of Internet Explorer 7 (2006), widespread browser adoption of the standardized XMLHttpRequest name had been achieved.
The standardized XMLHttpRequest naming convention is now universally recognized across all major browser engines, including Mozilla's Gecko (2002), Safari 1.2 (2004), and Opera 8.0 (2005).
=== Specification Progression === The World Wide Web Consortium (W3C) released an initial Working Draft specification for the XMLHttpRequest object on April 5, 2006. This was followed by a Level 2 Working Draft specification on February 25, 2008, which introduced features like progress monitoring, cross-origin request facilitation, and byte stream handling. By the close of 2011, the Level 2 features were consolidated back into the primary specification document. Subsequently, in late 2012, the responsibility for maintaining this standard transitioned to the WHATWG, which continues to manage it as a living document utilizing Web IDL notation.
== Operational Use Cases == The typical process for dispatching a request using XMLHttpRequest involves a sequence of distinct programming actions.
- Instantiate an XMLHttpRequest proxy object via its constructor:
- Invoke the "open" method to define the request verb, specify the target resource URI, and select between synchronous or asynchronous execution mode:
- For asynchronous operations, an event handler must be assigned to intercept state change notifications:
- Command the request transmission by calling the "send" method:
- Process the response data within the designated event listener. Upon a successful response from the server, data is typically accessible via the "responseText" attribute once the object reaches state 4 (the "done" state). Beyond these core requirements, XMLHttpRequest offers advanced controls over request transmission and response processing. Custom headers can be affixed to fine-tune server behavior, and payload data can be transmitted to the server within the "send" argument. Responses can be automatically deserialized from JSON into native JavaScript objects, or streamed incrementally rather than waiting for the complete payload. Furthermore, requests can be terminated prematurely or configured with a timeout threshold.
== Cross-Origin Interactions ==
During the early phases of the World Wide Web's evolution, restrictions were placed on resource fetching across different domains, leading to limitations in application functionality.

