Chrome DevTools for coding agents
fix: do not block tool calls on a roots/list the client is slow to answer (#2477)
Thomas Bachemd93e66701f29
diff --git a/src/index.ts b/src/index.tsindex 7c61218e..2b625d62 100644--- a/src/index.ts+++ b/src/index.ts@@ -16,6 +16,7 @@ import {FilePersistence} from './telemetry/persistence.js';import {McpServer,type CallToolResult,+ type Root,SetLevelRequestSchema,ListRootsResultSchema,RootsListChangedNotificationSchema,@@ -29,6 +30,16 @@ import {VERSION} from './version.js';export {buildFlag} from './ToolHandler.js';+/**+ * Timeout for a `roots/list` that a tool call is waiting on, matching the 5s+ * default used for page operations. `getContext()` awaits it while+ * `ToolHandler` holds the tool mutex, so leaving it unbounded lets a client+ * that negotiates `roots` but does not answer block every tool for the SDK's+ * default of 60s. Background refreshes are not bounded by this, so roots a+ * slow client sends late still land.+ */+const ROOTS_REQUEST_TIMEOUT = 5_000;+export async function createMcpServer(serverArgs: ReturnType<typeof parseArguments>,options: {@@ -58,7 +69,15 @@ export async function createMcpServer(return {};});- const updateRoots = async () => {+ // Roots are client state rather than browser state, so the last listing stays+ // valid across browser reconnects and only the client can invalidate it, via+ // the `roots/list_changed` notification handled below+ let lastRoots: Root[] | undefined;++ // `timeout` is only passed where a tool call is waiting on the result – the+ // background refreshes below block nobody, so bounding them would just discard+ // roots a slow client was about to send+ const updateRoots = async (timeout?: number) => {if (!server.server.getClientCapabilities()?.roots) {return;}@@ -66,8 +85,10 @@ export async function createMcpServer(const roots = await server.server.request({method: 'roots/list'},ListRootsResultSchema,+ timeout === undefined ? undefined : {timeout},);- context?.setRoots(roots.roots);+ lastRoots = roots.roots;+ context?.setRoots(lastRoots);} catch (e) {logger?.('Failed to list roots', e);}@@ -158,7 +179,16 @@ export async function createMcpServer(// Surfaces a one-time note in the next response after a reconnect.reconnected: context !== undefined,});- await updateRoots();+ if (lastRoots === undefined) {+ // Nothing listed yet, so this call has to wait – bounded, since it is+ // holding the tool mutex, and a later background refresh still lands+ await updateRoots(ROOTS_REQUEST_TIMEOUT);+ } else {+ // Carry the known roots over and refresh out of band, so a reconnect+ // never pays for a client round-trip+ context.setRoots(lastRoots);+ void updateRoots();+ }}return context;}diff --git a/tests/index.test.ts b/tests/index.test.tsindex 497e732d..2c9bb1a9 100644--- a/tests/index.test.ts+++ b/tests/index.test.ts@@ -9,6 +9,7 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import {describe, it} from 'node:test';+import {pathToFileURL} from 'node:url';import {Client} from '@modelcontextprotocol/sdk/client/index.js';import {StdioClientTransport} from '@modelcontextprotocol/sdk/client/stdio.js';@@ -285,6 +286,89 @@ describe('e2e', () => {);});+ it('does not block tools if the client never answers roots/list', async () => {+ await withClient(+ async client => {+ // A client that negotiates roots but never responds. getContext()+ // awaits updateRoots() while holding the tool mutex, so an unbounded+ // request would stall this call for the SDK default of 60s.+ client.setRequestHandler(ListRootsRequestSchema, () => {+ return new Promise<never>(() => {+ // Intentionally never settles+ });+ });++ const start = Date.now();+ // Raise the client-side timeout above the SDK default so an unbounded+ // roots request surfaces as the assertion below rather than a timeout+ const result = await client.callTool(+ {+ name: 'list_pages',+ arguments: {},+ },+ undefined,+ {timeout: 90_000},+ );+ const elapsed = Date.now() - start;++ assert.strictEqual(result.isError, undefined);+ // Bounded roots request plus browser launch settles well under this,+ // leaving room for a slow CI runner while still catching the 60s stall+ assert.ok(+ elapsed < 45_000,+ `list_pages took ${elapsed}ms, expected the bounded roots request to settle well before the 60s SDK default`,+ );+ },+ [],+ {+ capabilities: {+ roots: {listChanged: true},+ },+ },+ );+ });++ it('still applies roots from a client slower than the bound', async () => {+ const workspace = await fs.promises.mkdtemp(+ path.join(os.homedir(), '.roots-slow-client-'),+ );+ try {+ await withClient(+ async client => {+ // Answers after the bound the blocking call uses, so the roots only+ // arrive via the background listing+ client.setRequestHandler(ListRootsRequestSchema, async () => {+ await new Promise(resolve => setTimeout(resolve, 8_000));+ return {+ roots: [{uri: pathToFileURL(workspace).href, name: 'workspace'}],+ };+ });++ await client.callTool({name: 'list_pages', arguments: {}});+ await new Promise(resolve => setTimeout(resolve, 5_000));++ const result = await client.callTool({+ name: 'take_screenshot',+ arguments: {filePath: path.join(workspace, 'shot.png')},+ });++ // Asserted before isError so a denial reports the path it rejected+ const content = result.content as TextContent[];+ assert.match(content[0].text, /Saved screenshot to/);+ assert.strictEqual(result.isError, undefined);+ },+ [],+ {+ capabilities: {+ roots: {listChanged: true},+ },+ },+ );+ } finally {+ await fs.promises.rm(workspace, {recursive: true, force: true});+ }+ });+describe('Dialogs', () => {async function createNewPageAndTriggerDialog(client: Client) {// Navigate to a page with a button that triggers a dialog on click