Skip to content

MCP Tool result gets inserted (or uploaded) multiple times. #21

@hayeah

Description

@hayeah

Describe the bug

Using ChatGPT, tool result gets inserted multiple times.

Image

To Reproduce

If i use the same tab, switch to another chat log, and come back to the conversation. Click "run" or "insert" would insert multiple copies of the result.

It gets progressively worse if I do this multiple times.

Reloading the window would reset the listeners, and fix it.

What’s happening

  • Every time initChatGPTComponents(), initGeminiComponents() and the other init…Components helpers run, they call initializeAdapter() from adaptercomponents/common.ts.
  • That helper always calls setupToolExecutionListener(stateManager, adapterName) without checking whether a listener for that adapter has already been registered.
  • setupToolExecutionListener attaches a fresh anonymous callback with document.addEventListener('mcp:tool-execution-complete', …). Because the callback reference is new each time, the previous one is not overwritten and can’t be removed later.
  • When you click Insert or Attach File, the renderer dispatches a single mcp:tool-execution-complete event, but now two (or ten!) identical listeners all react, each calling handleAutoInsert[…], so the same text/file is dropped into the chat input multiple times.

Why it gets worse over time

  • Those init…Components helpers are re-invoked on SPA-style navigation, URL-polling loops, or when the extension falls back to “initialise every adapter just in case” logic (see adapters/index.ts). Each reinvocation stacks another listener.
  • There is no equivalent removeEventListener call, and nothing de-dupes listeners by adapterName.

Fix in one line

Add a guard so the listener is registered once per adapter:

// adaptercomponents/common.ts
export function setupToolExecutionListener(stateManager: ToggleStateManager, adapterName: string): void {
  // guard double subscription
  document.addEventListener('mcp:tool-execution-complete', ...);
}

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions