mcp: improve error handling in resources and tools

- Handle failures during HTML, Markdown, and link serialization.
- Return MCP internal errors when result serialization fails.
- Refactor resource reading logic for better clarity and consistency.
This commit is contained in:
Adrià Arrufat
2026-03-27 11:28:47 +09:00
parent cdd33621e3
commit c8d8ca5e94
2 changed files with 42 additions and 34 deletions

View File

@@ -28,6 +28,7 @@ pub fn handleList(server: *Server, req: protocol.Request) !void {
const ReadParams = struct {
uri: []const u8,
};
const Format = enum { html, markdown };
const ResourceStreamingResult = struct {
contents: []const struct {
@@ -38,7 +39,7 @@ const ResourceStreamingResult = struct {
const StreamingText = struct {
page: *lp.Page,
format: enum { html, markdown },
format: Format,
pub fn jsonStringify(self: @This(), jw: *std.json.Stringify) !void {
try jw.beginWriteRaw();
@@ -47,9 +48,11 @@ const ResourceStreamingResult = struct {
switch (self.format) {
.html => lp.dump.root(self.page.document, .{}, &escaped.writer, self.page) catch |err| {
log.err(.mcp, "html dump failed", .{ .err = err });
return error.WriteFailed;
},
.markdown => lp.markdown.dump(self.page.document.asNode(), .{}, &escaped.writer, self.page) catch |err| {
log.err(.mcp, "markdown dump failed", .{ .err = err });
return error.WriteFailed;
},
}
try jw.writer.writeByte('"');
@@ -86,28 +89,25 @@ pub fn handleRead(server: *Server, arena: std.mem.Allocator, req: protocol.Reque
return server.sendError(req_id, .PageNotLoaded, "Page not loaded");
};
switch (uri) {
.@"mcp://page/html" => {
const result: ResourceStreamingResult = .{
.contents = &.{.{
.uri = params.uri,
.mimeType = "text/html",
.text = .{ .page = page, .format = .html },
}},
};
try server.sendResult(req_id, result);
},
.@"mcp://page/markdown" => {
const result: ResourceStreamingResult = .{
.contents = &.{.{
.uri = params.uri,
.mimeType = "text/markdown",
.text = .{ .page = page, .format = .markdown },
}},
};
try server.sendResult(req_id, result);
},
}
const format: Format = switch (uri) {
.@"mcp://page/html" => .html,
.@"mcp://page/markdown" => .markdown,
};
const mime_type: []const u8 = switch (uri) {
.@"mcp://page/html" => "text/html",
.@"mcp://page/markdown" => "text/markdown",
};
const result: ResourceStreamingResult = .{
.contents = &.{.{
.uri = params.uri,
.mimeType = mime_type,
.text = .{ .page = page, .format = format },
}},
};
server.sendResult(req_id, result) catch {
return server.sendError(req_id, .InternalError, "Failed to serialize resource content");
};
}
const testing = @import("../testing.zig");