Compare commits

...

3 Commits

Author SHA1 Message Date
Adrià Arrufat
1854627b69 mcp: final protocol cleanup after removing screenshot tool
- Removed unused ImageContent from protocol.
- Simplified CallToolResult back to only support TextContent.
- Cleaned up CallToolResult usages in tools.zig.
2026-04-01 15:00:55 +02:00
Adrià Arrufat
fffa8b6d4b mcp/cdp: fix inactivity timeout
- Fixed CDP inactivity timeout by resetting it when the browser is busy (loading or executing macrotasks).
- Removed the placeholder screenshot tool.
- Refactored MCP tool schemas to constants to avoid duplication.
2026-04-01 14:37:40 +02:00
Adrià Arrufat
58fc60d669 mcp: improve navigation reliability and add CDP support
- Configurable navigation timeouts and wait strategies in MCP tools.
- Default navigation timeout increased from 2s to 10s.
- Added navigate, eval, and screenshot MCP tools.
- Supported running a CDP server alongside MCP using --cdp-port.
- Fixed various startup crashes when running CDP in MCP mode.
- Hardened MCP server error handling.
2026-04-01 12:41:56 +02:00
4 changed files with 135 additions and 73 deletions

View File

@@ -160,6 +160,7 @@ pub fn userAgentSuffix(self: *const Config) ?[]const u8 {
pub fn cdpTimeout(self: *const Config) usize { pub fn cdpTimeout(self: *const Config) usize {
return switch (self.mode) { return switch (self.mode) {
.serve => |opts| if (opts.timeout > 604_800) 604_800_000 else @as(usize, opts.timeout) * 1000, .serve => |opts| if (opts.timeout > 604_800) 604_800_000 else @as(usize, opts.timeout) * 1000,
.mcp => 10000, // Default timeout for MCP-CDP
else => unreachable, else => unreachable,
}; };
} }
@@ -167,6 +168,7 @@ pub fn cdpTimeout(self: *const Config) usize {
pub fn port(self: *const Config) u16 { pub fn port(self: *const Config) u16 {
return switch (self.mode) { return switch (self.mode) {
.serve => |opts| opts.port, .serve => |opts| opts.port,
.mcp => |opts| opts.cdp_port orelse 0,
else => unreachable, else => unreachable,
}; };
} }
@@ -174,6 +176,7 @@ pub fn port(self: *const Config) u16 {
pub fn advertiseHost(self: *const Config) []const u8 { pub fn advertiseHost(self: *const Config) []const u8 {
return switch (self.mode) { return switch (self.mode) {
.serve => |opts| opts.advertise_host orelse opts.host, .serve => |opts| opts.advertise_host orelse opts.host,
.mcp => "127.0.0.1",
else => unreachable, else => unreachable,
}; };
} }
@@ -192,6 +195,7 @@ pub fn webBotAuth(self: *const Config) ?WebBotAuthConfig {
pub fn maxConnections(self: *const Config) u16 { pub fn maxConnections(self: *const Config) u16 {
return switch (self.mode) { return switch (self.mode) {
.serve => |opts| opts.cdp_max_connections, .serve => |opts| opts.cdp_max_connections,
.mcp => 16,
else => unreachable, else => unreachable,
}; };
} }
@@ -199,6 +203,7 @@ pub fn maxConnections(self: *const Config) u16 {
pub fn maxPendingConnections(self: *const Config) u31 { pub fn maxPendingConnections(self: *const Config) u31 {
return switch (self.mode) { return switch (self.mode) {
.serve => |opts| opts.cdp_max_pending_connections, .serve => |opts| opts.cdp_max_pending_connections,
.mcp => 128,
else => unreachable, else => unreachable,
}; };
} }
@@ -224,6 +229,7 @@ pub const Serve = struct {
pub const Mcp = struct { pub const Mcp = struct {
common: Common = .{}, common: Common = .{},
version: mcp.Version = .default, version: mcp.Version = .default,
cdp_port: ?u16 = null,
}; };
pub const DumpFormat = enum { pub const DumpFormat = enum {
@@ -677,6 +683,19 @@ fn parseMcpArgs(
continue; continue;
} }
if (std.mem.eql(u8, "--cdp-port", opt) or std.mem.eql(u8, "--cdp_port", opt)) {
const str = args.next() orelse {
log.fatal(.mcp, "missing argument value", .{ .arg = opt });
return error.InvalidArgument;
};
result.cdp_port = std.fmt.parseInt(u16, str, 10) catch |err| {
log.fatal(.mcp, "invalid argument value", .{ .arg = opt, .err = err });
return error.InvalidArgument;
};
continue;
}
if (try parseCommonArg(allocator, opt, args, &result.common)) { if (try parseCommonArg(allocator, opt, args, &result.common)) {
continue; continue;
} }

View File

@@ -330,6 +330,11 @@ pub const Client = struct {
ms_remaining = self.ws.timeout_ms; ms_remaining = self.ws.timeout_ms;
}, },
.done => { .done => {
if (self.isBusy()) {
last_message = milliTimestamp(.monotonic);
ms_remaining = self.ws.timeout_ms;
continue;
}
const now = milliTimestamp(.monotonic); const now = milliTimestamp(.monotonic);
const elapsed = now - last_message; const elapsed = now - last_message;
if (elapsed >= ms_remaining) { if (elapsed >= ms_remaining) {
@@ -343,6 +348,24 @@ pub const Client = struct {
} }
} }
fn isBusy(self: *const Client) bool {
if (self.http.active > 0 or self.http.intercepted > 0) {
return true;
}
const cdp = switch (self.mode) {
.cdp => |*c| c,
.http => return false,
};
const session = cdp.browser.session orelse return false;
if (session.browser.hasBackgroundTasks() or session.browser.msToNextMacrotask() != null) {
return true;
}
return false;
}
fn blockingReadStart(ctx: *anyopaque) bool { fn blockingReadStart(ctx: *anyopaque) bool {
const self: *Client = @ptrCast(@alignCast(ctx)); const self: *Client = @ptrCast(@alignCast(ctx));
self.ws.setBlocking(true) catch |err| { self.ws.setBlocking(true) catch |err| {

View File

@@ -144,11 +144,22 @@ fn run(allocator: Allocator, main_arena: Allocator) !void {
app.network.run(); app.network.run();
}, },
.mcp => { .mcp => |opts| {
log.info(.mcp, "starting server", .{}); log.info(.mcp, "starting server", .{});
log.opts.format = .logfmt; log.opts.format = .logfmt;
var cdp_server: ?*lp.Server = null;
if (opts.cdp_port) |port| {
const address = std.net.Address.parseIp("127.0.0.1", port) catch |err| {
log.fatal(.mcp, "invalid cdp address", .{ .err = err, .port = port });
return;
};
cdp_server = try lp.Server.init(app, address);
try sighandler.on(lp.Server.shutdown, .{cdp_server.?});
}
defer if (cdp_server) |s| s.deinit();
var worker_thread = try std.Thread.spawn(.{}, mcpThread, .{ allocator, app }); var worker_thread = try std.Thread.spawn(.{}, mcpThread, .{ allocator, app });
defer worker_thread.join(); defer worker_thread.join();

View File

@@ -9,57 +9,72 @@ const protocol = @import("protocol.zig");
const Server = @import("Server.zig"); const Server = @import("Server.zig");
const CDPNode = @import("../cdp/Node.zig"); const CDPNode = @import("../cdp/Node.zig");
const goto_schema = protocol.minify(
\\{
\\ "type": "object",
\\ "properties": {
\\ "url": { "type": "string", "description": "The URL to navigate to, must be a valid URL." },
\\ "timeout": { "type": "integer", "description": "Optional timeout in milliseconds. Defaults to 10000." },
\\ "waitUntil": { "type": "string", "enum": ["load", "domcontentloaded", "networkidle", "done"], "description": "Optional wait strategy. Defaults to 'done'." }
\\ },
\\ "required": ["url"]
\\}
);
const url_params_schema = protocol.minify(
\\{
\\ "type": "object",
\\ "properties": {
\\ "url": { "type": "string", "description": "Optional URL to navigate to before processing." },
\\ "timeout": { "type": "integer", "description": "Optional timeout in milliseconds. Defaults to 10000." },
\\ "waitUntil": { "type": "string", "enum": ["load", "domcontentloaded", "networkidle", "done"], "description": "Optional wait strategy. Defaults to 'done'." }
\\ }
\\}
);
const evaluate_schema = protocol.minify(
\\{
\\ "type": "object",
\\ "properties": {
\\ "script": { "type": "string" },
\\ "url": { "type": "string", "description": "Optional URL to navigate to before evaluating." },
\\ "timeout": { "type": "integer", "description": "Optional timeout in milliseconds. Defaults to 10000." },
\\ "waitUntil": { "type": "string", "enum": ["load", "domcontentloaded", "networkidle", "done"], "description": "Optional wait strategy. Defaults to 'done'." }
\\ },
\\ "required": ["script"]
\\}
);
pub const tool_list = [_]protocol.Tool{ pub const tool_list = [_]protocol.Tool{
.{ .{
.name = "goto", .name = "goto",
.description = "Navigate to a specified URL and load the page in memory so it can be reused later for info extraction.", .description = "Navigate to a specified URL and load the page in memory so it can be reused later for info extraction.",
.inputSchema = protocol.minify( .inputSchema = goto_schema,
\\{ },
\\ "type": "object", .{
\\ "properties": { .name = "navigate",
\\ "url": { "type": "string", "description": "The URL to navigate to, must be a valid URL." } .description = "Alias for goto. Navigate to a specified URL and load the page in memory.",
\\ }, .inputSchema = goto_schema,
\\ "required": ["url"]
\\}
),
}, },
.{ .{
.name = "markdown", .name = "markdown",
.description = "Get the page content in markdown format. If a url is provided, it navigates to that url first.", .description = "Get the page content in markdown format. If a url is provided, it navigates to that url first.",
.inputSchema = protocol.minify( .inputSchema = url_params_schema,
\\{
\\ "type": "object",
\\ "properties": {
\\ "url": { "type": "string", "description": "Optional URL to navigate to before fetching markdown." }
\\ }
\\}
),
}, },
.{ .{
.name = "links", .name = "links",
.description = "Extract all links in the opened page. If a url is provided, it navigates to that url first.", .description = "Extract all links in the opened page. If a url is provided, it navigates to that url first.",
.inputSchema = protocol.minify( .inputSchema = url_params_schema,
\\{
\\ "type": "object",
\\ "properties": {
\\ "url": { "type": "string", "description": "Optional URL to navigate to before extracting links." }
\\ }
\\}
),
}, },
.{ .{
.name = "evaluate", .name = "evaluate",
.description = "Evaluate JavaScript in the current page context. If a url is provided, it navigates to that url first.", .description = "Evaluate JavaScript in the current page context. If a url is provided, it navigates to that url first.",
.inputSchema = protocol.minify( .inputSchema = evaluate_schema,
\\{ },
\\ "type": "object", .{
\\ "properties": { .name = "eval",
\\ "script": { "type": "string" }, .description = "Alias for evaluate. Evaluate JavaScript in the current page context.",
\\ "url": { "type": "string", "description": "Optional URL to navigate to before evaluating." } .inputSchema = evaluate_schema,
\\ },
\\ "required": ["script"]
\\}
),
}, },
.{ .{
.name = "semantic_tree", .name = "semantic_tree",
@@ -69,6 +84,8 @@ pub const tool_list = [_]protocol.Tool{
\\ "type": "object", \\ "type": "object",
\\ "properties": { \\ "properties": {
\\ "url": { "type": "string", "description": "Optional URL to navigate to before fetching the semantic tree." }, \\ "url": { "type": "string", "description": "Optional URL to navigate to before fetching the semantic tree." },
\\ "timeout": { "type": "integer", "description": "Optional timeout in milliseconds. Defaults to 10000." },
\\ "waitUntil": { "type": "string", "enum": ["load", "domcontentloaded", "networkidle", "done"], "description": "Optional wait strategy. Defaults to 'done'." },
\\ "backendNodeId": { "type": "integer", "description": "Optional backend node ID to get the tree for a specific element instead of the document root." }, \\ "backendNodeId": { "type": "integer", "description": "Optional backend node ID to get the tree for a specific element instead of the document root." },
\\ "maxDepth": { "type": "integer", "description": "Optional maximum depth of the tree to return. Useful for exploring high-level structure first." } \\ "maxDepth": { "type": "integer", "description": "Optional maximum depth of the tree to return. Useful for exploring high-level structure first." }
\\ } \\ }
@@ -91,38 +108,17 @@ pub const tool_list = [_]protocol.Tool{
.{ .{
.name = "interactiveElements", .name = "interactiveElements",
.description = "Extract interactive elements from the opened page. If a url is provided, it navigates to that url first.", .description = "Extract interactive elements from the opened page. If a url is provided, it navigates to that url first.",
.inputSchema = protocol.minify( .inputSchema = url_params_schema,
\\{
\\ "type": "object",
\\ "properties": {
\\ "url": { "type": "string", "description": "Optional URL to navigate to before extracting interactive elements." }
\\ }
\\}
),
}, },
.{ .{
.name = "structuredData", .name = "structuredData",
.description = "Extract structured data (like JSON-LD, OpenGraph, etc) from the opened page. If a url is provided, it navigates to that url first.", .description = "Extract structured data (like JSON-LD, OpenGraph, etc) from the opened page. If a url is provided, it navigates to that url first.",
.inputSchema = protocol.minify( .inputSchema = url_params_schema,
\\{
\\ "type": "object",
\\ "properties": {
\\ "url": { "type": "string", "description": "Optional URL to navigate to before extracting structured data." }
\\ }
\\}
),
}, },
.{ .{
.name = "detectForms", .name = "detectForms",
.description = "Detect all forms on the page and return their structure including fields, types, and required status. If a url is provided, it navigates to that url first.", .description = "Detect all forms on the page and return their structure including fields, types, and required status. If a url is provided, it navigates to that url first.",
.inputSchema = protocol.minify( .inputSchema = url_params_schema,
\\{
\\ "type": "object",
\\ "properties": {
\\ "url": { "type": "string", "description": "Optional URL to navigate to before detecting forms." }
\\ }
\\}
),
}, },
.{ .{
.name = "click", .name = "click",
@@ -189,15 +185,21 @@ pub fn handleList(server: *Server, arena: std.mem.Allocator, req: protocol.Reque
const GotoParams = struct { const GotoParams = struct {
url: [:0]const u8, url: [:0]const u8,
timeout: ?u32 = null,
waitUntil: ?lp.Config.WaitUntil = null,
}; };
const UrlParams = struct { const UrlParams = struct {
url: ?[:0]const u8 = null, url: ?[:0]const u8 = null,
timeout: ?u32 = null,
waitUntil: ?lp.Config.WaitUntil = null,
}; };
const EvaluateParams = struct { const EvaluateParams = struct {
script: [:0]const u8, script: [:0]const u8,
url: ?[:0]const u8 = null, url: ?[:0]const u8 = null,
timeout: ?u32 = null,
waitUntil: ?lp.Config.WaitUntil = null,
}; };
const ToolStreamingText = struct { const ToolStreamingText = struct {
@@ -274,6 +276,7 @@ const ToolAction = enum {
structuredData, structuredData,
detectForms, detectForms,
evaluate, evaluate,
eval,
semantic_tree, semantic_tree,
click, click,
fill, fill,
@@ -291,6 +294,7 @@ const tool_map = std.StaticStringMap(ToolAction).initComptime(.{
.{ "structuredData", .structuredData }, .{ "structuredData", .structuredData },
.{ "detectForms", .detectForms }, .{ "detectForms", .detectForms },
.{ "evaluate", .evaluate }, .{ "evaluate", .evaluate },
.{ "eval", .eval },
.{ "semantic_tree", .semantic_tree }, .{ "semantic_tree", .semantic_tree },
.{ "click", .click }, .{ "click", .click },
.{ "fill", .fill }, .{ "fill", .fill },
@@ -324,7 +328,7 @@ pub fn handleCall(server: *Server, arena: std.mem.Allocator, req: protocol.Reque
.interactiveElements => try handleInteractiveElements(server, arena, req.id.?, call_params.arguments), .interactiveElements => try handleInteractiveElements(server, arena, req.id.?, call_params.arguments),
.structuredData => try handleStructuredData(server, arena, req.id.?, call_params.arguments), .structuredData => try handleStructuredData(server, arena, req.id.?, call_params.arguments),
.detectForms => try handleDetectForms(server, arena, req.id.?, call_params.arguments), .detectForms => try handleDetectForms(server, arena, req.id.?, call_params.arguments),
.evaluate => try handleEvaluate(server, arena, req.id.?, call_params.arguments), .eval, .evaluate => try handleEvaluate(server, arena, req.id.?, call_params.arguments),
.semantic_tree => try handleSemanticTree(server, arena, req.id.?, call_params.arguments), .semantic_tree => try handleSemanticTree(server, arena, req.id.?, call_params.arguments),
.click => try handleClick(server, arena, req.id.?, call_params.arguments), .click => try handleClick(server, arena, req.id.?, call_params.arguments),
.fill => try handleFill(server, arena, req.id.?, call_params.arguments), .fill => try handleFill(server, arena, req.id.?, call_params.arguments),
@@ -335,7 +339,7 @@ pub fn handleCall(server: *Server, arena: std.mem.Allocator, req: protocol.Reque
fn handleGoto(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void { fn handleGoto(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void {
const args = try parseArgs(GotoParams, arena, arguments, server, id, "goto"); const args = try parseArgs(GotoParams, arena, arguments, server, id, "goto");
try performGoto(server, args.url, id); try performGoto(server, args.url, id, args.timeout, args.waitUntil);
const content = [_]protocol.TextContent([]const u8){.{ .text = "Navigated successfully." }}; const content = [_]protocol.TextContent([]const u8){.{ .text = "Navigated successfully." }};
try server.sendResult(id, protocol.CallToolResult([]const u8){ .content = &content }); try server.sendResult(id, protocol.CallToolResult([]const u8){ .content = &content });
@@ -343,7 +347,7 @@ fn handleGoto(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arg
fn handleMarkdown(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void { fn handleMarkdown(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void {
const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id); const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id);
const page = try ensurePage(server, id, args.url); const page = try ensurePage(server, id, args.url, args.timeout, args.waitUntil);
const content = [_]protocol.TextContent(ToolStreamingText){.{ const content = [_]protocol.TextContent(ToolStreamingText){.{
.text = .{ .page = page, .action = .markdown }, .text = .{ .page = page, .action = .markdown },
@@ -355,7 +359,7 @@ fn handleMarkdown(server: *Server, arena: std.mem.Allocator, id: std.json.Value,
fn handleLinks(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void { fn handleLinks(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void {
const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id); const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id);
const page = try ensurePage(server, id, args.url); const page = try ensurePage(server, id, args.url, args.timeout, args.waitUntil);
const content = [_]protocol.TextContent(ToolStreamingText){.{ const content = [_]protocol.TextContent(ToolStreamingText){.{
.text = .{ .page = page, .action = .links }, .text = .{ .page = page, .action = .links },
@@ -370,9 +374,11 @@ fn handleSemanticTree(server: *Server, arena: std.mem.Allocator, id: std.json.Va
url: ?[:0]const u8 = null, url: ?[:0]const u8 = null,
backendNodeId: ?u32 = null, backendNodeId: ?u32 = null,
maxDepth: ?u32 = null, maxDepth: ?u32 = null,
timeout: ?u32 = null,
waitUntil: ?lp.Config.WaitUntil = null,
}; };
const args = try parseArgsOrDefault(TreeParams, arena, arguments, server, id); const args = try parseArgsOrDefault(TreeParams, arena, arguments, server, id);
const page = try ensurePage(server, id, args.url); const page = try ensurePage(server, id, args.url, args.timeout, args.waitUntil);
const content = [_]protocol.TextContent(ToolStreamingText){.{ const content = [_]protocol.TextContent(ToolStreamingText){.{
.text = .{ .text = .{
@@ -417,7 +423,7 @@ fn handleNodeDetails(server: *Server, arena: std.mem.Allocator, id: std.json.Val
fn handleInteractiveElements(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void { fn handleInteractiveElements(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void {
const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id); const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id);
const page = try ensurePage(server, id, args.url); const page = try ensurePage(server, id, args.url, args.timeout, args.waitUntil);
const elements = lp.interactive.collectInteractiveElements(page.document.asNode(), arena, page) catch |err| { const elements = lp.interactive.collectInteractiveElements(page.document.asNode(), arena, page) catch |err| {
log.err(.mcp, "elements collection failed", .{ .err = err }); log.err(.mcp, "elements collection failed", .{ .err = err });
@@ -438,7 +444,7 @@ fn handleInteractiveElements(server: *Server, arena: std.mem.Allocator, id: std.
fn handleStructuredData(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void { fn handleStructuredData(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void {
const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id); const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id);
const page = try ensurePage(server, id, args.url); const page = try ensurePage(server, id, args.url, args.timeout, args.waitUntil);
const data = lp.structured_data.collectStructuredData(page.document.asNode(), arena, page) catch |err| { const data = lp.structured_data.collectStructuredData(page.document.asNode(), arena, page) catch |err| {
log.err(.mcp, "struct data collection failed", .{ .err = err }); log.err(.mcp, "struct data collection failed", .{ .err = err });
@@ -453,7 +459,7 @@ fn handleStructuredData(server: *Server, arena: std.mem.Allocator, id: std.json.
fn handleDetectForms(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void { fn handleDetectForms(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void {
const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id); const args = try parseArgsOrDefault(UrlParams, arena, arguments, server, id);
const page = try ensurePage(server, id, args.url); const page = try ensurePage(server, id, args.url, args.timeout, args.waitUntil);
const forms_data = lp.forms.collectForms(arena, page.document.asNode(), page) catch |err| { const forms_data = lp.forms.collectForms(arena, page.document.asNode(), page) catch |err| {
log.err(.mcp, "form collection failed", .{ .err = err }); log.err(.mcp, "form collection failed", .{ .err = err });
@@ -474,7 +480,7 @@ fn handleDetectForms(server: *Server, arena: std.mem.Allocator, id: std.json.Val
fn handleEvaluate(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void { fn handleEvaluate(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arguments: ?std.json.Value) !void {
const args = try parseArgs(EvaluateParams, arena, arguments, server, id, "evaluate"); const args = try parseArgs(EvaluateParams, arena, arguments, server, id, "evaluate");
const page = try ensurePage(server, id, args.url); const page = try ensurePage(server, id, args.url, args.timeout, args.waitUntil);
var ls: js.Local.Scope = undefined; var ls: js.Local.Scope = undefined;
page.js.localScope(&ls); page.js.localScope(&ls);
@@ -630,9 +636,9 @@ fn handleWaitForSelector(server: *Server, arena: std.mem.Allocator, id: std.json
return server.sendResult(id, protocol.CallToolResult([]const u8){ .content = &content }); return server.sendResult(id, protocol.CallToolResult([]const u8){ .content = &content });
} }
fn ensurePage(server: *Server, id: std.json.Value, url: ?[:0]const u8) !*lp.Page { fn ensurePage(server: *Server, id: std.json.Value, url: ?[:0]const u8, timeout: ?u32, waitUntil: ?lp.Config.WaitUntil) !*lp.Page {
if (url) |u| { if (url) |u| {
try performGoto(server, u, id); try performGoto(server, u, id, timeout, waitUntil);
} }
return server.session.currentPage() orelse { return server.session.currentPage() orelse {
try server.sendError(id, .PageNotLoaded, "Page not loaded"); try server.sendError(id, .PageNotLoaded, "Page not loaded");
@@ -668,7 +674,7 @@ fn parseArgs(comptime T: type, arena: std.mem.Allocator, arguments: ?std.json.Va
}; };
} }
fn performGoto(server: *Server, url: [:0]const u8, id: std.json.Value) !void { fn performGoto(server: *Server, url: [:0]const u8, id: std.json.Value, timeout: ?u32, waitUntil: ?lp.Config.WaitUntil) !void {
const session = server.session; const session = server.session;
if (session.page != null) { if (session.page != null) {
session.removePage(); session.removePage();
@@ -689,7 +695,10 @@ fn performGoto(server: *Server, url: [:0]const u8, id: std.json.Value) !void {
try server.sendError(id, .InternalError, "Failed to start page runner"); try server.sendError(id, .InternalError, "Failed to start page runner");
return error.NavigationFailed; return error.NavigationFailed;
}; };
runner.wait(.{ .ms = 2000 }) catch { runner.wait(.{
.ms = timeout orelse 10000,
.until = waitUntil orelse .done,
}) catch {
try server.sendError(id, .InternalError, "Timeout waiting for page load"); try server.sendError(id, .InternalError, "Timeout waiting for page load");
return error.NavigationFailed; return error.NavigationFailed;
}; };