@0x1f320.sh/why-did-you-render-mcp 1.0.0-dev.2 → 1.0.0-dev.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # why-did-you-render-mcp
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@0x1f320.sh/why-did-you-render-mcp.svg?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/@0x1f320.sh/why-did-you-render-mcp)
4
+ [![CI](https://img.shields.io/github/actions/workflow/status/0x1f320/why-did-you-render-mcp/ci.yml?style=flat&colorA=000000&colorB=000000)](https://github.com/0x1f320/why-did-you-render-mcp/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/@0x1f320.sh/why-did-you-render-mcp?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/@0x1f320.sh/why-did-you-render-mcp)
6
+
3
7
  An [MCP](https://modelcontextprotocol.io/) server that bridges [why-did-you-render](https://github.com/welldone-software/why-did-you-render) data from the browser to coding agents. It captures unnecessary React re-render reports in real time and exposes them as MCP tools, so agents can diagnose and fix performance issues without manual browser inspection.
4
8
 
5
9
  ## How It Works
@@ -39,10 +43,8 @@ import whyDidYouRender from "@welldone-software/why-did-you-render";
39
43
  import { buildOptions } from "@0x1f320.sh/why-did-you-render-mcp/client";
40
44
 
41
45
  if (process.env.NODE_ENV === "development") {
42
- const { notifier } = buildOptions();
43
-
44
46
  whyDidYouRender(React, {
45
- notifier,
47
+ ...buildOptions(),
46
48
  trackAllPureComponents: true,
47
49
  });
48
50
  }
@@ -59,31 +61,99 @@ const { notifier } = buildOptions({
59
61
 
60
62
  ### 2. Add the MCP server to your agent
61
63
 
62
- Add the server to your MCP client configuration. For example, in Claude Desktop's `claude_desktop_config.json`:
64
+ <details>
65
+ <summary>Claude Code</summary>
66
+
67
+ ```sh
68
+ claude mcp add why-did-you-render -- npx -y @0x1f320.sh/why-did-you-render-mcp
69
+ ```
70
+
71
+ </details>
72
+
73
+ <details>
74
+ <summary>Claude Desktop</summary>
75
+
76
+ ```sh
77
+ claude mcp add-json why-did-you-render '{"command":"npx","args":["-y","@0x1f320.sh/why-did-you-render-mcp"]}' -s user
78
+ ```
79
+
80
+ Or manually edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) / `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
81
+
82
+ ```json
83
+ {
84
+ "mcpServers": {
85
+ "why-did-you-render": {
86
+ "command": "npx",
87
+ "args": ["-y", "@0x1f320.sh/why-did-you-render-mcp"]
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ </details>
94
+
95
+ <details>
96
+ <summary>Cursor</summary>
97
+
98
+ ```sh
99
+ cursor --add-mcp '{"name":"why-did-you-render","command":"npx","args":["-y","@0x1f320.sh/why-did-you-render-mcp"]}'
100
+ ```
101
+
102
+ Or add to `.cursor/mcp.json` in your project:
63
103
 
64
104
  ```json
65
105
  {
66
106
  "mcpServers": {
67
107
  "why-did-you-render": {
68
108
  "command": "npx",
69
- "args": ["@0x1f320.sh/why-did-you-render-mcp"]
109
+ "args": ["-y", "@0x1f320.sh/why-did-you-render-mcp"]
70
110
  }
71
111
  }
72
112
  }
73
113
  ```
74
114
 
75
- Or if you installed it globally:
115
+ </details>
116
+
117
+ <details>
118
+ <summary>Windsurf</summary>
119
+
120
+ Add to `~/.codeium/windsurf/mcp_config.json`:
76
121
 
77
122
  ```json
78
123
  {
79
124
  "mcpServers": {
80
125
  "why-did-you-render": {
81
- "command": "why-did-you-render-mcp"
126
+ "command": "npx",
127
+ "args": ["-y", "@0x1f320.sh/why-did-you-render-mcp"]
82
128
  }
83
129
  }
84
130
  }
85
131
  ```
86
132
 
133
+ </details>
134
+
135
+ <details>
136
+ <summary>VS Code (GitHub Copilot)</summary>
137
+
138
+ ```sh
139
+ code --add-mcp '{"name":"why-did-you-render","command":"npx","args":["-y","@0x1f320.sh/why-did-you-render-mcp"]}'
140
+ ```
141
+
142
+ Or add to `.vscode/mcp.json` in your project:
143
+
144
+ ```json
145
+ {
146
+ "servers": {
147
+ "why-did-you-render": {
148
+ "command": "npx",
149
+ "args": ["-y", "@0x1f320.sh/why-did-you-render-mcp"]
150
+ }
151
+ }
152
+ }
153
+ ```
154
+
155
+ </details>
156
+
87
157
  ### 3. Start your dev server and interact with the app
88
158
 
89
159
  Once both the MCP server and your React dev server are running, interact with your app in the browser. The agent can now query re-render data using the MCP tools below.
@@ -126,6 +196,7 @@ Browser (project-b) ──┤
126
196
  - **Multiple MCP instances** can run simultaneously. Only the first instance starts the WebSocket server; others gracefully skip. All instances share the same JSONL data directory.
127
197
  - **Multi-project support** — Each project is identified by `location.origin`. Render data is stored in per-project JSONL files.
128
198
  - **No daemon required** — Each MCP instance is independent. The WebSocket server is opportunistically claimed by whichever instance starts first.
199
+ - **Value dictionary deduplication** — Render reports often repeat the same `prevValue`/`nextValue` objects across thousands of entries. Each JSONL file stores a content-addressed dictionary on its first line, mapping xxhash-wasm hashes to unique values. Render lines reference them via `@@ref:<hash>` sentinels instead of inlining the full object, dramatically reducing file size. Reads hydrate refs transparently.
129
200
 
130
201
  ## Configuration
131
202
 
@@ -1,92 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/client/utils/describe-value.ts
3
- function describeValue(value) {
4
- if (value === null) return "null";
5
- if (value === void 0) return "undefined";
6
- if (typeof value === "function") return `function ${value.name || "anonymous"}`;
7
- if (typeof value !== "object") return String(value);
8
- if (Array.isArray(value)) return `Array(${value.length})`;
9
- const name = Object.getPrototypeOf(value)?.constructor?.name;
10
- if (name && name !== "Object") return name;
11
- return "Object";
12
- }
13
- //#endregion
14
- //#region src/client/utils/sanitize-differences.ts
15
- function sanitizeDifferences(diffs) {
16
- if (!Array.isArray(diffs)) return false;
17
- return diffs.map((diff) => ({
18
- pathString: diff.pathString,
19
- diffType: diff.diffType,
20
- prevValue: describeValue(diff.prevValue),
21
- nextValue: describeValue(diff.nextValue)
22
- }));
23
- }
24
- //#endregion
25
- //#region src/client/utils/sanitize-reason.ts
26
- function sanitizeReason(reason) {
27
- return {
28
- propsDifferences: sanitizeDifferences(reason.propsDifferences),
29
- stateDifferences: sanitizeDifferences(reason.stateDifferences),
30
- hookDifferences: sanitizeDifferences(reason.hookDifferences)
31
- };
32
- }
33
- //#endregion
34
- //#region src/client/index.ts
35
- const DEFAULT_WS_URL = "ws://localhost:4649";
36
- function patchDevToolsHook(onCommit) {
37
- if (!globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__) globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
38
- supportsFiber: true,
39
- inject() {},
40
- onCommitFiberRoot() {},
41
- onCommitFiberUnmount() {}
42
- };
43
- const hook = globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;
44
- const original = hook.onCommitFiberRoot.bind(hook);
45
- hook.onCommitFiberRoot = (...args) => {
46
- onCommit();
47
- return original(...args);
48
- };
49
- }
50
- function buildOptions(opts) {
51
- const wsUrl = opts?.wsUrl ?? DEFAULT_WS_URL;
52
- const projectId = opts?.projectId ?? globalThis.location?.origin ?? "default";
53
- let ws = null;
54
- let queue = [];
55
- let commitId = 0;
56
- patchDevToolsHook(() => {
57
- commitId++;
58
- });
59
- function connect() {
60
- ws = new WebSocket(wsUrl);
61
- ws.addEventListener("open", () => {
62
- for (const msg of queue) ws?.send(JSON.stringify(msg));
63
- queue = [];
64
- });
65
- ws.addEventListener("close", () => {
66
- ws = null;
67
- setTimeout(connect, 1e3);
68
- });
69
- ws.addEventListener("error", () => {
70
- ws?.close();
71
- });
72
- }
73
- connect();
74
- function send(msg) {
75
- if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg));
76
- else queue.push(msg);
77
- }
78
- return { notifier(info) {
79
- send({
80
- type: "render",
81
- projectId,
82
- commitId,
83
- payload: {
84
- displayName: info.displayName,
85
- reason: sanitizeReason(info.reason),
86
- hookName: info.hookName
87
- }
88
- });
89
- } };
90
- }
91
- //#endregion
92
- exports.buildOptions = buildOptions;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`socket.io-client`),l=require(`error-stack-parser`);l=s(l);const u=[`whyDidYouRender`,`react-dom`,`react.development`,`react.production`,`scheduler.`,`installHook`,`console.`],d=[`trackHookChanges`,`WDYRFunctionalComponent`,`Object.notifier`,`notifier`,`console.trace`];function f(e){return u.some(t=>e.includes(t))}function p(e){return d.some(t=>e===t)}function m(e){return e.replace(/WDYR$/,``)}function h(e){let t=e.startsWith(`new `)?e.slice(4):e,n=t.lastIndexOf(`.`);return m(n>=0?t.slice(n+1):t)}function g(e){return/^use[A-Z]/.test(e)}function _(e){let t;try{t=l.default.parse(e)}catch{return[]}let n=[];for(let e of t){let t=e.fileName??``;if(!t||f(t))continue;let r=e.functionName;if(!r||p(r))continue;let i=h(r);i&&n.push({type:g(i)?`hook`:`component`,name:i,location:{path:t,line:e.lineNumber??0}})}return n}const v=Symbol.for(`react.element`),y=Symbol.for(`react.transitional.element`),b=Symbol.for(`react.memo`),x=Symbol.for(`react.forward_ref`);function S(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.$$typeof===v||t.$$typeof===y||t.$$typeof===60103}function C(e){let t=!1,n=!1,r=e;for(let e=0;e<5&&!(typeof r!=`object`||!r);e++){let e=r;if(e.$$typeof===b)t=!0,r=e.type;else if(e.$$typeof===x)n=!0,r=e.render;else break}let i=`Unknown`;return typeof r==`string`?i=r:typeof r==`function`&&(i=r.displayName||r.name||`Anonymous`),{name:i,memo:t,forwardRef:n}}function w(e,t,n){let r=C(e.type),i={};if(e.props&&typeof e.props==`object`)for(let r of Object.keys(e.props))r!==`children`&&(i[r]=T(e.props[r],t,n+1));return{type:`react-node`,component:r,props:i}}function T(e,t,n){if(e==null)return null;if(typeof e==`function`)return{type:`function`,name:e.name||`anonymous`};if(typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isNaN(e)?`NaN`:Number.isFinite(e)?Object.is(e,-0)?`-0`:e:e>0?`Infinity`:`-Infinity`;if(typeof e==`string`)return e;if(typeof e==`bigint`||typeof e==`symbol`)return e.toString();if(t.has(e))return`[Circular]`;if(n>=8)return`[MaxDepth]`;if(t.add(e),S(e))return w(e,t,n);if(Array.isArray(e))return e.map(e=>T(e,t,n+1));let r=Object.getPrototypeOf(e)?.constructor?.name;if(r&&r!==`Object`){if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return String(e);if(e instanceof Map){let r={};for(let[i,a]of e.entries())r[String(i)]=T(a,t,n+1);return{type:`Map`,entries:r}}if(e instanceof Set)return{type:`Set`,values:[...e].map(e=>T(e,t,n+1))};if(e instanceof Promise)return`Promise`;if(e instanceof Error)return{type:`Error`,name:e.name,message:e.message};if(typeof Node<`u`&&e instanceof Node&&e instanceof Element){let t={};for(let n of e.attributes)t[n.name]=n.value;return{type:`dom`,tagName:e.tagName.toLowerCase(),attrs:t}}return{type:`class`,name:r}}let i={};for(let r of Object.keys(e))i[r]=T(e[r],t,n+1);return i}function E(e){return T(e,new WeakSet,0)}function D(e){return Array.isArray(e)?e.map(e=>({pathString:e.pathString,diffType:e.diffType,prevValue:E(e.prevValue),nextValue:E(e.nextValue)})):!1}function O(e){return{propsDifferences:D(e.propsDifferences),stateDifferences:D(e.stateDifferences),hookDifferences:D(e.hookDifferences)}}function k(e){console.log(`%c[WDYR MCP]%c ${e}`,`color: #38bdf8; font-weight: bold`,`color: inherit; font-weight: normal`)}function A(e){globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__||(globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__={supportsFiber:!0,inject(){},onCommitFiberRoot(){},onCommitFiberUnmount(){}});let t=globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__,n=t.onCommitFiberRoot.bind(t);t.onCommitFiberRoot=(...t)=>(e(),n(...t))}function j(e){let t={};return e.include&&(t.include=e.include.map(e=>e.source)),e.exclude&&(t.exclude=e.exclude.map(e=>e.source)),e.trackAllPureComponents!=null&&(t.trackAllPureComponents=e.trackAllPureComponents),e.trackHooks!=null&&(t.trackHooks=e.trackHooks),e.trackExtraHooks&&(t.trackExtraHooks=e.trackExtraHooks.map(([,e])=>e)),e.logOnDifferentValues!=null&&(t.logOnDifferentValues=e.logOnDifferentValues),e.logOwnerReasons!=null&&(t.logOwnerReasons=e.logOwnerReasons),t}function M(e){let{wsUrl:t,projectId:n,notifier:r,...i}=e??{},a=t??`http://localhost:4649`,o=n??globalThis.location?.origin??`default`,s=0;A(()=>{s++});let l=(0,c.io)(a,{reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,transports:[`websocket`]});l.on(`connect`,()=>{k(`Connected to ${a}`),e&&l.emit(`config`,j(e),o)}),l.on(`disconnect`,()=>{k(`Disconnected, reconnecting...`)});let u=null,d=!1;function f(){d=!1,!(!u||u.reports.length===0)&&(l.emit(`render-batch`,u.reports,o,u.commitId),u=null)}return{...i,notifier(e){let t=_(Error()),n={displayName:e.displayName,reason:O(e.reason),hookName:e.hookName,...t.length>0&&{stackFrames:t}};u&&u.commitId===s?u.reports.push(n):(u&&f(),u={commitId:s,reports:[n]}),d||(d=!0,queueMicrotask(f)),r&&r(e)}}}exports.buildOptions=M;
@@ -1,13 +1,11 @@
1
- import { UpdateInfo } from "@welldone-software/why-did-you-render";
1
+ import { WhyDidYouRenderOptions } from "@welldone-software/why-did-you-render";
2
2
 
3
3
  //#region src/client/index.d.ts
4
4
  sideEffect();
5
- interface ClientOptions {
5
+ interface ClientOptions extends WhyDidYouRenderOptions {
6
6
  wsUrl?: string;
7
7
  projectId?: string;
8
8
  }
9
- declare function buildOptions(opts?: ClientOptions): {
10
- notifier(info: UpdateInfo): void;
11
- };
9
+ declare function buildOptions(opts?: ClientOptions): WhyDidYouRenderOptions;
12
10
  //#endregion
13
11
  export { ClientOptions, buildOptions };
@@ -1,13 +1,11 @@
1
- import { UpdateInfo } from "@welldone-software/why-did-you-render";
1
+ import { WhyDidYouRenderOptions } from "@welldone-software/why-did-you-render";
2
2
 
3
3
  //#region src/client/index.d.ts
4
4
  sideEffect();
5
- interface ClientOptions {
5
+ interface ClientOptions extends WhyDidYouRenderOptions {
6
6
  wsUrl?: string;
7
7
  projectId?: string;
8
8
  }
9
- declare function buildOptions(opts?: ClientOptions): {
10
- notifier(info: UpdateInfo): void;
11
- };
9
+ declare function buildOptions(opts?: ClientOptions): WhyDidYouRenderOptions;
12
10
  //#endregion
13
11
  export { ClientOptions, buildOptions };
@@ -1,91 +1 @@
1
- //#region src/client/utils/describe-value.ts
2
- function describeValue(value) {
3
- if (value === null) return "null";
4
- if (value === void 0) return "undefined";
5
- if (typeof value === "function") return `function ${value.name || "anonymous"}`;
6
- if (typeof value !== "object") return String(value);
7
- if (Array.isArray(value)) return `Array(${value.length})`;
8
- const name = Object.getPrototypeOf(value)?.constructor?.name;
9
- if (name && name !== "Object") return name;
10
- return "Object";
11
- }
12
- //#endregion
13
- //#region src/client/utils/sanitize-differences.ts
14
- function sanitizeDifferences(diffs) {
15
- if (!Array.isArray(diffs)) return false;
16
- return diffs.map((diff) => ({
17
- pathString: diff.pathString,
18
- diffType: diff.diffType,
19
- prevValue: describeValue(diff.prevValue),
20
- nextValue: describeValue(diff.nextValue)
21
- }));
22
- }
23
- //#endregion
24
- //#region src/client/utils/sanitize-reason.ts
25
- function sanitizeReason(reason) {
26
- return {
27
- propsDifferences: sanitizeDifferences(reason.propsDifferences),
28
- stateDifferences: sanitizeDifferences(reason.stateDifferences),
29
- hookDifferences: sanitizeDifferences(reason.hookDifferences)
30
- };
31
- }
32
- //#endregion
33
- //#region src/client/index.ts
34
- const DEFAULT_WS_URL = "ws://localhost:4649";
35
- function patchDevToolsHook(onCommit) {
36
- if (!globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__) globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
37
- supportsFiber: true,
38
- inject() {},
39
- onCommitFiberRoot() {},
40
- onCommitFiberUnmount() {}
41
- };
42
- const hook = globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;
43
- const original = hook.onCommitFiberRoot.bind(hook);
44
- hook.onCommitFiberRoot = (...args) => {
45
- onCommit();
46
- return original(...args);
47
- };
48
- }
49
- function buildOptions(opts) {
50
- const wsUrl = opts?.wsUrl ?? DEFAULT_WS_URL;
51
- const projectId = opts?.projectId ?? globalThis.location?.origin ?? "default";
52
- let ws = null;
53
- let queue = [];
54
- let commitId = 0;
55
- patchDevToolsHook(() => {
56
- commitId++;
57
- });
58
- function connect() {
59
- ws = new WebSocket(wsUrl);
60
- ws.addEventListener("open", () => {
61
- for (const msg of queue) ws?.send(JSON.stringify(msg));
62
- queue = [];
63
- });
64
- ws.addEventListener("close", () => {
65
- ws = null;
66
- setTimeout(connect, 1e3);
67
- });
68
- ws.addEventListener("error", () => {
69
- ws?.close();
70
- });
71
- }
72
- connect();
73
- function send(msg) {
74
- if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg));
75
- else queue.push(msg);
76
- }
77
- return { notifier(info) {
78
- send({
79
- type: "render",
80
- projectId,
81
- commitId,
82
- payload: {
83
- displayName: info.displayName,
84
- reason: sanitizeReason(info.reason),
85
- hookName: info.hookName
86
- }
87
- });
88
- } };
89
- }
90
- //#endregion
91
- export { buildOptions };
1
+ import{io as e}from"socket.io-client";import t from"error-stack-parser";const n=[`whyDidYouRender`,`react-dom`,`react.development`,`react.production`,`scheduler.`,`installHook`,`console.`],r=[`trackHookChanges`,`WDYRFunctionalComponent`,`Object.notifier`,`notifier`,`console.trace`];function i(e){return n.some(t=>e.includes(t))}function a(e){return r.some(t=>e===t)}function o(e){return e.replace(/WDYR$/,``)}function s(e){let t=e.startsWith(`new `)?e.slice(4):e,n=t.lastIndexOf(`.`);return o(n>=0?t.slice(n+1):t)}function c(e){return/^use[A-Z]/.test(e)}function l(e){let n;try{n=t.parse(e)}catch{return[]}let r=[];for(let e of n){let t=e.fileName??``;if(!t||i(t))continue;let n=e.functionName;if(!n||a(n))continue;let o=s(n);o&&r.push({type:c(o)?`hook`:`component`,name:o,location:{path:t,line:e.lineNumber??0}})}return r}const u=Symbol.for(`react.element`),d=Symbol.for(`react.transitional.element`),f=Symbol.for(`react.memo`),p=Symbol.for(`react.forward_ref`);function m(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.$$typeof===u||t.$$typeof===d||t.$$typeof===60103}function h(e){let t=!1,n=!1,r=e;for(let e=0;e<5&&!(typeof r!=`object`||!r);e++){let e=r;if(e.$$typeof===f)t=!0,r=e.type;else if(e.$$typeof===p)n=!0,r=e.render;else break}let i=`Unknown`;return typeof r==`string`?i=r:typeof r==`function`&&(i=r.displayName||r.name||`Anonymous`),{name:i,memo:t,forwardRef:n}}function g(e,t,n){let r=h(e.type),i={};if(e.props&&typeof e.props==`object`)for(let r of Object.keys(e.props))r!==`children`&&(i[r]=_(e.props[r],t,n+1));return{type:`react-node`,component:r,props:i}}function _(e,t,n){if(e==null)return null;if(typeof e==`function`)return{type:`function`,name:e.name||`anonymous`};if(typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isNaN(e)?`NaN`:Number.isFinite(e)?Object.is(e,-0)?`-0`:e:e>0?`Infinity`:`-Infinity`;if(typeof e==`string`)return e;if(typeof e==`bigint`||typeof e==`symbol`)return e.toString();if(t.has(e))return`[Circular]`;if(n>=8)return`[MaxDepth]`;if(t.add(e),m(e))return g(e,t,n);if(Array.isArray(e))return e.map(e=>_(e,t,n+1));let r=Object.getPrototypeOf(e)?.constructor?.name;if(r&&r!==`Object`){if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return String(e);if(e instanceof Map){let r={};for(let[i,a]of e.entries())r[String(i)]=_(a,t,n+1);return{type:`Map`,entries:r}}if(e instanceof Set)return{type:`Set`,values:[...e].map(e=>_(e,t,n+1))};if(e instanceof Promise)return`Promise`;if(e instanceof Error)return{type:`Error`,name:e.name,message:e.message};if(typeof Node<`u`&&e instanceof Node&&e instanceof Element){let t={};for(let n of e.attributes)t[n.name]=n.value;return{type:`dom`,tagName:e.tagName.toLowerCase(),attrs:t}}return{type:`class`,name:r}}let i={};for(let r of Object.keys(e))i[r]=_(e[r],t,n+1);return i}function v(e){return _(e,new WeakSet,0)}function y(e){return Array.isArray(e)?e.map(e=>({pathString:e.pathString,diffType:e.diffType,prevValue:v(e.prevValue),nextValue:v(e.nextValue)})):!1}function b(e){return{propsDifferences:y(e.propsDifferences),stateDifferences:y(e.stateDifferences),hookDifferences:y(e.hookDifferences)}}function x(e){console.log(`%c[WDYR MCP]%c ${e}`,`color: #38bdf8; font-weight: bold`,`color: inherit; font-weight: normal`)}function S(e){globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__||(globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__={supportsFiber:!0,inject(){},onCommitFiberRoot(){},onCommitFiberUnmount(){}});let t=globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__,n=t.onCommitFiberRoot.bind(t);t.onCommitFiberRoot=(...t)=>(e(),n(...t))}function C(e){let t={};return e.include&&(t.include=e.include.map(e=>e.source)),e.exclude&&(t.exclude=e.exclude.map(e=>e.source)),e.trackAllPureComponents!=null&&(t.trackAllPureComponents=e.trackAllPureComponents),e.trackHooks!=null&&(t.trackHooks=e.trackHooks),e.trackExtraHooks&&(t.trackExtraHooks=e.trackExtraHooks.map(([,e])=>e)),e.logOnDifferentValues!=null&&(t.logOnDifferentValues=e.logOnDifferentValues),e.logOwnerReasons!=null&&(t.logOwnerReasons=e.logOwnerReasons),t}function w(t){let{wsUrl:n,projectId:r,notifier:i,...a}=t??{},o=n??`http://localhost:4649`,s=r??globalThis.location?.origin??`default`,c=0;S(()=>{c++});let u=e(o,{reconnection:!0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,transports:[`websocket`]});u.on(`connect`,()=>{x(`Connected to ${o}`),t&&u.emit(`config`,C(t),s)}),u.on(`disconnect`,()=>{x(`Disconnected, reconnecting...`)});let d=null,f=!1;function p(){f=!1,!(!d||d.reports.length===0)&&(u.emit(`render-batch`,d.reports,s,d.commitId),d=null)}return{...a,notifier(e){let t=l(Error()),n={displayName:e.displayName,reason:b(e.reason),hookName:e.hookName,...t.length>0&&{stackFrames:t}};d&&d.commitId===c?d.reports.push(n):(d&&p(),d={commitId:c,reports:[n]}),f||(f=!0,queueMicrotask(p)),i&&i(e)}}}export{w as buildOptions};
@@ -1,384 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
- import { z } from "zod";
5
- import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync } from "node:fs";
6
- import { homedir } from "node:os";
7
- import { join } from "node:path";
8
- import { WebSocketServer } from "ws";
9
- //#region src/server/store/utils/read-jsonl.ts
10
- function readJsonl(file) {
11
- if (!existsSync(file)) return [];
12
- return readFileSync(file, "utf-8").split("\n").filter(Boolean).map((line) => JSON.parse(line));
13
- }
14
- //#endregion
15
- //#region src/server/store/utils/sanitize-project-id.ts
16
- function sanitizeProjectId(projectId) {
17
- return projectId.replaceAll(/[^a-zA-Z0-9_.-]/g, "_");
18
- }
19
- //#endregion
20
- //#region src/server/store/utils/to-result.ts
21
- function toResult(stored) {
22
- return {
23
- project: stored.projectId,
24
- displayName: stored.displayName,
25
- reason: stored.reason,
26
- ...stored.hookName != null && { hookName: stored.hookName },
27
- ...stored.commitId != null && { commitId: stored.commitId }
28
- };
29
- }
30
- //#endregion
31
- //#region src/server/store/render-store.ts
32
- const FLUSH_DELAY_MS = 200;
33
- var RenderStore = class {
34
- dir;
35
- buffers = /* @__PURE__ */ new Map();
36
- timers = /* @__PURE__ */ new Map();
37
- constructor(dir) {
38
- this.dir = dir ?? join(homedir(), ".wdyr-mcp", "renders");
39
- mkdirSync(this.dir, { recursive: true });
40
- }
41
- addRender(report, projectId, commitId) {
42
- const stored = {
43
- ...report,
44
- projectId,
45
- ...commitId != null && { commitId }
46
- };
47
- let buf = this.buffers.get(projectId);
48
- if (!buf) {
49
- buf = [];
50
- this.buffers.set(projectId, buf);
51
- }
52
- buf.push(stored);
53
- const existing = this.timers.get(projectId);
54
- if (existing) clearTimeout(existing);
55
- this.timers.set(projectId, setTimeout(() => this.flush(projectId), FLUSH_DELAY_MS));
56
- }
57
- flush(projectId) {
58
- if (projectId) this.flushProject(projectId);
59
- else for (const id of this.buffers.keys()) this.flushProject(id);
60
- }
61
- flushProject(projectId) {
62
- const buf = this.buffers.get(projectId);
63
- if (!buf || buf.length === 0) return;
64
- const lines = buf.map((s) => JSON.stringify(s)).join("\n");
65
- appendFileSync(this.projectFile(projectId), `${lines}\n`);
66
- buf.length = 0;
67
- const timer = this.timers.get(projectId);
68
- if (timer) {
69
- clearTimeout(timer);
70
- this.timers.delete(projectId);
71
- }
72
- }
73
- getAllRenders(projectId) {
74
- this.flush(projectId);
75
- if (projectId) return readJsonl(this.projectFile(projectId)).map(toResult);
76
- return this.jsonlFiles().flatMap((f) => readJsonl(join(this.dir, f)).map(toResult));
77
- }
78
- getRendersByComponent(componentName, projectId) {
79
- return this.getAllRenders(projectId).filter((r) => r.displayName === componentName);
80
- }
81
- clearRenders(projectId) {
82
- if (projectId) {
83
- this.buffers.delete(projectId);
84
- const timer = this.timers.get(projectId);
85
- if (timer) {
86
- clearTimeout(timer);
87
- this.timers.delete(projectId);
88
- }
89
- const file = this.projectFile(projectId);
90
- if (existsSync(file)) unlinkSync(file);
91
- } else {
92
- for (const [id, timer] of this.timers) clearTimeout(timer);
93
- this.buffers.clear();
94
- this.timers.clear();
95
- for (const f of this.jsonlFiles()) unlinkSync(join(this.dir, f));
96
- }
97
- }
98
- getProjects() {
99
- this.flush();
100
- const projects = /* @__PURE__ */ new Set();
101
- for (const f of this.jsonlFiles()) {
102
- const firstLine = readFileSync(join(this.dir, f), "utf-8").split("\n")[0];
103
- if (!firstLine) continue;
104
- const stored = JSON.parse(firstLine);
105
- projects.add(stored.projectId);
106
- }
107
- return [...projects];
108
- }
109
- getCommitIds(projectId) {
110
- const renders = this.getAllRenders(projectId);
111
- return [...new Set(renders.map((r) => r.commitId).filter((id) => id != null))];
112
- }
113
- getRendersByCommit(commitId, projectId) {
114
- return this.getAllRenders(projectId).filter((r) => r.commitId === commitId);
115
- }
116
- getSummary(projectId) {
117
- const renders = this.getAllRenders(projectId);
118
- const summary = {};
119
- for (const r of renders) {
120
- summary[r.project] ??= {};
121
- const project = summary[r.project];
122
- project[r.displayName] = (project[r.displayName] ?? 0) + 1;
123
- }
124
- return summary;
125
- }
126
- projectFile(projectId) {
127
- return join(this.dir, `${sanitizeProjectId(projectId)}.jsonl`);
128
- }
129
- jsonlFiles() {
130
- return readdirSync(this.dir).filter((f) => f.endsWith(".jsonl"));
131
- }
132
- };
133
- //#endregion
134
- //#region src/server/store/index.ts
135
- const store = new RenderStore();
136
- //#endregion
137
- //#region src/server/tools/utils/resolve-project.ts
138
- /**
139
- * Resolves the project to use. If a project is explicitly given, use it.
140
- * If only one project exists, auto-select it. If multiple exist, return
141
- * a message asking the agent to disambiguate.
142
- */
143
- function resolveProject(project) {
144
- if (project) return { projectId: project };
145
- const projects = store.getProjects();
146
- if (projects.length === 0) return { projectId: void 0 };
147
- if (projects.length === 1) return { projectId: projects[0] };
148
- return {
149
- projectId: void 0,
150
- error: [
151
- "Multiple projects are recording render data. Ask the user which project they are working on (e.g. their dev server URL like http://localhost:3000).",
152
- "",
153
- "Active projects:",
154
- ...projects.map((p) => `- ${p}`)
155
- ].join("\n")
156
- };
157
- }
158
- //#endregion
159
- //#region src/server/tools/utils/text-result.ts
160
- function textResult(text) {
161
- return { content: [{
162
- type: "text",
163
- text
164
- }] };
165
- }
166
- //#endregion
167
- //#region src/server/tools/clear-renders.ts
168
- function register$5(server) {
169
- server.registerTool("clear_renders", {
170
- title: "Clear Renders",
171
- description: "Clears collected render data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.",
172
- inputSchema: { project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.") }
173
- }, async ({ project }) => {
174
- const resolved = resolveProject(project);
175
- if (resolved.error) return textResult(resolved.error);
176
- store.clearRenders(resolved.projectId);
177
- return textResult(resolved.projectId ? `Render data cleared for ${resolved.projectId}.` : "All render data cleared.");
178
- });
179
- }
180
- //#endregion
181
- //#region src/server/tools/get-commits.ts
182
- function register$4(server) {
183
- server.registerTool("get_commits", {
184
- title: "Get Commits",
185
- description: "Returns a list of React commit IDs that have recorded render data for a project. Use these IDs with get_renders_by_commit to inspect individual commits.",
186
- inputSchema: { project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.") }
187
- }, async ({ project }) => {
188
- const resolved = resolveProject(project);
189
- if (resolved.error) return textResult(resolved.error);
190
- const commitIds = store.getCommitIds(resolved.projectId);
191
- if (commitIds.length === 0) return textResult("No commits recorded yet. Make sure the browser is connected and triggering re-renders.");
192
- return textResult(JSON.stringify(commitIds));
193
- });
194
- }
195
- //#endregion
196
- //#region src/server/tools/get-projects.ts
197
- function register$3(server) {
198
- server.registerTool("get_projects", {
199
- title: "Get Projects",
200
- description: "Returns a list of project identifiers (browser origin URLs) that have recorded render data.",
201
- inputSchema: {}
202
- }, async () => {
203
- const projects = store.getProjects();
204
- if (projects.length === 0) return textResult("No projects have recorded render data yet.");
205
- return textResult(`Active projects:\n${projects.map((p) => `- ${p}`).join("\n")}`);
206
- });
207
- }
208
- //#endregion
209
- //#region src/server/tools/get-render-summary.ts
210
- function register$2(server) {
211
- server.registerTool("get_render_summary", {
212
- title: "Get Render Summary",
213
- description: "Returns a summary of unnecessary re-renders grouped by component name with counts. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.",
214
- inputSchema: { project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.") }
215
- }, async ({ project }) => {
216
- const resolved = resolveProject(project);
217
- if (resolved.error) return textResult(resolved.error);
218
- const summary = store.getSummary(resolved.projectId);
219
- if (Object.keys(summary).length === 0) return textResult("No unnecessary renders recorded yet.");
220
- const lines = [];
221
- for (const [projectId, components] of Object.entries(summary)) {
222
- lines.push(`[${projectId}]`);
223
- for (const [name, count] of Object.entries(components)) lines.push(` ${name}: ${count} re-render(s)`);
224
- }
225
- return textResult(`Unnecessary re-render summary:\n\n${lines.join("\n")}`);
226
- });
227
- }
228
- //#endregion
229
- //#region src/server/tools/get-renders-by-commit.ts
230
- function register$1(server) {
231
- server.registerTool("get_renders_by_commit", {
232
- title: "Get Renders by Commit",
233
- description: "Returns all unnecessary re-renders for a specific React commit ID. Use get_commits first to discover available commit IDs.",
234
- inputSchema: {
235
- commitId: z.number().describe("The React commit ID to filter by."),
236
- project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.")
237
- }
238
- }, async ({ commitId, project }) => {
239
- const resolved = resolveProject(project);
240
- if (resolved.error) return textResult(resolved.error);
241
- const renders = store.getRendersByCommit(commitId, resolved.projectId);
242
- if (renders.length === 0) return textResult(`No renders recorded for commit ${commitId}.`);
243
- return textResult(JSON.stringify(renders, null, 2));
244
- });
245
- }
246
- //#endregion
247
- //#region src/server/tools/get-unnecessary-renders.ts
248
- function register(server) {
249
- server.registerTool("get_unnecessary_renders", {
250
- title: "Get Unnecessary Renders",
251
- description: "Returns all unnecessary re-renders collected from the browser. If multiple projects are active and no project is specified, the tool will ask you to disambiguate by asking the user for their dev server URL.",
252
- inputSchema: {
253
- component: z.string().optional().describe("Filter by component name. Omit to get all renders."),
254
- project: z.string().optional().describe("Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.")
255
- }
256
- }, async ({ component, project }) => {
257
- const resolved = resolveProject(project);
258
- if (resolved.error) return textResult(resolved.error);
259
- const renders = component ? store.getRendersByComponent(component, resolved.projectId) : store.getAllRenders(resolved.projectId);
260
- if (renders.length === 0) return textResult(component ? `No unnecessary renders recorded for "${component}".` : "No unnecessary renders recorded yet. Make sure the browser is connected and triggering re-renders.");
261
- return textResult(JSON.stringify(renders, null, 2));
262
- });
263
- }
264
- //#endregion
265
- //#region src/server/tools/index.ts
266
- function registerTools(server) {
267
- register(server);
268
- register$2(server);
269
- register$4(server);
270
- register$1(server);
271
- register$3(server);
272
- register$5(server);
273
- }
274
- //#endregion
275
- //#region src/server/liveness.ts
276
- const DEFAULT_INTERVAL_MS = 3e4;
277
- var HeartbeatManager = class {
278
- connections = /* @__PURE__ */ new Map();
279
- timer;
280
- constructor(wss, store, intervalMs = DEFAULT_INTERVAL_MS) {
281
- this.wss = wss;
282
- this.store = store;
283
- this.timer = setInterval(() => this.check(), intervalMs);
284
- }
285
- trackConnection(ws) {
286
- this.connections.set(ws, {
287
- isAlive: true,
288
- projectId: null
289
- });
290
- ws.on("pong", () => {
291
- const meta = this.connections.get(ws);
292
- if (meta) meta.isAlive = true;
293
- });
294
- ws.on("close", () => {
295
- this.connections.delete(ws);
296
- });
297
- }
298
- setProjectId(ws, projectId) {
299
- const meta = this.connections.get(ws);
300
- if (meta) meta.projectId = projectId;
301
- }
302
- stop() {
303
- clearInterval(this.timer);
304
- this.connections.clear();
305
- }
306
- check() {
307
- for (const [ws, meta] of this.connections) {
308
- if (!meta.isAlive) {
309
- this.connections.delete(ws);
310
- ws.terminate();
311
- if (meta.projectId && !this.hasOtherConnection(ws, meta.projectId)) {
312
- console.error(`[wdyr-mcp] client for ${meta.projectId} is dead, clearing render data`);
313
- this.store.clearRenders(meta.projectId);
314
- }
315
- continue;
316
- }
317
- meta.isAlive = false;
318
- ws.ping();
319
- }
320
- }
321
- hasOtherConnection(deadWs, projectId) {
322
- for (const [ws, meta] of this.connections) if (ws !== deadWs && meta.projectId === projectId) return true;
323
- return false;
324
- }
325
- };
326
- //#endregion
327
- //#region src/server/ws.ts
328
- function createWsServer(port) {
329
- const wss = new WebSocketServer({
330
- port,
331
- host: "127.0.0.1"
332
- });
333
- const heartbeat = new HeartbeatManager(wss, store);
334
- wss.on("error", (err) => {
335
- if (err.code === "EADDRINUSE") console.error(`[wdyr-mcp] Port ${port} already in use, another instance owns the WS server. Skipping.`);
336
- else console.error("[wdyr-mcp] WS server error:", err);
337
- });
338
- wss.on("listening", () => {
339
- console.error(`[wdyr-mcp] WebSocket server listening on ws://localhost:${port}`);
340
- });
341
- wss.on("connection", (ws) => {
342
- console.error(`[wdyr-mcp] browser connected (ws://localhost:${port})`);
343
- heartbeat.trackConnection(ws);
344
- ws.on("message", (raw) => {
345
- try {
346
- const msg = JSON.parse(String(raw));
347
- if (msg.type === "render") {
348
- const projectId = msg.projectId ?? "default";
349
- heartbeat.setProjectId(ws, projectId);
350
- store.addRender(msg.payload, projectId, msg.commitId);
351
- }
352
- } catch {
353
- console.error("[wdyr-mcp] invalid message received");
354
- }
355
- });
356
- ws.on("close", () => {
357
- console.error("[wdyr-mcp] browser disconnected");
358
- });
359
- });
360
- wss.on("close", () => {
361
- heartbeat.stop();
362
- });
363
- return wss;
364
- }
365
- //#endregion
366
- //#region src/server/index.ts
367
- const DEFAULT_WS_PORT = 4649;
368
- const server = new McpServer({
369
- name: "why-did-you-render",
370
- version: "0.0.0"
371
- });
372
- registerTools(server);
373
- async function main() {
374
- createWsServer(Number(process.env.WDYR_WS_PORT) || DEFAULT_WS_PORT);
375
- const transport = new StdioServerTransport();
376
- await server.connect(transport);
377
- console.error("[wdyr-mcp] MCP server running on stdio");
378
- }
379
- main().catch((error) => {
380
- console.error("[wdyr-mcp] Fatal error:", error);
381
- process.exit(1);
382
- });
383
- //#endregion
384
- export {};
2
+ import{McpServer as e}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as t}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as n}from"zod";import{existsSync as r,mkdirSync as i,readFileSync as a,readdirSync as o,unlinkSync as s,writeFileSync as c}from"node:fs";import{homedir as l}from"node:os";import{join as u}from"node:path";import d from"xxhash-wasm";import f from"node:http";import{Server as p}from"socket.io";const m=`@@dict`,h=`@@ref:`;let g;const _=d().then(e=>{g=e.h64ToString});function v(){return _}function y(e){return g(JSON.stringify(e))}function b(e){return typeof e==`object`&&!!e}function x(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;if(b(n)){let e=y(n);t[e]??=n,n=`${h}${e}`}if(b(r)){let e=y(r);t[e]??=r,r=`${h}${e}`}return n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function S(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=x(n,t),o=x(r,t),s=x(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function C(e,t){return e?e.map(e=>{let{prevValue:n,nextValue:r}=e;return typeof n==`string`&&n.startsWith(h)&&(n=t[n.slice(6)]??n),typeof r==`string`&&r.startsWith(h)&&(r=t[r.slice(6)]??r),n===e.prevValue&&r===e.nextValue?e:{...e,prevValue:n,nextValue:r}}):!1}function w(e,t){let{propsDifferences:n,stateDifferences:r,hookDifferences:i}=e.reason,a=C(n,t),o=C(r,t),s=C(i,t);return a===n&&o===r&&s===i?e:{...e,reason:{propsDifferences:a,stateDifferences:o,hookDifferences:s}}}function T(e){if(!r(e))return[];let t=a(e,`utf-8`).split(`
3
+ `).filter(Boolean);if(t.length===0)return[];let n,i=0,o=JSON.parse(t[0]);`@@dict`in o&&(n=o[m],i=1);let s=t.slice(i).map(e=>JSON.parse(e));return n?s.map(e=>w(e,n)):s}function E(e){return e.replaceAll(/[^a-zA-Z0-9_.-]/g,`_`)}function D(e){return{project:e.projectId,displayName:e.displayName,reason:e.reason,...e.hookName!=null&&{hookName:e.hookName},...e.commitId!=null&&{commitId:e.commitId},...e.timestamp!=null&&{timestamp:e.timestamp}}}const O=`nocommit`,k=new class{dir;buffers=new Map;timers=new Map;dicts=new Map;bufferMeta=new Map;trackedComponents=new Map;wdyrConfigs=new Map;constructor(e){this.dir=e??u(l(),`.wdyr-mcp`,`renders`),i(this.dir,{recursive:!0})}addRender(e,t,n){let r={...e,projectId:t,timestamp:Date.now(),...n!=null&&{commitId:n}},i=this.bufferKey(t,n),a=this.buffers.get(i);a||(a=[],this.buffers.set(i,a),this.bufferMeta.set(i,{projectId:t,commitId:n})),a.push(r);let o=this.timers.get(i);o&&clearTimeout(o),this.timers.set(i,setTimeout(()=>{this.flushAsync(t,n).catch(e=>console.error(`[wdyr-mcp] flush error for ${i}:`,e))},200))}async flushAsync(e,t){await v(),this.flush(e,t)}flush(e,t){if(e!=null&&t!==void 0)this.flushBuffer(this.bufferKey(e,t));else if(e!=null)for(let t of this.bufferKeysForProject(e))this.flushBuffer(t);else for(let e of[...this.buffers.keys()])this.flushBuffer(e)}flushBuffer(e){let t=this.buffers.get(e);if(!t||t.length===0)return;let n=this.bufferMeta.get(e);if(!n)return;let r=this.dicts.get(e);r||(r={},this.dicts.set(e,r));let i=t.map(e=>S(e,r)),a=this.commitFile(n.projectId,n.commitId),o=this.readDataLines(a),s=i.map(e=>JSON.stringify(e)),l=[...o,...s];c(a,`${(Object.keys(r).length>0?[JSON.stringify({[m]:r}),...l]:l).join(`
4
+ `)}\n`),t.length=0;let u=this.timers.get(e);u&&(clearTimeout(u),this.timers.delete(e))}readDataLines(e){return r(e)?a(e,`utf-8`).split(`
5
+ `).filter(e=>!(!e||e.startsWith(`{"@@dict"`))):[]}getAllRenders(e){return this.flush(e),e?this.projectFiles(e).flatMap(e=>T(u(this.dir,e)).map(D)):this.jsonlFiles().flatMap(e=>T(u(this.dir,e)).map(D))}getRendersByComponent(e,t){return this.getAllRenders(t).filter(t=>t.displayName===e)}clearRenders(e){if(e){for(let t of this.bufferKeysForProject(e)){this.buffers.delete(t),this.dicts.delete(t),this.bufferMeta.delete(t);let e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}for(let t of this.projectFiles(e))s(u(this.dir,t))}else{for(let[,e]of this.timers)clearTimeout(e);this.buffers.clear(),this.timers.clear(),this.dicts.clear(),this.bufferMeta.clear();for(let e of this.jsonlFiles())s(u(this.dir,e))}}clearRendersByComponent(e,t){this.flush(t);let n=t?this.projectFiles(t):this.jsonlFiles(),r=0;for(let t of n){let n=u(this.dir,t),i=T(n),a=i.length,o=i.filter(t=>t.displayName!==e);r+=a-o.length,o.length===0?(s(n),this.clearBuffersForFile(t)):o.length<a&&(this.rewriteFile(n,o),this.clearBuffersForFile(t))}return r}clearRendersByCommit(e,t){this.flush(t);let n=t?this.projectFiles(t):this.jsonlFiles(),r=0;for(let t of n){let n=this.parseFilename(t);n?.commitId!=null&&n.commitId<e&&(s(u(this.dir,t)),this.clearBuffersForFile(t),r++)}return r}getProjects(){this.flush();let e=new Set,t=new Set;for(let n of this.jsonlFiles()){let r=this.parseFilename(n);if(!r||t.has(r.projectSanitized))continue;t.add(r.projectSanitized);let i=a(u(this.dir,n),`utf-8`).split(`
6
+ `);for(let t of i){if(!t)continue;let n=JSON.parse(t);if(!(`@@dict`in n)){e.add(n.projectId);break}}}return[...e]}getCommitIds(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=new Set;for(let e of t){let t=this.parseFilename(e);t?.commitId!=null&&n.add(t.commitId)}return[...n].sort((e,t)=>e-t)}getCommits(e){this.flush(e);let t=e?this.projectFiles(e):this.jsonlFiles(),n=[];for(let e of t){let t=this.parseFilename(e);if(t?.commitId==null)continue;let r=T(u(this.dir,e));r.length!==0&&n.push({commitId:t.commitId,timestamp:r.find(e=>e.timestamp!=null)?.timestamp??null,renderCount:r.length,components:[...new Set(r.map(e=>e.displayName))]})}return n.sort((e,t)=>e.commitId-t.commitId)}getRendersByCommit(e,t){if(t)return this.flush(t,e),T(this.commitFile(t,e)).map(D);this.flush();let n=`_commit_${e}.jsonl`;return this.jsonlFiles().filter(e=>e.endsWith(n)).flatMap(e=>T(u(this.dir,e)).map(D))}getSummary(e){let t=this.getAllRenders(e),n={};for(let e of t){n[e.project]??={};let t=n[e.project];t[e.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=t[e.displayName];r.count++,Array.isArray(e.reason.propsDifferences)&&r.reasons.props++,Array.isArray(e.reason.stateDifferences)&&r.reasons.state++,Array.isArray(e.reason.hookDifferences)&&r.reasons.hooks++}return n}getSummaryByCommit(e){let t=this.getAllRenders(e),n={};for(let e of t){if(e.commitId==null)continue;n[e.project]??={},n[e.project][e.commitId]??={};let t=n[e.project][e.commitId];t[e.displayName]??={count:0,reasons:{props:0,state:0,hooks:0}};let r=t[e.displayName];r.count++,Array.isArray(e.reason.propsDifferences)&&r.reasons.props++,Array.isArray(e.reason.stateDifferences)&&r.reasons.state++,Array.isArray(e.reason.hookDifferences)&&r.reasons.hooks++}return n}setTrackedComponents(e,t){this.trackedComponents.set(t,e)}getTrackedComponents(e){let t={},n=e?[e]:this.getProjects();for(let e of n){let n=[...new Set(this.getAllRenders(e).map(e=>e.displayName))];t[e]={registered:this.trackedComponents.get(e)??[],observed:n}}return t}setWdyrConfig(e,t){this.wdyrConfigs.set(t,e)}getWdyrConfig(e){let t={};if(e){let n=this.wdyrConfigs.get(e);n&&(t[e]=n)}else for(let[e,n]of this.wdyrConfigs)t[e]=n;return t}rewriteFile(e,t){c(e,`${t.map(e=>JSON.stringify(e)).join(`
7
+ `)}\n`)}clearBuffersForFile(e){let t=this.parseFilename(e);if(t)for(let[e,n]of this.bufferMeta){if(E(n.projectId)!==t.projectSanitized||!(t.commitId==null?n.commitId==null:n.commitId===t.commitId))continue;this.buffers.delete(e),this.dicts.delete(e),this.bufferMeta.delete(e);let r=this.timers.get(e);r&&(clearTimeout(r),this.timers.delete(e))}}bufferKey(e,t){return`${e}\0${t??O}`}bufferKeysForProject(e){let t=`${e}\0`;return[...this.buffers.keys()].filter(e=>e.startsWith(t))}commitFile(e,t){let n=E(e),r=t==null?`_${O}`:`_commit_${t}`;return u(this.dir,`${n}${r}.jsonl`)}projectFiles(e){let t=E(e);return o(this.dir).filter(e=>e.startsWith(t)&&e.endsWith(`.jsonl`))}parseFilename(e){if(!e.endsWith(`.jsonl`))return null;let t=e.slice(0,-6),n=t.match(/^(.+)_commit_(\d+)$/);if(n)return{projectSanitized:n[1],commitId:Number(n[2])};let r=t.match(/^(.+)_nocommit$/);return r?{projectSanitized:r[1]}:{projectSanitized:t}}jsonlFiles(){return o(this.dir).filter(e=>e.endsWith(`.jsonl`))}};function A(e){if(e)return{projectId:e};let t=k.getProjects();return t.length===0?{projectId:void 0}:t.length===1?{projectId:t[0]}:{projectId:void 0,error:[`Multiple projects are recording render data. Ask the user which project they are working on (e.g. their dev server URL like http://localhost:3000).`,``,`Active projects:`,...t.map(e=>`- ${e}`)].join(`
8
+ `)}}function j(e){return{content:[{type:`text`,text:e}]}}function M(e){e.registerTool(`clear_renders`,{title:`Clear Renders`,description:`Clears collected render data. Supports filtering by component name or by commit ID threshold. When no filter is given, clears all data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),component:n.string().optional().describe(`Clear only renders for this component (by displayName).`),beforeCommit:n.number().optional().describe(`Clear all renders from commits with an ID strictly less than this value.`)}},async({project:e,component:t,beforeCommit:n})=>{let r=A(e);return r.error?j(r.error):t?j(`Cleared ${k.clearRendersByComponent(t,r.projectId)} render(s) for component "${t}".`):n==null?(k.clearRenders(r.projectId),j(r.projectId?`Render data cleared for ${r.projectId}.`:`All render data cleared.`)):j(`Cleared renders from ${k.clearRendersByCommit(n,r.projectId)} commit file(s) before commit #${n}.`)})}function N(e){e.registerTool(`get_commits`,{title:`Get Commits`,description:`Returns a list of React commit IDs that have recorded render data for a project. Use these IDs with get_renders_by_commit to inspect individual commits.`,inputSchema:{project:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=A(e);if(t.error)return j(t.error);let n=k.getCommits(t.projectId);return n.length===0?j(`No commits recorded yet. Make sure the browser is connected and triggering re-renders.`):j(JSON.stringify(n,null,2))})}function P(e){e.registerTool(`get_projects`,{title:`Get Projects`,description:`Returns a list of project identifiers (browser origin URLs) that have recorded render data.`,inputSchema:{}},async()=>{let e=k.getProjects();return e.length===0?j(`No projects have recorded render data yet.`):j(`Active projects:\n${e.map(e=>`- ${e}`).join(`
9
+ `)}`)})}function F(e){e.registerTool(`get_render_summary`,{title:`Get Render Summary`,description:`Returns a summary of re-renders grouped by component name with counts. Use groupBy: 'commit' to get per-commit breakdowns instead of a single aggregate. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`),groupBy:n.enum([`commit`]).optional().describe(`Group results by commit. When set to 'commit', returns per-commit render summaries instead of a single aggregate.`)}},async({project:e,groupBy:t})=>{let n=A(e);return n.error?j(n.error):t===`commit`?R(n.projectId):L(n.projectId)})}function I(e){let t=[];return e.props>0&&t.push(`props: ${e.props}`),e.state>0&&t.push(`state: ${e.state}`),e.hooks>0&&t.push(`hooks: ${e.hooks}`),t.length>0?` — ${t.join(`, `)}`:``}function L(e){let t=k.getSummary(e);if(Object.keys(t).length===0)return j(`No renders recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);for(let[e,{count:t,reasons:i}]of Object.entries(r))n.push(` ${e}: ${t} re-render(s)${I(i)}`)}return j(`Re-render summary:\n\n${n.join(`
10
+ `)}`)}function R(e){let t=k.getSummaryByCommit(e);if(Object.keys(t).length===0)return j(`No renders with commit IDs recorded yet.`);let n=[];for(let[e,r]of Object.entries(t)){n.push(`[${e}]`);let t=Object.keys(r).map(Number).sort((e,t)=>e-t);for(let e of t){let t=r[e],i=Object.values(t).reduce((e,t)=>e+t.count,0);n.push(` Commit #${e} (${i} re-render(s)):`);for(let[e,{count:r,reasons:i}]of Object.entries(t))n.push(` ${e}: ${r}${I(i)}`)}}return j(`Re-render summary (by commit):\n\n${n.join(`
11
+ `)}`)}function z(e){e.registerTool(`get_renders_by_commit`,{title:`Get Renders by Commit`,description:`Returns all re-renders for a specific React commit ID. Use get_commits first to discover available commit IDs.`,inputSchema:{commitId:n.number().describe(`The React commit ID to filter by.`),component:n.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({commitId:e,component:t,project:n})=>{let r=A(n);if(r.error)return j(r.error);let i=k.getRendersByCommit(e,r.projectId);return t&&(i=i.filter(e=>e.displayName===t)),i.length===0?j(t?`No renders recorded for component "${t}" in commit ${e}.`:`No renders recorded for commit ${e}.`):j(JSON.stringify(i,null,2))})}function B(e){e.registerTool(`get_renders`,{title:`Get Renders`,description:`Returns all re-renders collected from the browser. If multiple projects are active and no project is specified, the tool will ask you to disambiguate by asking the user for their dev server URL.`,inputSchema:{component:n.string().optional().describe(`Filter by component name. Omit to get all renders.`),project:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({component:e,project:t})=>{let n=A(t);if(n.error)return j(n.error);let r=e?k.getRendersByComponent(e,n.projectId):k.getAllRenders(n.projectId);return r.length===0?j(e?`No renders recorded for "${e}".`:`No renders recorded yet. Make sure the browser is connected and triggering re-renders.`):j(JSON.stringify(r,null,2))})}function V(e){let t=[];if(e.include?.length){t.push(` include:`);for(let n of e.include)t.push(` - /${n}/`)}if(e.exclude?.length){t.push(` exclude:`);for(let n of e.exclude)t.push(` - /${n}/`)}if(e.trackAllPureComponents!=null&&t.push(` trackAllPureComponents: ${e.trackAllPureComponents}`),e.trackHooks!=null&&t.push(` trackHooks: ${e.trackHooks}`),e.trackExtraHooks?.length){t.push(` trackExtraHooks:`);for(let n of e.trackExtraHooks)t.push(` - ${n}`)}return e.logOnDifferentValues!=null&&t.push(` logOnDifferentValues: ${e.logOnDifferentValues}`),e.logOwnerReasons!=null&&t.push(` logOwnerReasons: ${e.logOwnerReasons}`),t}function H(e){e.registerTool(`get_tracked_components`,{title:`Get Tracked Components`,description:`Returns the why-did-you-render configuration for the connected project, including include/exclude filters and tracking options. Also shows components observed in render data. If multiple projects are active and no project is specified, the tool will ask you to disambiguate.`,inputSchema:{project:n.string().optional().describe(`Project identifier (the browser's origin URL, e.g. http://localhost:3000). Omit to auto-detect.`)}},async({project:e})=>{let t=A(e);if(t.error)return j(t.error);let n=k.getWdyrConfig(t.projectId),r=k.getTrackedComponents(t.projectId),i=Object.keys(n).length>0,a=Object.keys(r).length>0;if(!i&&!a)return j(`No configuration or tracked components found. Make sure the browser is connected and triggering re-renders.`);let o=[],s=new Set([...Object.keys(n),...Object.keys(r)]);for(let e of s){o.push(`[${e}]`);let t=n[e];if(t){o.push(`Configuration:`);let e=V(t);e.length>0?o.push(...e):o.push(` (default options)`)}let i=r[e];if(i?.observed.length){o.push(`Observed in renders:`);for(let e of i.observed)o.push(` - ${e}`)}}return j(o.join(`
12
+ `))})}function U(e){B(e),F(e),N(e),z(e),P(e),H(e),M(e)}function W(e){let t=f.createServer(),n=new p(t,{cors:{origin:`*`},serveClient:!1});return n.on(`connection`,t=>{console.error(`[wdyr-mcp] browser connected (http://localhost:${e})`),t.data.projectId=null,t.on(`render`,(e,n,r)=>{t.data.projectId=n,k.addRender(e,n,r)}),t.on(`render-batch`,(e,n,r)=>{t.data.projectId=n;for(let t of e)k.addRender(t,n,r)}),t.on(`register`,(e,n)=>{t.data.projectId=n,k.setTrackedComponents(e,n)}),t.on(`config`,(e,n)=>{t.data.projectId=n,k.setWdyrConfig(e,n)}),t.on(`disconnect`,()=>{console.error(`[wdyr-mcp] browser disconnected`);let e=t.data.projectId;e&&([...n.sockets.sockets.values()].some(n=>n.id!==t.id&&n.data.projectId===e)||(console.error(`[wdyr-mcp] last client for ${e} disconnected, clearing render data`),k.clearRenders(e)))})}),t.on(`error`,t=>{t.code===`EADDRINUSE`?console.error(`[wdyr-mcp] Port ${e} already in use, another instance owns the WS server. Skipping.`):console.error(`[wdyr-mcp] server error:`,t)}),t.listen(e,`127.0.0.1`,()=>{console.error(`[wdyr-mcp] socket.io server listening on http://localhost:${e}`)}),n}const G=new e({name:`why-did-you-render`,version:`0.0.0`});U(G);async function K(){let e=W(Number(process.env.WDYR_WS_PORT)||4649),n=new t;await G.connect(n),console.error(`[wdyr-mcp] MCP server running on stdio`);let r=!1;async function i(){r||(r=!0,console.error(`[wdyr-mcp] Shutting down…`),e?.close(),await G.close(),process.exit(0))}process.stdin.on(`end`,i),process.on(`SIGTERM`,i),process.on(`SIGINT`,i)}K().catch(e=>{console.error(`[wdyr-mcp] Fatal error:`,e),process.exit(1)});export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0x1f320.sh/why-did-you-render-mcp",
3
- "version": "1.0.0-dev.2",
3
+ "version": "1.0.0-dev.20",
4
4
  "type": "module",
5
5
  "description": "MCP server that collects why-did-you-render data from browser and exposes it to coding agents",
6
6
  "license": "MIT",
@@ -34,9 +34,7 @@
34
34
  "require": "./dist/client/index.cjs"
35
35
  }
36
36
  },
37
- "files": [
38
- "dist"
39
- ],
37
+ "files": ["dist"],
40
38
  "scripts": {
41
39
  "build": "tsdown",
42
40
  "dev": "tsdown --watch",
@@ -49,13 +47,18 @@
49
47
  },
50
48
  "dependencies": {
51
49
  "@modelcontextprotocol/sdk": "^1.12.1",
52
- "ws": "^8.18.0",
50
+ "error-stack-parser": "^2.1.4",
51
+ "socket.io": "^4.8.3",
52
+ "socket.io-client": "^4.8.3",
53
+ "xxhash-wasm": "^1.1.0",
53
54
  "zod": "^3.24.4"
54
55
  },
55
56
  "devDependencies": {
56
57
  "@biomejs/biome": "^1.9.4",
58
+ "@semantic-release/changelog": "^6.0.3",
59
+ "@semantic-release/exec": "^7.1.0",
60
+ "@semantic-release/git": "^10.0.1",
57
61
  "@types/node": "^22.14.1",
58
- "@types/ws": "^8.18.0",
59
62
  "@vitest/coverage-v8": "^4.1.2",
60
63
  "semantic-release": "^25.0.3",
61
64
  "tsdown": "^0.12.4",