豆豆友情提示:这是一个非官方 GitHub 代理镜像,主要用于网络测试或访问加速。请勿在此进行登录、注册或处理任何敏感信息。进行这些操作请务必访问官方网站 github.com。 Raw 内容也通过此代理提供。
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
31 changes: 31 additions & 0 deletions src/McpContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export class McpContext implements Context {
null;

#nextPageId = 1;
#extensionPages = new WeakMap<Target, Page>();

#extensionServiceWorkerMap = new WeakMap<Target, string>();
#nextExtensionServiceWorkerId = 1;
Expand Down Expand Up @@ -589,6 +590,36 @@ export class McpContext implements Context {
this.#options.experimentalIncludeAllPages,
);

const allTargets = this.browser.targets();
Comment thread
nroscino marked this conversation as resolved.
const extensionTargets = allTargets.filter(target => {
return (
target.url().startsWith('chrome-extension://') &&
target.type() === 'page'
);
});

for (const target of extensionTargets) {
// Right now target.page() returns null for popup and side panel pages.
let page = await target.page();
if (!page) {
// We need to cache pages instances for targets because target.asPage()
// returns a new page instance every time.
page = this.#extensionPages.get(target) ?? null;
if (!page) {
try {
page = await target.asPage();
this.#extensionPages.set(target, page);
} catch (e) {
this.logger('Failed to get page for extension target', e);
}
}
}

if (page && !allPages.includes(page)) {
allPages.push(page);
}
}

// Build a reverse lookup from BrowserContext instance → name.
const contextToName = new Map<BrowserContext, string>();
for (const [name, ctx] of this.#isolatedContexts) {
Expand Down
93 changes: 67 additions & 26 deletions src/McpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {DevTools} from './third_party/index.js';
import type {
ConsoleMessage,
ImageContent,
Page,
ResourceType,
TextContent,
} from './third_party/index.js';
Expand All @@ -42,6 +43,7 @@ interface TraceInsightData {
export class McpResponse implements Response {
#includePages = false;
#includeExtensionServiceWorkers = false;
#includeExtensionPages = false;
#snapshotParams?: SnapshotParams;
#attachedNetworkRequestId?: number;
#attachedNetworkRequestOptions?: {
Expand Down Expand Up @@ -94,6 +96,7 @@ export class McpResponse implements Response {

if (this.#args.categoryExtensions) {
this.#includeExtensionServiceWorkers = value;
this.#includeExtensionPages = value;
}
}

Expand Down Expand Up @@ -501,6 +504,7 @@ export class McpResponse implements Response {
pages?: object[];
pagination?: object;
extensionServiceWorkers?: object[];
extensionPages?: object[];
} = {};

const response = [];
Expand Down Expand Up @@ -559,34 +563,54 @@ Call ${handleDialog.name} to handle it before continuing.`);
}

if (this.#includePages) {
const parts = [`## Pages`];
for (const page of context.getPages()) {
const isolatedContextName = context.getIsolatedContextName(page);
const contextLabel = isolatedContextName
? ` isolatedContext=${isolatedContextName}`
: '';
parts.push(
`${context.getPageId(page)}: ${page.url()}${context.isPageSelected(page) ? ' [selected]' : ''}${contextLabel}`,
);
const allPages = context.getPages();

const {regularPages, extensionPages} = allPages.reduce(
(acc: {regularPages: Page[]; extensionPages: Page[]}, page: Page) => {
if (page.url().startsWith('chrome-extension://')) {
acc.extensionPages.push(page);
} else {
acc.regularPages.push(page);
}
return acc;
},
{regularPages: [], extensionPages: []},
);

if (regularPages.length) {
const parts = [`## Pages`];
const structuredPages = [];
for (const page of regularPages) {
const isolatedContextName = context.getIsolatedContextName(page);
const contextLabel = isolatedContextName
? ` isolatedContext=${isolatedContextName}`
: '';
parts.push(
`${context.getPageId(page)}: ${page.url()}${context.isPageSelected(page) ? ' [selected]' : ''}${contextLabel}`,
);
structuredPages.push(createStructuredPage(page, context));
}
response.push(...parts);
structuredContent.pages = structuredPages;
}
response.push(...parts);
structuredContent.pages = context.getPages().map(page => {
const isolatedContextName = context.getIsolatedContextName(page);
const entry: {
id: number | undefined;
url: string;
selected: boolean;
isolatedContext?: string;
} = {
id: context.getPageId(page),
url: page.url(),
selected: context.isPageSelected(page),
};
if (isolatedContextName) {
entry.isolatedContext = isolatedContextName;

if (this.#includeExtensionPages) {
if (extensionPages.length) {
response.push(`## Extension Pages`);
const structuredExtensionPages = [];
for (const page of extensionPages) {
const isolatedContextName = context.getIsolatedContextName(page);
const contextLabel = isolatedContextName
? ` isolatedContext=${isolatedContextName}`
: '';
response.push(
`${context.getPageId(page)}: ${page.url()}${context.isPageSelected(page) ? ' [selected]' : ''}${contextLabel}`,
);
structuredExtensionPages.push(createStructuredPage(page, context));
}
structuredContent.extensionPages = structuredExtensionPages;
}
return entry;
});
}
}

if (this.#includeExtensionServiceWorkers) {
Expand Down Expand Up @@ -803,3 +827,20 @@ Call ${handleDialog.name} to handle it before continuing.`);
this.#textResponseLines = [];
}
}
function createStructuredPage(page: Page, context: McpContext) {
const isolatedContextName = context.getIsolatedContextName(page);
const entry: {
id: number | undefined;
url: string;
selected: boolean;
isolatedContext?: string;
} = {
id: context.getPageId(page),
url: page.url(),
selected: context.isPageSelected(page),
};
if (isolatedContextName) {
entry.isolatedContext = isolatedContextName;
}
return entry;
}
18 changes: 9 additions & 9 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@ import {puppeteer} from './third_party/index.js';

let browser: Browser | undefined;

function makeTargetFilter() {
const ignoredPrefixes = new Set([
'chrome://',
'chrome-extension://',
'chrome-untrusted://',
]);
function makeTargetFilter(enableExtensions = false) {
const ignoredPrefixes = new Set(['chrome://', 'chrome-untrusted://']);
if (!enableExtensions) {
ignoredPrefixes.add('chrome-extension://');
}

return function targetFilter(target: Target): boolean {
if (target.url() === 'chrome://newtab/') {
Expand All @@ -51,14 +50,15 @@ export async function ensureBrowserConnected(options: {
devtools: boolean;
channel?: Channel;
userDataDir?: string;
enableExtensions?: boolean;
}) {
const {channel} = options;
const {channel, enableExtensions} = options;
if (browser?.connected) {
return browser;
}

const connectOptions: Parameters<typeof puppeteer.connect>[0] = {
targetFilter: makeTargetFilter(),
targetFilter: makeTargetFilter(enableExtensions),
defaultViewport: null,
handleDevToolsAsPage: true,
};
Expand Down Expand Up @@ -218,7 +218,7 @@ export async function launch(options: McpLaunchOptions): Promise<Browser> {
try {
const browser = await puppeteer.launch({
channel: puppeteerChannel,
targetFilter: makeTargetFilter(),
targetFilter: makeTargetFilter(options.enableExtensions),
executablePath,
defaultViewport: null,
userDataDir,
Expand Down
1 change: 1 addition & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export async function createMcpServer(
: undefined,
userDataDir: serverArgs.userDataDir,
devtools,
enableExtensions: serverArgs.categoryExtensions,
})
: await ensureBrowserLaunched({
headless: serverArgs.headless,
Expand Down
15 changes: 15 additions & 0 deletions tests/tools/fixtures/extension-side-panel/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "Test Extension Side Panel",
"version": "1.0.0",
"manifest_version": 3,
"permissions": ["sidePanel"],
"action": {
"default_title": "Click to open panel"
},
"background": {
"service_worker": "sw.js"
},
"side_panel": {
"default_path": "sidepanel.html"
}
}
9 changes: 9 additions & 0 deletions tests/tools/fixtures/extension-side-panel/sidepanel.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!doctype html>
<html>
<head>
<title>Side Panel</title>
</head>
<body>
<h1>Side Panel</h1>
</body>
</html>
3 changes: 3 additions & 0 deletions tests/tools/fixtures/extension-side-panel/sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
chrome.sidePanel
.setPanelBehavior({openPanelOnActionClick: true})
.catch(console.error);
27 changes: 27 additions & 0 deletions tests/tools/pages.test.js.snapshot
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
exports[`pages > list_pages > list pages for extension pages with --category-extensions 1`] = `
## Pages
1: about:blank [selected]
## Extension Pages
2: chrome-extension://<extension-id>/popup.html
`;

exports[`pages > list_pages > list pages for extension service workers with --category-extensions 1`] = `
## Pages
1: about:blank [selected]
## Extension Service Workers
sw-1: chrome-extension://<extension-id>/sw.js
`;

exports[`pages > list_pages > list pages for extension service workers without --category-extensions 1`] = `
## Pages
1: about:blank [selected]
`;

exports[`pages > list_pages > list pages for side panels with --category-extensions 1`] = `
## Pages
1: about:blank
## Extension Pages
2: chrome-extension://<extension-id>/sidepanel.html [selected]
## Extension Service Workers
sw-1: chrome-extension://<extension-id>/sw.js
`;
Loading
Loading