Skip to content

kaizen: remove eslint-disable for no-unused-vars in PrimitiveDetail#166

Open
gabrypavanello wants to merge 6 commits intomainfrom
kaizen/2026-02-11
Open

kaizen: remove eslint-disable for no-unused-vars in PrimitiveDetail#166
gabrypavanello wants to merge 6 commits intomainfrom
kaizen/2026-02-11

Conversation

@gabrypavanello
Copy link
Contributor

Rename destructured kind to _kind to leverage the existing varsIgnorePattern: '^_' in eslint config, removing an unnecessary suppression comment.

File: packages/inspector/src/dashboard/react/components/PrimitiveDetail.tsx

Build ✅ | Tests ✅ (74/74)

Sirius added 6 commits February 10, 2026 09:03
…SK-037-02)

Replace all raw console.log/warn/error calls across 17 inspector/src
files with scoped logger instances using createLogger(). Each module
gets a descriptive source name for log filtering.

- 17 files migrated to structured logger
- Stale eslint-disable no-console comments removed
- Tests updated to match new console.info output format
- bin/mcp-inspector.ts and widget-server-templates.ts untouched
- proxy-resources.ts skipped (console call is in client-side template)
…iveDetail

Rename destructured `kind` to `_kind` to leverage the existing
varsIgnorePattern (^_) in eslint config, eliminating the suppression comment.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 11, 2026

📝 Walkthrough

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced structured logging system configurable via the MCP_APPS_LOG_LEVEL environment variable.
    • Logs now include timestamps and source identifiers for improved observability.
  • Tests

    • Added comprehensive test suite for the logging system.

Walkthrough

This PR introduces a structured, environment-configurable logging system with level-based filtering and timestamp formatting. It adds a new logger module, exposes public logging utilities, and migrates all console-based logging across multiple packages to use the standardized logger instead.

Changes

Cohort / File(s) Summary
New Logger Infrastructure
packages/inspector/src/debug/logger.ts
Introduces LogLevel type, Logger interface with debug/info/warn/error methods, createLogger() factory, and defaultLogger instance. Supports MCP_APPS_LOG_LEVEL environment variable for threshold-based filtering and adds timestamp/level/source prefixes to all output.
Inspector Core Services
packages/inspector/src/connection.ts, packages/inspector/src/dual-server.ts, packages/inspector/src/widget-server.ts, packages/inspector/src/widget-session-manager.ts
Replace console.log/warn with logger-based calls across connection lifecycle, request handling, server startup/shutdown, and session management flows.
Inspector Session & Rendering
packages/inspector/src/session/session-renderer.ts, packages/inspector/src/session/session-store.ts
Replace console logging with logger.info/warn in dialog handling, viewport resizing, message delivery, validation, and session lifecycle management.
Inspector Host Emulators
packages/inspector/src/hosts/mcp-host.ts, packages/inspector/src/hosts/openai-host.ts
Replace console.log with logger.info for postMessage handling, UI initialization, tool execution, and display mode changes in both MCP and OpenAI host emulators.
Inspector Dashboard & Tools
packages/inspector/src/dashboard/cdp-streamer.ts, packages/inspector/src/tools/call-tool.ts, packages/inspector/src/tools/widget-control.ts, packages/inspector/src/proxy-tools.ts
Replace console logging with logger calls for CDP streaming frames, widget rendering, tool execution, and session error handling.
Inspector OAuth Module
packages/inspector/src/oauth/preset-config.ts, packages/inspector/src/oauth/provider.ts, packages/inspector/src/oauth/wellknown-proxy.ts
Replace console.log with logger.info in OAuth provider initialization and browser launch error handling.
Minor UI Component Cleanup
packages/inspector/src/dashboard/react/components/PrimitiveDetail.tsx
Rename unused variable kind to _kind to avoid linter warnings.
Public API & Re-exports
packages/inspector/src/index.ts
Export createLogger, defaultLogger, Logger type, and LogLevel type for public consumption.
Codegen Package Logging
packages/codegen/src/watcher.ts
Replace simple console-based defaultLogger with structured, level-driven logger respecting MCP_APPS_LOG_LEVEL.
Cross-Package Lightweight Loggers
packages/testing/src/eval/mcp/evaluator.ts, packages/ui-react/src/hooks.ts
Implement scoped lightweight loggers with warn methods to avoid cross-package dependencies while maintaining consistent logging behavior.
Logger Test Coverage
packages/inspector/tests/logger.test.ts, packages/inspector/tests/widget-session-manager.test.ts
Add comprehensive tests for logger module (levels, filtering, formatting, argument forwarding) and update session-manager tests to expect logger output.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 68.42% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main change: removing an eslint-disable comment by renaming a destructured variable to follow the existing ESLint pattern.
Description check ✅ Passed The description is directly related to the changeset, explaining the variable rename in PrimitiveDetail.tsx and its purpose in removing an unnecessary eslint-disable comment.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch kaizen/2026-02-11

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


