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
7 changes: 1 addition & 6 deletions bench/data-url-bench.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { median } from './statistics.mjs';
import assert from 'node:assert/strict';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -55,9 +56,3 @@ for (const fixture of fixtures) {
})) });
}
process.stdout.write(`${JSON.stringify({ node: process.version, warmups, iterations, results }, null, 2)}\n`);

function median(samples) {
const sorted = [...samples].sort((first, second) => first - second);
const middle = Math.floor(sorted.length / 2);
return (sorted[middle - 1] + sorted[middle]) / 2;
}
7 changes: 1 addition & 6 deletions bench/reading-order-bench.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { median } from './statistics.mjs';
import assert from 'node:assert/strict';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -48,12 +49,6 @@ for (const count of [400, 2000]) {

process.stdout.write(`${JSON.stringify({ node: process.version, warmups, iterations, results }, null, 2)}\n`);

function median(samples) {
const sorted = [...samples].sort((first, second) => first - second);
const middle = Math.floor(sorted.length / 2);
return (sorted[middle - 1] + sorted[middle]) / 2;
}

function fixture(count, order) {
const parent = {
role: 'generic', name: null, level: null, ref: 'parent', depth: 0, parent: null,
Expand Down
5 changes: 5 additions & 0 deletions bench/statistics.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function median(samples) {
const sorted = [...samples].sort((first, second) => first - second);
const middle = Math.floor(sorted.length / 2);
return (sorted[middle - 1] + sorted[middle]) / 2;
}
31 changes: 11 additions & 20 deletions tests/mcp-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ const testBackendFactory: ServerBackendFactory = {
}),
};

const noStreamFetch: typeof fetch = async (input, init) => {
const request = input instanceof Request ? input : undefined;
const method = init?.method ?? request?.method;
if (method === 'GET') {
return await new Promise<Response>((_resolve, reject) => {
(init?.signal ?? request?.signal)?.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
});
}
return fetch(input, init);
};

describe('mcp http transport hardening', () => {
const servers = new Set<http.Server>();

Expand Down Expand Up @@ -1390,16 +1401,6 @@ describe('mcp http transport hardening', () => {
// Never open the standalone GET stream: server-to-client requests such as
// listRoots could not be delivered, so a tool call only succeeds if the
// server no longer performs any.
const noStreamFetch: typeof fetch = async (input, init) => {
const request = input instanceof Request ? input : undefined;
const method = init?.method ?? request?.method;
if (method === 'GET') {
return await new Promise<Response>((_resolve, reject) => {
(init?.signal ?? request?.signal)?.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
});
}
return fetch(input, init);
};
const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: { roots: {} } });
client.setRequestHandler('roots/list', listRoots);
client.setRequestHandler('ping', () => ({}));
Expand Down Expand Up @@ -1443,16 +1444,6 @@ describe('mcp http transport hardening', () => {
}),
});

const noStreamFetch: typeof fetch = async (input, init) => {
const request = input instanceof Request ? input : undefined;
const method = init?.method ?? request?.method;
if (method === 'GET') {
return await new Promise<Response>((_resolve, reject) => {
(init?.signal ?? request?.signal)?.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
});
}
return fetch(input, init);
};
const client = new Client({ name: 'test-client', version: '1.0.0' }, { capabilities: {} });
client.setRequestHandler('ping', () => ({}));
const transport = new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), { fetch: noStreamFetch });
Expand Down
68 changes: 25 additions & 43 deletions tests/navigation-dialogs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,20 +286,33 @@ describe('navigation interrupted by a load-time dialog', () => {
}
});

