Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ export default defineConfig([
'src/telemetry/**/*.ts',
'src/BrowserManager.ts',
'src/processors/HeapSnapshotManager.ts',
'src/ToolHandler.ts',
],
rules: {
'@typescript-eslint/no-restricted-imports': [
Expand Down
32 changes: 27 additions & 5 deletions src/ToolHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import type {ParsedArguments} from './config/mcp-options.js';
import type {ReadonlyServerConfig} from './config/ServerConfig.js';
import type {McpContext} from './McpContext.js';
import type {McpPage} from './McpPage.js';
import {McpResponse, type DataFormat} from './McpResponse.js';
import {SlimMcpResponse} from './SlimMcpResponse.js';
import type {McpResponse, DataFormat} from './McpResponse.js';
import {ClearcutLogger} from './telemetry/ClearcutLogger.js';
import {
DisposableStack,
Expand Down Expand Up @@ -59,6 +58,29 @@ export const TOOL_CALL_TIMEOUT_MS = 60_000;

class ToolCallTimeoutError extends Error {}

type ResponseFactory = (
slim: boolean,
config: ReadonlyServerConfig,
) => McpResponse;

let responseFactory: Promise<ResponseFactory> | undefined;

/**
* Loads the response classes on first use, because they import the browser
* bundle through the formatters.
*/
function loadResponseFactory(): Promise<ResponseFactory> {
responseFactory ??= Promise.all([
import('./McpResponse.js'),
import('./SlimMcpResponse.js'),
]).then(([mcpResponseModule, slimMcpResponseModule]) => (slim, config) => {
return slim
? new slimMcpResponseModule.SlimMcpResponse(config)
: new mcpResponseModule.McpResponse(config);
});
return responseFactory;
}

function buildDisabledMessage(
toolName: string,
flag: string,
Expand Down Expand Up @@ -497,6 +519,8 @@ export class ToolHandler {
const signal = options?.signal ?? new AbortController().signal;
signal.throwIfAborted();
const context = await raceWithSignal(this.getContext(), signal);
// Loaded before the call takes its queue, so waiting never holds a queue.
const createResponse = await raceWithSignal(loadResponseFactory(), signal);
let queueGuard: Disposable | undefined;
try {
queueGuard = await this.#queueFor(context, rawArgs)?.scheduleTask(signal);
Expand Down Expand Up @@ -532,9 +556,7 @@ export class ToolHandler {
let pageUrl: string | undefined;
try {
logger?.(`${tool.name} request: ${JSON.stringify(params, null, ' ')}`);
const response = isSlimTool(tool)
? new SlimMcpResponse(this.#config)
: new McpResponse(this.#config);
const response = createResponse(isSlimTool(tool), this.#config);
// The execution owns the queue even when its caller stops waiting.
const execution = isBrowserlessTool(tool)
? this.#runBrowserlessTool(tool, params, response, context, signal)
Expand Down
62 changes: 62 additions & 0 deletions tests/ToolHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {ConfigParser} from '../src/config/ConfigParser.js';
import type {McpContext} from '../src/McpContext.js';
import {McpPage} from '../src/McpPage.js';
import {McpResponse, type DataFormat} from '../src/McpResponse.js';
import {SlimMcpResponse} from '../src/SlimMcpResponse.js';
import {ClearcutLogger} from '../src/telemetry/ClearcutLogger.js';
import {FilePersistence} from '../src/telemetry/persistence.js';
import {McpClient, WatchdogMessageType} from '../src/telemetry/types.js';
Expand Down Expand Up @@ -1612,6 +1613,67 @@ describe('ToolHandler', () => {
]);
});

function createResponseRecordingHandler(slim: boolean) {
const config = parseConfig(slim ? ['--slim'] : []);
const toolHandler = sinon.stub().resolves();
const tool = defineBrowserlessTool(() => ({
name: 'response_tool',
description: 'A tool that records the response it gets',
annotations: {
category: ToolCategory.MEMORY,
readOnlyHint: true,
conditions: slim ? ['slim'] : [],
},
schema: {},
blockedByDialog: false,
verifyFilesSchema: {},
handler: toolHandler,
}))(config.resolved);
const context = createMockMcpContext();
const handler = new ToolHandler(
tool,
config,
async () => context,
sinon.spy(),
);
return {handler, toolHandler, context};
}

it('creates a SlimMcpResponse for slim tools', async () => {
const {handler, toolHandler, context} =
createResponseRecordingHandler(true);

await handler.handle({});

sinon.assert.calledOnceWithExactly(
toolHandler,
{params: {}},
sinon.match.instanceOf(SlimMcpResponse),
context,
);
});

it('creates an McpResponse that is not a SlimMcpResponse for other tools', async () => {
sinon
.stub(McpResponse.prototype, 'handle')
.resolves({content: [], structuredContent: {}});
const {handler, toolHandler, context} =
createResponseRecordingHandler(false);

await handler.handle({});

sinon.assert.calledOnceWithExactly(
toolHandler,
{params: {}},
sinon.match(
response =>
response instanceof McpResponse &&
!(response instanceof SlimMcpResponse),
),
context,
);
});

it('enables slim tools with --slim', () => {
assert.strictEqual(createHandler('navigate', ['--slim']).disabled, false);
});
Expand Down