Comment @coderabbitai help to get the list of available commands and usage tips.

@claude
Copy link
Contributor

claude bot commented Feb 11, 2026

Code Review: PR #166 - Kaizen: Remove eslint-disable for no-unused-vars in PrimitiveDetail

Summary

This PR introduces a structured logging system across the codebase and makes a clean code improvement by eliminating an unnecessary ESLint suppression comment. The overall implementation is solid and aligns well with the repository's standards.

✅ Strengths

1. Excellent Structured Logging Design

  • Clean API: The createLogger(source) factory pattern is elegant and provides consistent structured output
  • Environment-driven configuration: Using MCP_APPS_LOG_LEVEL for runtime control is a best practice
  • Level gating: Proper log level hierarchy with efficient early-exit checks
  • Type-safe: Full TypeScript support with proper LogLevel type and Logger interface

2. Comprehensive Test Coverage

  • logger.test.ts provides thorough coverage of all log levels and edge cases
  • Tests use proper mocking and cleanup patterns

3. Consistent Migration Pattern

  • Replaced raw console.log/warn/error calls with scoped loggers across 17+ files
  • Removed stale eslint-disable no-console comments systematically
  • Each module gets a descriptive source name

4. Clean Code Win (PrimitiveDetail.tsx)

  • Leverages existing varsIgnorePattern: '^_' in ESLint config—no suppression needed
  • Small change, high readability improvement

⚠️ Issues & Concerns

🔴 Critical: Code Duplication Across Packages

Location: packages/codegen/src/watcher.ts, packages/testing/src/eval/mcp/evaluator.ts, packages/ui-react/src/hooks.ts

Problem: The logger implementation is duplicated inline in 3 packages that don't depend on @mcp-apps-kit/inspector

Impact:

  • DRY violation: 4 separate implementations of the same logging logic
  • Maintenance burden: Bug fixes require 4 separate changes
  • Inconsistency risk: Implementations could drift over time
  • Violates AGENTS.md: "AVOID cross-package circular dependencies; prefer moving shared utilities down"

Recommendation:

  1. Extract to shared package: Create packages/logger or add to packages/core
  2. Single source of truth: All packages import from one location

Alternative (if keeping duplication):

  • Document why duplication is intentional
  • Add comment explaining the rationale

🟡 Minor: Test Assertion Format

Location: packages/inspector/tests/widget-session-manager.test.ts:229-250

The test checks for two separate console arguments, but verify this matches the actual logger output format which concatenates prefix + message into one string.


🟡 Minor: Missing JSDoc

Add JSDoc to the public createLogger API since it's exported from inspector/index.ts


🔍 Security & Performance

No Security Concerns

  • No sensitive data exposure
  • No injection vulnerabilities
  • Safe environment variable usage

Performance

  • Efficient log level gating prevents expensive operations
  • Minimal overhead

🎯 Recommendations Summary

Must Fix (Before Merge)

  1. Resolve code duplication: Extract logger to shared package OR document why duplication is intentional
  2. Verify test assertions: Ensure they match actual logger output format

Should Fix (Before Merge)

  1. Add JSDoc: Document public createLogger API
  2. Verify build: Run pnpm build && pnpm test && pnpm lint && pnpm typecheck

🏆 Overall Assessment

Quality: ⭐⭐⭐⭐☆ (4/5)

Verdict: This is a well-designed, thoroughly-tested improvement. The structured logging system is production-ready and the code cleanup is exemplary. The code duplication issue is the main blocker—once addressed, this PR will be excellent.

Effort: ~454 additions, 191 deletions across 24 files. Impressive consistency.


Thanks for this solid contribution! The logging infrastructure will greatly improve debugging and observability. Please address the duplication concern and we're good to merge. 🚀

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
packages/inspector/src/session/session-renderer.ts (3)

206-217: ⚠️ Potential issue | 🟠 Major

Use console.info instead of logger.info inside page.evaluate (browser context).

The logger object is defined at the module level in Node.js and is not accessible within page.evaluate, which runs in the browser context. Calling logger.info() will throw a ReferenceError, breaking the host-context update. Use console.info instead.

Proposed fix
-      logger.info("[MCP Host] Sent ui/notifications/host-context-changed", ctx);
+      console.info("[MCP Host] Sent ui/notifications/host-context-changed", ctx);

282-332: ⚠️ Potential issue | 🟠 Major

Replace logger.info() calls with console.info() inside page.evaluate().

The logger object is defined in server-side code and is not available in the browser context where page.evaluate() executes. Attempting to call logger.info() will throw a ReferenceError. Use console.info() instead, which is always available in browser context.

Proposed fix (use console in page context)
-      logger.info("[MCP Host] Tool response is not a valid object:", responseData);
+      console.info("[MCP Host] Tool response is not a valid object:", responseData);
...
-      logger.info("[MCP Host] Tool response missing valid name/toolName string:", responseData);
+      console.info("[MCP Host] Tool response missing valid name/toolName string:", responseData);
...
-      logger.info("[MCP Host] No pending calls for tool:", toolName);
+      console.info("[MCP Host] No pending calls for tool:", toolName);
...
-      logger.info("[MCP Host] Delivered synced tool response:", toolName, call.messageId);
+      console.info("[MCP Host] Delivered synced tool response:", toolName, call.messageId);

250-256: ⚠️ Potential issue | 🟠 Major

Use console.info() instead of logger.info() in browser context.

The logger object is scoped to the Node.js renderer process and is not available within page.evaluate(), which executes code in an isolated browser context. This will throw a ReferenceError at runtime.

Proposed fix
-      logger.info("[OpenAI Host] Sent globals sync:", message.data);
+      console.info("[OpenAI Host] Sent globals sync:", message.data);

Note: This pattern occurs multiple times throughout this file (at least 5 other instances). Consider a broader audit to replace all logger calls within page.evaluate() blocks with console methods.

packages/inspector/src/hosts/mcp-host.ts (1)

220-281: ⚠️ Potential issue | 🟠 Major

Replace logger calls with console in Playwright init script.

The init script executes in the browser page context where logger is undefined, causing runtime errors. Use console.info() instead.