it('does not hang the crawl on a dialog that opens after the navigation succeeded', async () => {
async function prepareCrawl() {
const outputDir = await mkdtemp(path.join(tmpdir(), 'mcp-crawl-dialog-'));
config.outputDir = outputDir;
await backend.callTool('browser_navigate', { url: 'http://fixture.local/after' });
const urls = ['first', 'late', 'second'].map(name => `http://fixture.local/${name}`);
return outputDir;
}

async function checkCrawl(outputDir: string, urls: string[], timeout: number, check: (result: Awaited<ReturnType<BrowserServerBackend['callTool']>>) => Promise<void>) {
const audit = backend.callTool('audit_site', {
startUrl: urls[0], strategy: 'provided', urls, maxPages: 3, waitAfterNavigationMs: 0,
});
let auditReturned = false;
void audit.then(() => { auditReturned = true; });
try {
// Without the fix the page's evaluate never returns: the audit waits forever.
await vi.waitFor(() => expect(auditReturned).toBe(true), { timeout: 8000 });
const result = await audit;
await vi.waitFor(() => expect(auditReturned).toBe(true), { timeout });
await check(await audit);
} finally {
await browserContext.close();
await audit;
await rm(outputDir, { recursive: true, force: true });
}
}

it('does not hang the crawl on a dialog that opens after the navigation succeeded', async () => {
const outputDir = await prepareCrawl();
const urls = ['first', 'late', 'second'].map(name => `http://fixture.local/${name}`);
await checkCrawl(outputDir, urls, 8000, async result => {
expect(result.structuredContent).toMatchObject({ totals: { scannedPages: 2, erroredPages: 1 } });
const files = await readdir(outputDir);
const report = JSON.parse(await readFile(path.join(outputDir, files[0]), 'utf8'));
Expand All @@ -308,51 +321,24 @@ describe('navigation interrupted by a load-time dialog', () => {
]);
expect(report.pages[1].error).toContain('"alert" dialog with message "After load"');
expect(browserContext.pages()).toHaveLength(1);
} finally {
// Settles a hung audit so a regression fails here instead of leaking the crawl.
await browserContext.close();
await audit;
await rm(outputDir, { recursive: true, force: true });
}
});
});

it('does not take a same-document navigation by the previous page for the next page committing', async () => {
const outputDir = await mkdtemp(path.join(tmpdir(), 'mcp-crawl-dialog-'));
config.outputDir = outputDir;
await backend.callTool('browser_navigate', { url: 'http://fixture.local/after' });
const outputDir = await prepareCrawl();
const urls = ['outgoing-pushstate', 'delayed', 'second'].map(name => `http://fixture.local/${name}`);
const audit = backend.callTool('audit_site', {
startUrl: urls[0], strategy: 'provided', urls, maxPages: 3, waitAfterNavigationMs: 0,
});
let auditReturned = false;
void audit.then(() => { auditReturned = true; });
try {
await vi.waitFor(() => expect(auditReturned).toBe(true), { timeout: 10000 });
const result = await audit;
await checkCrawl(outputDir, urls, 10000, async result => {
// Without telling the two apart, the pushState counts as 'delayed' committing and it fails.
expect(result.structuredContent).toMatchObject({ totals: { scannedPages: 3, erroredPages: 0 } });
expect(browserContext.pages()).toHaveLength(1);
} finally {
await browserContext.close();
await audit;
await rm(outputDir, { recursive: true, force: true });
}
});
});

it('audits a page again when the previous page raised its dialog during the navigation to it', async () => {
const outputDir = await mkdtemp(path.join(tmpdir(), 'mcp-crawl-dialog-'));
config.outputDir = outputDir;
await backend.callTool('browser_navigate', { url: 'http://fixture.local/after' });
const outputDir = await prepareCrawl();
const urls = ['outgoing', 'delayed', 'second'].map(name => `http://fixture.local/${name}`);
await browserContext.addCookies([{ name: 'sid', value: 'signed-in', url: 'http://fixture.local/' }]);
const audit = backend.callTool('audit_site', {
startUrl: urls[0], strategy: 'provided', urls, maxPages: 3, waitAfterNavigationMs: 0,
});
let auditReturned = false;
void audit.then(() => { auditReturned = true; });
try {
await vi.waitFor(() => expect(auditReturned).toBe(true), { timeout: 10000 });
const result = await audit;
await checkCrawl(outputDir, urls, 10000, async result => {
// Without the retry, 'delayed' is reported as failed for the previous page's dialog.
expect(result.structuredContent).toMatchObject({ totals: { scannedPages: 3, erroredPages: 0 } });
const files = await readdir(outputDir);
Expand All @@ -363,11 +349,7 @@ describe('navigation interrupted by a load-time dialog', () => {
// The cookie went while the outgoing page was still the one running.
expect(report.sessionLosses).toEqual([{ url: urls[0], cookies: ['sid'] }]);
expect(browserContext.pages()).toHaveLength(1);
} finally {
await browserContext.close();
await audit;
await rm(outputDir, { recursive: true, force: true });
}
});
});

it('keeps the back-navigation replay code when the dialog is closed outside MCP before the response', async () => {
Expand Down
34 changes: 34 additions & 0 deletions tests/transportFixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { Transport } from '@modelcontextprotocol/client';

export function forwardTransport(inner: Transport, afterMessage: NonNullable<Transport['onmessage']>): Transport {
const transport: Transport = {
start: async () => {
inner.onmessage = (message, extra) => {
transport.onmessage?.(message, extra);
afterMessage(message, extra);
};
inner.onclose = () => transport.onclose?.();
inner.onerror = error => transport.onerror?.(error);
await inner.start();
},
send: (message, options) => inner.send(message, options),
close: () => inner.close(),
};
return transport;
}
Loading
Loading