How the TradingView-MCP Server Handles Connection Failures When TradingView Closes Unexpectedly

The TradingView-MCP server detects unexpected disconnections through a liveness check in connection.js and automatically attempts to re-establish the Chrome DevTools Protocol (CDP) connection using an exponential back-off retry strategy.

The tradesdontlie/tradingview-mcp repository provides a Model Context Protocol (MCP) server that controls the TradingView desktop client via CDP. When users close TradingView unexpectedly or the application crashes, the server must handle connection failures gracefully to maintain operational stability. This article examines the specific mechanisms implemented in src/connection.js to detect stale sessions and recover automatically.

Liveness Check on Every Client Request

All core tools rely on the getClient() function exported from src/connection.js. Before returning a cached client, the function validates the connection by executing a trivial JavaScript evaluation against the remote page.

If the evaluation throws an error—indicating that TradingView has closed—the cached client is cleared and the function initiates a fresh connection attempt.

if (client) {
  try {
    await client.Runtime.evaluate({ expression: '1', returnByValue: true });
    return client;                     // → still alive
  } catch {
    client = null;                     // → stale, will reconnect
    targetInfo = null;
  }
}

Automatic Reconnection with Exponential Back-Off

When getClient() detects a dead connection or no cached client exists, it invokes connect() to establish a new CDP session. This function implements a robust retry loop with specific constraints:

  • Maximum attempts: MAX_RETRIES = 5
  • Base delay: BASE_DELAY = 500 ms
  • Back-off strategy: Exponential growth as BASE_DELAY * 2^attempt, capped at 30 seconds
  • Target discovery: findChartTarget() scans the CDP endpoint /json/list for a page URL containing tradingview.com/chart

If the target cannot be found or the handshake fails, the loop continues until retries are exhausted. After the final attempt, the function throws a descriptive error.

throw new Error(`CDP connection failed after ${MAX_RETRIES} attempts: ${lastError?.message}`);

Explicit Reconnection for Tab Switches

Certain operations, such as switching tabs, require attaching to a specific CDP target immediately. The reconnectTo(targetId) helper closes any existing client, clears cached state, and invokes connect(targetId) to attach to the new target without waiting for the next automatic check.

import { reconnectTo } from '../connection.js';

export async function tab_switch(targetId) {
  await reconnectTo(targetId);                     // forces a fresh CDP session
  // subsequent calls will use the new target
}

Error Propagation to the MCP Layer

All tool implementations call await getClient() before issuing CDP commands. If reconnection fails after all retries, the thrown error propagates through the call stack to src/server.js. The MCP framework captures this exception and returns a structured error response, allowing consuming applications to notify users that TradingView is not running.

Summary

  • The server validates CDP connection health on every request by evaluating the expression '1' via client.Runtime.evaluate.
  • Failed liveness checks trigger an automatic reconnection attempt with exponential back-off, retrying up to 5 times.
  • The findChartTarget() function locates valid TradingView chart instances by scanning the CDP /json/list endpoint.
  • Manual reconnection is available via reconnectTo(targetId) for scenarios like tab switching.
  • Connection errors bubble up to the MCP layer in src/server.js, ensuring users receive clear feedback when TradingView is unavailable.

Frequently Asked Questions

What happens when TradingView closes while a tool is executing?

When TradingView closes unexpectedly, the next call to getClient() detects the stale connection through the Runtime.evaluate liveness check. The cached client is immediately cleared, and the server attempts to reconnect automatically before processing the request.

How many times does the server retry the connection?

The server attempts to reconnect a maximum of 5 times, using an exponential back-off strategy starting at 500 ms and capping at 30 seconds between attempts.

Can I manually force a reconnection to a specific TradingView tab?

Yes. The reconnectTo(targetId) function in src/connection.js allows tools to force an immediate reconnection to a specific CDP target. This is used by tab management tools to switch contexts instantly.

Where is the connection logic implemented in the codebase?

All connection lifecycle management, including liveness checks, retry logic, and target discovery, is implemented in src/connection.js. The MCP server setup and error handling reside in src/server.js.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →