navigateTool.ts•2.12 kB
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { getWebDriver } from "../services/seleniumService.js";
// Define the input schema for the navigate tool using Zod
const NavigateInputSchema = z.object({
url: z.string().url({ message: "Invalid URL format." }),
});
// Infer the input type from the schema
type NavigateInput = z.infer<typeof NavigateInputSchema>;
// Define the output schema (simple success message)
// While defined, the current handler returns simpler text/error content.
// Modify handler return if strict schema validation on output is needed.
const NavigateOutputSchema = z.object({
success: z.boolean(),
message: z.string(),
});
/**
* Registers the selenium_navigate tool with the MCP server.
*/
export function registerNavigateTool(server: McpServer): void {
const description = "Navigates the browser controlled by Selenium WebDriver to a specified URL.";
// Use the correct server.tool method with description and schema shape
server.tool(
'selenium_navigate', // name
description, // description
NavigateInputSchema.shape, // paramsSchema (the shape, not the object)
// handler (cb)
async (params: NavigateInput) => {
const driver = getWebDriver();
try {
console.log(`Navigating to: ${params.url}`);
await driver.get(params.url);
const currentUrl = await driver.getCurrentUrl();
console.log(`Successfully navigated to: ${currentUrl}`);
// Return success content within the expected structure
return {
content: [
{
type: "text",
text: `Successfully navigated to ${currentUrl}`,
},
]
};
} catch (error: any) {
console.error(`Error navigating to ${params.url}:`, error);
// Throw an error instead of returning an error structure
// The SDK should catch this and set isError=true in the response.
throw new Error(`Failed to navigate to ${params.url}. Error: ${error.message || 'Unknown error'}`);
}
}
);
}