Proposed fix
-                logger.info('[MCP Host Emulator] Received ui/initialize, responding...');
+                console.info('[MCP Host Emulator] Received ui/initialize, responding...');
...
-                logger.info('[MCP Host Emulator] Sent ui/initialize response');
+                console.info('[MCP Host Emulator] Sent ui/initialize response');
...
-                  logger.info('[MCP Host Emulator] Sending ui/notifications/tool-result...');
+                  console.info('[MCP Host Emulator] Sending ui/notifications/tool-result...');
...
-                  logger.info('[MCP Host Emulator] Display mode changed to:', requestedMode, 'sizing:', sizing);
+                  console.info('[MCP Host Emulator] Display mode changed to:', requestedMode, 'sizing:', sizing);
🤖 Fix all issues with AI agents
In `@packages/inspector/src/hosts/openai-host.ts`:
- Line 248: Inside the template returned by getPlaywrightInitScript(), replace
the page-context log call that uses logger.info(...) with console.info(...) so
requestDisplayMode() will not throw in the browser page; update any occurrences
inside the getPlaywrightInitScript() string (including the requestDisplayMode
function body) to use console.info and ensure no other references to the
module-scoped logger remain in that injected script.

In `@packages/inspector/src/widget-session-manager.ts`:
- Around line 412-413: The logger.info calls inside page.evaluate are running in
the browser VM and will throw ReferenceError; locate each page.evaluate(...)
invocation in widget-session-manager.ts (the calls that currently contain
logger.info("[MCP Host] Sent ui/notifications/host-context-changed", ctx) and
the other similar messages at the affected locations) and move the
logger.info(...) out of the evaluate callback to run in Node context instead —
modify the evaluate functions to return a success flag or result (e.g.,
true/false or the ctx) and then call logger.info(...) after await
page.evaluate(...) using that returned value; ensure all occurrences listed (the
blocks around the shown log strings) follow this pattern so no logger is
referenced inside the page.evaluate scope.

In `@packages/ui-react/src/hooks.ts`:
- Around line 22-33: The eslint disable is placed on the wrong line and
`process` is used as a free global; update the uiReactLogger initialization to
check for process via globalThis (e.g., guard with typeof globalThis.process !==
"undefined") and derive envLevel from globalThis.process.env safely, remove the
incorrect eslint-disable comment, and keep the rest of the logic in
uiReactLogger (references: uiReactLogger, envLevel, LEVELS, threshold, ok, ts)
so ESLint no-undef no longer flags `process`.

}));

console.log('[OpenAI Host] requestDisplayMode:', mode, 'sizing:', sizing);
logger.info('[OpenAI Host] requestDisplayMode:', mode, 'sizing:', sizing);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file structure and the specific file mentioned
fd -t f "openai-host.ts" packages/inspector/src/

Repository: AndurilCode/mcp-apps-kit

Length of output: 111


🏁 Script executed:

# Read the file to understand the context around line 248
wc -l packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 115


🏁 Script executed:

# Read the file with context around line 248
sed -n '240,260p' packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 640


🏁 Script executed:

# Read a broader context to understand the function structure
sed -n '220,280p' packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 2157


🏁 Script executed:

# Check the imports at the top of the file
head -30 packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 795


🏁 Script executed:

# Look for more context - see the broader structure and how this object is used
sed -n '180,220p' packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 1247


🏁 Script executed:

# Check if there's any Playwright or page context setup
grep -n "page\|context\|addInitScript\|evaluate" packages/inspector/src/hosts/openai-host.ts | head -20

Repository: AndurilCode/mcp-apps-kit

Length of output: 141


🏁 Script executed:

# Look for where this object is being used/returned
grep -n "requestDisplayMode\|window\.__openaiEmulator" packages/inspector/src/hosts/openai-host.ts | head -20

Repository: AndurilCode/mcp-apps-kit

Length of output: 1390


🏁 Script executed:

# Look at the function that generates the init script
sed -n '95,155p' packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 2615


🏁 Script executed:

# Search for how this script is being injected into the page
grep -n "addInitScript\|evaluateHandle\|evaluate\|JSON.stringify" packages/inspector/src/hosts/openai-host.ts | head -30

Repository: AndurilCode/mcp-apps-kit

Length of output: 1150


🏁 Script executed:

# Let's see the return statement and how the script string is constructed
sed -n '128,160p' packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 1238


🏁 Script executed:

# Check the end of the function to see how the script is returned
sed -n '295,310p' packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 654


🏁 Script executed:

# Check where this init script is actually used/injected
grep -n "getPlaywrightInitScript\|addInitScript" packages/inspector/src/hosts/openai-host.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 183


🏁 Script executed:

# Also search in other files to see how this is being used
rg "getPlaywrightInitScript\|addInitScript" packages/inspector/src/ -B 2 -A 2

Repository: AndurilCode/mcp-apps-kit

Length of output: 50


🏁 Script executed:

# Let's verify that logger is indeed a Node.js logger not available in page context
sed -n '1,25p' packages/inspector/src/hosts/openai-host.ts | grep -A 2 "createLogger"

Repository: AndurilCode/mcp-apps-kit

Length of output: 215


🏁 Script executed:

# Let's confirm the exact structure - check if logger.info is within the template literal string
sed -n '128,310p' packages/inspector/src/hosts/openai-host.ts | grep -n "logger\|console" -B 2 -A 2

Repository: AndurilCode/mcp-apps-kit

Length of output: 240


🏁 Script executed:

# Check the debug/logger module to understand what createLogger does
cat packages/inspector/src/debug/logger.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 2974


🏁 Script executed:

# Let me verify the exact line numbers and structure
# Show the full template literal to understand the scope
sed -n '128,310p' packages/inspector/src/hosts/openai-host.ts | head -100

Repository: AndurilCode/mcp-apps-kit

Length of output: 3191


🏁 Script executed:

# Count backticks to verify we're in a template literal
sed -n '128,310p' packages/inspector/src/hosts/openai-host.ts | grep -c '`'

Repository: AndurilCode/mcp-apps-kit

Length of output: 69


🏁 Script executed:

# Search for where the opening backtick is and closing backtick
sed -n '128,310p' packages/inspector/src/hosts/openai-host.ts | tail -20

Repository: AndurilCode/mcp-apps-kit

Length of output: 761


🏁 Script executed:

# Let's check if there are other logger calls within the template literal
sed -n '128,305p' packages/inspector/src/hosts/openai-host.ts | grep "logger\."

Repository: AndurilCode/mcp-apps-kit

Length of output: 154


🏁 Script executed:

# Check if logger is used anywhere else in the init script string
sed -n '128,310p' packages/inspector/src/hosts/openai-host.ts | grep -n "logger" -B 1 -A 1

Repository: AndurilCode/mcp-apps-kit

Length of output: 202


Replace logger.info() with console.info() in page context.

The getPlaywrightInitScript() method returns a template literal string that will be injected into the browser page via Playwright. The logger variable is not available in the page context—it's defined only in the Node.js module scope. When requestDisplayMode() is called, this will throw ReferenceError: logger is not defined and break the emulator flow. Use console.info() instead, which is natively available in the page.

Proposed fix
-            logger.info('[OpenAI Host] requestDisplayMode:', mode, 'sizing:', sizing);
+            console.info('[OpenAI Host] requestDisplayMode:', mode, 'sizing:', sizing);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
logger.info('[OpenAI Host] requestDisplayMode:', mode, 'sizing:', sizing);
console.info('[OpenAI Host] requestDisplayMode:', mode, 'sizing:', sizing);
🤖 Prompt for AI Agents
In `@packages/inspector/src/hosts/openai-host.ts` at line 248, Inside the template
returned by getPlaywrightInitScript(), replace the page-context log call that
uses logger.info(...) with console.info(...) so requestDisplayMode() will not
throw in the browser page; update any occurrences inside the
getPlaywrightInitScript() string (including the requestDisplayMode function
body) to use console.info and ensure no other references to the module-scoped
logger remain in that injected script.

Comment on lines +412 to 413
logger.info("[MCP Host] Sent ui/notifications/host-context-changed", ctx);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Playwright page.evaluate execution context Node variables access browser

