Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
10 changes: 10 additions & 0 deletions src/McpContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import type {
} from './third_party/index.js';
import {Locator} from './third_party/index.js';
import {PredefinedNetworkConditions} from './third_party/index.js';
import type {ToolGroup, ToolDefinition} from './tools/inPage.js';
import {listPages} from './tools/pages.js';
import {CLOSE_PAGE_ERROR} from './tools/ToolDefinition.js';
import type {Context, DevToolsData} from './tools/ToolDefinition.js';
Expand Down Expand Up @@ -101,6 +102,7 @@ export class McpContext implements Context {
#screenRecorderData: {recorder: ScreenRecorder; filePath: string} | null =
null;

#inPageTools?: ToolGroup<ToolDefinition>;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should move this to McpPage instead of McpContext to support pageId routing (currently experimental).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please check if other new tools have the same problem

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

Expand Down Expand Up @@ -464,6 +466,14 @@ export class McpContext implements Context {
this.#updateSelectedPageTimeouts();
}

setInPageTools(toolGroup?: ToolGroup<ToolDefinition>) {
this.#inPageTools = toolGroup;
}

getInPageTools(): ToolGroup<ToolDefinition> | undefined {
return this.#inPageTools;
}

#updateSelectedPageTimeouts() {
const page = this.#getSelectedMcpPage();
// For waiters 5sec timeout should be sufficient.
Expand Down
1 change: 1 addition & 0 deletions src/McpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,7 @@ export class McpResponse implements Response {
let inPageTools: ToolGroup<ToolDefinition> | undefined;
if (this.#listInPageTools) {
inPageTools = await getToolGroup(context.getSelectedMcpPage());
context.setInPageTools(inPageTools);
}

let consoleMessages: Array<ConsoleFormatter | IssueFormatter> | undefined;
Expand Down
1 change: 1 addition & 0 deletions src/third_party/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export {
type TextContent,
} from '@modelcontextprotocol/sdk/types.js';
export {z as zod} from 'zod';
export {default as ajv} from 'ajv';
export {
Locator,
PredefinedNetworkConditions,
Expand Down
6 changes: 6 additions & 0 deletions src/tools/ToolDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ import type {InstalledExtension} from '../utils/ExtensionRegistry.js';
import type {PaginationOptions} from '../utils/types.js';

import type {ToolCategory} from './categories.js';
import type {
ToolGroup,
ToolDefinition as InPageToolDefinition,
} from './inPage.js';

export interface BaseToolDefinition<
Schema extends zod.ZodRawShape = zod.ZodRawShape,
Expand Down Expand Up @@ -194,6 +198,8 @@ export type Context = Readonly<{
triggerExtensionAction(id: string): Promise<void>;
listExtensions(): InstalledExtension[];
getExtension(id: string): InstalledExtension | undefined;
setInPageTools(toolGroup?: ToolGroup<InPageToolDefinition>): void;
Comment thread
wolfib marked this conversation as resolved.
Outdated
getInPageTools(): ToolGroup<InPageToolDefinition> | undefined;
getSelectedMcpPage(): McpPage;
getExtensionServiceWorkers(): ExtensionServiceWorker[];
getExtensionServiceWorkerId(
Expand Down
64 changes: 60 additions & 4 deletions src/tools/inPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import {type JSONSchema7} from '../third_party/index.js';
import {zod, ajv, type JSONSchema7} from '../third_party/index.js';

import {ToolCategory} from './categories.js';
import {definePageTool} from './ToolDefinition.js';
Expand Down Expand Up @@ -37,9 +37,13 @@ declare global {

export const listInPageTools = definePageTool({
name: 'list_in_page_tools',
description: `Lists all in-page-tools the page exposes for providing runtime information.
To call 'list_in_page_tools', call 'evaluate_script' with
'window.__dtmcp.executeTool("list_in_page_tools", {})'.`,
description: `Lists all in-page tools the page exposes for providing runtime information.
In-page tools can be called via the 'execute_in_page_tool()' MCP tool.
Alternatively, in-page tools can be executed by calling 'evaluate_script' and adding the
following command to the script:
'window.__dtmcp.executeTool(toolName, params)'
Comment thread
wolfib marked this conversation as resolved.
This might be helpful when the in-page-tools return non-serializable values or when composing
the in-page-tools with additional functionality.`,
annotations: {
category: ToolCategory.IN_PAGE,
readOnlyHint: true,
Expand All @@ -50,3 +54,55 @@ export const listInPageTools = definePageTool({
response.setListInPageTools();
},
});

export const executeInPageTool = definePageTool({
name: 'execute_in_page_tool',
description: `Executes a tool exposed by the page.`,
annotations: {
category: ToolCategory.IN_PAGE,
readOnlyHint: false,
conditions: ['inPageTools'],
},
schema: {
toolName: zod.string().describe('The name of the tool to execute'),
params: zod
Comment thread
wolfib marked this conversation as resolved.
.record(zod.string(), zod.unknown())
.optional()
.describe('The parameters to pass to the tool'),
},
handler: async (request, response, context) => {
const page = context.getSelectedMcpPage();
Comment thread
wolfib marked this conversation as resolved.
const toolName = request.params.toolName;
const params = request.params.params ?? {};

const toolGroup = context.getInPageTools();
const tool = toolGroup?.tools.find(t => t.name === toolName);
if (!tool) {
throw new Error(`Tool ${toolName} not found`);
}
const ajvInstance = new ajv();
const validate = ajvInstance.compile(tool.inputSchema);
const valid = validate(params);
if (!valid) {
throw new Error(
`Invalid parameters for tool ${toolName}: ${ajvInstance.errorsText(validate.errors)}`,
);
}

const result = await page.pptrPage.evaluate(
async (name, args) => {
if (!window.__dtmcp?.executeTool) {
throw new Error('No tools found on the page');
}
const toolResult = await window.__dtmcp.executeTool(name, args);

return {
result: toolResult,
};
},
toolName,
params,
);
response.appendResponseLine(JSON.stringify(result, null, 2));
},
});
50 changes: 50 additions & 0 deletions tests/third_party_notices.test.js.snapshot
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,56 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


-------------------- DEPENDENCY DIVIDER --------------------

Name: uri-js
URL: https://github.com/garycourt/uri-js
Version: <VERSION>
License: BSD-2-Clause

Copyright 2011 Gary Court. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court.


-------------------- DEPENDENCY DIVIDER --------------------

Name: fast-json-stable-stringify
URL: https://github.com/epoberezkin/fast-json-stable-stringify
Version: <VERSION>
License: MIT

This software is released under the MIT license:

Copyright (c) 2017 Evgeny Poberezkin
Copyright (c) 2013 James Halliday

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


-------------------- DEPENDENCY DIVIDER --------------------

Name: puppeteer-core
Expand Down
Loading
Loading