💡 Result:

page.evaluate() runs inside the browser page’s JavaScript VM, while your Playwright test code runs in Node.js. These environments don’t intersect, so variables/functions from Node (e.g., const x = ...) are not directly accessible inside evaluate() unless you explicitly send them in. (playwright.dev)

1) Pass Node values into the page via the argument

const data = { startDate: '2026-02-11' };

await page.evaluate(({ startDate }) => {
  // runs in the browser
  window.localStorage.setItem('startDate', startDate);
}, data);

Playwright evaluate() takes a single optional argument (serializable values and/or handles). (playwright.dev)

(Stack Overflow explanation of the same pitfall + fix.) (stackoverflow.com)

2) If you need to call back into Node from the page, expose a function/binding

Use exposeFunction/exposeBinding to install a function on window that executes in Node when called from the page. (playwright.dev)

await page.context().exposeFunction('sha256', (text: string) => /* node code */ text);

await page.evaluate(async () => {
  const hash = await (window as any).sha256('hello'); // calls Node
  return hash;
});

If you tell me your exact goal (read a Node variable? call a Node function? access filesystem/env?), I can suggest the cleanest pattern.

Citations:


🏁 Script executed:

wc -l packages/inspector/src/widget-session-manager.ts

Repository: AndurilCode/mcp-apps-kit

Length of output: 121


🏁 Script executed:

cat -n packages/inspector/src/widget-session-manager.ts | sed -n '400,430p'

Repository: AndurilCode/mcp-apps-kit

Length of output: 1699


🏁 Script executed:

cat -n packages/inspector/src/widget-session-manager.ts | sed -n '430,460p'

Repository: AndurilCode/mcp-apps-kit

Length of output: 1286


🏁 Script executed:

cat -n packages/inspector/src/widget-session-manager.ts | sed -n '735,775p'

Repository: AndurilCode/mcp-apps-kit

Length of output: 1773


🏁 Script executed:

cat -n packages/inspector/src/widget-session-manager.ts | sed -n '785,810p'

Repository: AndurilCode/mcp-apps-kit

Length of output: 1281


Remove logger.info() calls from inside page.evaluate() blocks — they will throw ReferenceError in browser context.

page.evaluate() executes JavaScript in the browser page VM, where Node-side variables like logger are undefined. Move logging outside the evaluate blocks, optionally returning a boolean to signal whether the operation succeeded.

Affected locations: 412-413, 442-443, 747-748, 760-761, 796-797

✅ Recommended pattern
-        await page.evaluate((ctx: typeof hostContext) => {
+        const didPost = await page.evaluate((ctx: typeof hostContext) => {
           const iframe = document.getElementById("widget-frame") as HTMLIFrameElement | null;
           if (iframe?.contentWindow) {
             const message = {
               jsonrpc: "2.0",
               method: "ui/notifications/host-context-changed",
               params: { hostContext: ctx },
             };
             iframe.contentWindow.postMessage(message, "*");
-            logger.info("[MCP Host] Sent ui/notifications/host-context-changed", ctx);
+            return true;
           }
+          return false;
         }, hostContext);
+        if (this.debug && didPost) {
+          logger.info("[MCP Host] Sent ui/notifications/host-context-changed", hostContext);
+        }
🤖 Prompt for AI Agents
In `@packages/inspector/src/widget-session-manager.ts` around lines 412 - 413, The
logger.info calls inside page.evaluate are running in the browser VM and will
throw ReferenceError; locate each page.evaluate(...) invocation in
widget-session-manager.ts (the calls that currently contain logger.info("[MCP
Host] Sent ui/notifications/host-context-changed", ctx) and the other similar
messages at the affected locations) and move the logger.info(...) out of the
evaluate callback to run in Node context instead — modify the evaluate functions
to return a success flag or result (e.g., true/false or the ctx) and then call
logger.info(...) after await page.evaluate(...) using that returned value;
ensure all occurrences listed (the blocks around the shown log strings) follow
this pattern so no logger is referenced inside the page.evaluate scope.

Comment on lines +22 to +33
// Lightweight scoped logger (mirrors inspector's createLogger, avoids cross-package dep)
const uiReactLogger = (() => {
const source = "ui-react:hooks";
const ts = () => new Date().toISOString();
const LEVELS: Record<string, number> = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
// eslint-disable-next-line no-undef, @typescript-eslint/no-unnecessary-condition
const envLevel =
typeof process !== "undefined"
? ((process.env?.MCP_APPS_LOG_LEVEL as string | undefined) ?? "").toLowerCase()
: "";
const threshold: number = LEVELS[envLevel] ?? 1; // 1 = info
const ok = (l: string): boolean => (LEVELS[l] ?? 1) >= threshold;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Fix no-undef on process (disable is on the wrong line).

Line 27 disables only the next line, but process is referenced on Line 29–30, so ESLint can still error. Consider avoiding process as a free global via globalThis and drop the disable.

✅ Suggested fix (no `any`, no eslint-disable)
-  // eslint-disable-next-line no-undef, `@typescript-eslint/no-unnecessary-condition`
-  const envLevel =
-    typeof process !== "undefined"
-      ? ((process.env?.MCP_APPS_LOG_LEVEL as string | undefined) ?? "").toLowerCase()
-      : "";
+  const processEnv =
+    typeof globalThis !== "undefined" && "process" in globalThis
+      ? (
+          globalThis as {
+            process?: { env?: Record<string, string | undefined> };
+          }
+        ).process?.env
+      : undefined;
+  const envLevel = (processEnv?.MCP_APPS_LOG_LEVEL ?? "").toLowerCase();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Lightweight scoped logger (mirrors inspector's createLogger, avoids cross-package dep)
const uiReactLogger = (() => {
const source = "ui-react:hooks";
const ts = () => new Date().toISOString();
const LEVELS: Record<string, number> = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
// eslint-disable-next-line no-undef, @typescript-eslint/no-unnecessary-condition
const envLevel =
typeof process !== "undefined"
? ((process.env?.MCP_APPS_LOG_LEVEL as string | undefined) ?? "").toLowerCase()
: "";
const threshold: number = LEVELS[envLevel] ?? 1; // 1 = info
const ok = (l: string): boolean => (LEVELS[l] ?? 1) >= threshold;
// Lightweight scoped logger (mirrors inspector's createLogger, avoids cross-package dep)
const uiReactLogger = (() => {
const source = "ui-react:hooks";
const ts = () => new Date().toISOString();
const LEVELS: Record<string, number> = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
const processEnv =
typeof globalThis !== "undefined" && "process" in globalThis
? (
globalThis as {
process?: { env?: Record<string, string | undefined> };
}
).process?.env
: undefined;
const envLevel = (processEnv?.MCP_APPS_LOG_LEVEL ?? "").toLowerCase();
const threshold: number = LEVELS[envLevel] ?? 1; // 1 = info
const ok = (l: string): boolean => (LEVELS[l] ?? 1) >= threshold;
🧰 Tools
🪛 ESLint

[error] 30-30: 'process' is not defined.

(no-undef)

🤖 Prompt for AI Agents
In `@packages/ui-react/src/hooks.ts` around lines 22 - 33, The eslint disable is
placed on the wrong line and `process` is used as a free global; update the
uiReactLogger initialization to check for process via globalThis (e.g., guard
with typeof globalThis.process !== "undefined") and derive envLevel from
globalThis.process.env safely, remove the incorrect eslint-disable comment, and
keep the rest of the logic in uiReactLogger (references: uiReactLogger,
envLevel, LEVELS, threshold, ok, ts) so ESLint no-undef no longer flags
`process`.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant