Skip to content

Commit 0852361

Browse files
oddharshChromium LUCI CQ
authored andcommitted
WebMCP: Reject tool results that can't be converted to a string
Imperative and declarative WebMCP tools both turn a non-object result into a string with `ScriptValue::ToString()`, which calls `ToString(context).ToLocalChecked()`. Converting a Symbol throws, so the `MaybeLocal` is empty and the renderer hits a fatal V8 error ("Empty MaybeLocal"): await document.modelContext.registerTool({ name: 'tool', description: 'desc', execute: () => Symbol(), }); const [tool] = await document.modelContext.getTools(); document.modelContext.executeTool(tool); // Crash. A declarative tool crashes the same way through `e.respondWith(Promise.resolve(Symbol()))`. This CL converts these results inside a `v8::TryCatch`, and fails the execution when conversion throws, the same way both paths already handle an object that can't be serialized to JSON. `executeTool()` then rejects with `OperationError`. For imperative tools this matches the spec: "invoke the execute callback" serializes the result to a JSON string, which throws for a Symbol, so the execution fails with "unserializable result". In `ModelContext`, the object and non-object branches now share one `TryCatch`. How other non-object results, such as strings and `undefined`, should serialize is a separate question, which I raised in webmachinelearning/webmcp#361. Adds unserializable-result cases (a Symbol, an object with a BigInt property, a throwing toJSON(), and a throwing getter) to the imperative executeTool-error-window-onerror test, and a declarative executeTool-respondWith-unserializable test covering the same cases. The Symbol cases crash without this CL. Also adds me to AUTHORS. [email protected], [email protected] Bug: None Change-Id: I6266226ae361e12e52df65b218b70f6a3102aba5 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/8640683 Reviewed-by: Mason Freed <[email protected]> Commit-Queue: Aadharsh Pannirselvam <[email protected]> Commit-Queue: Khushal Sagar <[email protected]> Reviewed-by: Khushal Sagar <[email protected]> Cr-Commit-Position: refs/heads/main@{#1740992}
1 parent 3bd9257 commit 0852361

5 files changed

Lines changed: 150 additions & 21 deletions

File tree

‎AUTHORS‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
# BEGIN individuals section.
1616
# keep-sorted start block=no case=no
17+
Aadharsh Pannirselvam <[email protected]>
1718
1819
Aaron Boushley <[email protected]>
1920
Aaron Dewes <[email protected]>

‎third_party/blink/renderer/core/html/forms/html_form_element.cc‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,21 @@ void HTMLFormElement::HandleWebMcpToolResponse(HTMLFormMcpTool* tool,
324324
}
325325

326326
if (result.IsNull()) {
327-
value.ToString(result);
327+
// Objects were handled above, so `value` is a primitive here. Symbol is
328+
// the only primitive whose string conversion throws.
329+
v8::TryCatch try_catch(script_state->GetIsolate());
330+
v8::Local<v8::String> string;
331+
if (!value.V8Value()
332+
->ToString(script_state->GetContext())
333+
.ToLocal(&string)) {
334+
tool->CallDoneCallback(base::unexpected(
335+
ScriptToolError(ScriptToolErrorCode::kToolInvocationFailed,
336+
"respondWith promise resolved with a value that "
337+
"could not be converted to a string")));
338+
return;
339+
}
340+
result = ToBlinkString<String>(script_state->GetIsolate(), string,
341+
kDoNotExternalize);
328342
}
329343
tool->CallDoneCallback(result);
330344
} else {

‎third_party/blink/renderer/core/script_tools/model_context.cc‎

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -246,33 +246,39 @@ class ModelContext::ToolFunctionFinishedCallback
246246

247247
void React(ScriptState* script_state, ScriptValue value) {
248248
if (success_) {
249-
std::optional<String> result;
250-
if (value.IsObject()) {
249+
String result;
250+
{
251251
v8::TryCatch try_catch(script_state->GetIsolate());
252-
v8::Local<v8::String> json_string;
253-
if (v8::JSON::Stringify(script_state->GetContext(), value.V8Value())
254-
.ToLocal(&json_string)) {
255-
result = ToBlinkString<String>(script_state->GetIsolate(),
256-
json_string, kDoNotExternalize);
252+
v8::Local<v8::Context> context = script_state->GetContext();
253+
v8::Local<v8::String> v8_result;
254+
if (value.IsObject()) {
255+
// Serializing to JSON runs script and can throw, e.g. for a cyclic
256+
// object, a BigInt property, or a throwing getter or toJSON().
257+
if (!v8::JSON::Stringify(context, value.V8Value())
258+
.ToLocal(&v8_result)) {
259+
CHECK(try_catch.HasCaught());
260+
HandleFailure(script_state, ScriptValue(script_state->GetIsolate(),
261+
try_catch.Exception()));
262+
return;
263+
}
257264
} else {
258-
CHECK(try_catch.HasCaught());
259-
HandleFailure(script_state, ScriptValue(script_state->GetIsolate(),
260-
try_catch.Exception()));
261-
return;
262-
}
263-
}
264-
265-
if (!result) {
266-
String temp;
267-
if (value.ToString(temp)) {
268-
result.emplace(std::move(temp));
265+
// `value` is a primitive, and Symbol is the only primitive whose
266+
// string conversion throws.
267+
if (!value.V8Value()->ToString(context).ToLocal(&v8_result)) {
268+
CHECK(try_catch.HasCaught());
269+
HandleFailure(script_state, ScriptValue(script_state->GetIsolate(),
270+
try_catch.Exception()));
271+
return;
272+
}
269273
}
274+
result = ToBlinkString<String>(script_state->GetIsolate(), v8_result,
275+
kDoNotExternalize);
270276
}
271277

272-
if (!result || result->empty()) {
278+
if (result.empty()) {
273279
result = "Operation succeeded";
274280
}
275-
model_context_->OnToolExecuted(invocation_id_, *result);
281+
model_context_->OnToolExecuted(invocation_id_, result);
276282
} else {
277283
HandleFailure(script_state, value);
278284
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<!DOCTYPE html>
2+
<meta charset="utf-8">
3+
<title>WebMCP: executeTool with declarative tool returning an unserializable value via respondWith</title>
4+
<script src="/resources/testharness.js"></script>
5+
<script src="/resources/testharnessreport.js"></script>
6+
<script src="../resources/helpers.js"></script>
7+
<body>
8+
<form id="form" toolname="unserializable_tool" tooldescription="Declarative tool returning an unserializable value" toolautosubmit>
9+
</form>
10+
11+
<script>
12+
// Each case returns a value that can't become a tool result string: either
13+
// JSON serialization (objects) or string conversion (primitives) throws.
14+
const cases = [
15+
{
16+
description: 'a Symbol',
17+
makeResult: () => Symbol('result'),
18+
},
19+
{
20+
description: 'an object with a BigInt property',
21+
makeResult: () => ({value: 1n}),
22+
},
23+
{
24+
description: 'an object whose toJSON() throws',
25+
makeResult: () => ({toJSON() { throw new Error('toJSON'); }}),
26+
},
27+
{
28+
description: 'an object with a throwing getter',
29+
makeResult: () => ({get value() { throw new Error('getter'); }}),
30+
},
31+
];
32+
33+
let makeResult;
34+
const form = document.querySelector('#form');
35+
form.addEventListener('submit', (e) => {
36+
e.preventDefault();
37+
e.respondWith(Promise.resolve(makeResult()));
38+
});
39+
40+
for (const {description, makeResult: make} of cases) {
41+
promise_test(async t => {
42+
const tool = await waitForTool('unserializable_tool');
43+
makeResult = make;
44+
45+
await promise_rejects_dom(
46+
t,
47+
'OperationError',
48+
document.modelContext.executeTool(tool),
49+
`executeTool() should reject with OperationError when respondWith is passed ${description}`
50+
);
51+
}, `Declarative tool executeTool() rejects when respondWith() receives ${description}`);
52+
}
53+
</script>
54+
</body>

‎third_party/blink/web_tests/external/wpt/webmcp/imperative/executeTool-error-window-onerror.https.html‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,60 @@
7171

7272
assert_false(errorFired, 'window.onerror/error event should not be fired');
7373
}, 'Tool execution returning circular object rejects and does not trigger window.onerror');
74+
75+
// Each case returns a value that can't become a tool result string: either
76+
// JSON serialization (objects) or string conversion (primitives) throws.
77+
const unserializableCases = [
78+
{
79+
name: 'symbol_tool',
80+
description: 'a Symbol',
81+
execute: () => Symbol('result'),
82+
},
83+
{
84+
name: 'bigint_property_tool',
85+
description: 'an object with a BigInt property',
86+
execute: () => ({value: 1n}),
87+
},
88+
{
89+
name: 'throwing_tojson_tool',
90+
description: 'an object whose toJSON() throws',
91+
execute: () => ({toJSON() { throw new Error('toJSON'); }}),
92+
},
93+
{
94+
name: 'throwing_getter_tool',
95+
description: 'an object with a throwing getter',
96+
execute: () => ({get value() { throw new Error('getter'); }}),
97+
},
98+
];
99+
100+
for (const {name, description, execute} of unserializableCases) {
101+
promise_test(async t => {
102+
let errorFired = false;
103+
const errorHandler = () => {
104+
errorFired = true;
105+
};
106+
window.addEventListener('error', errorHandler);
107+
t.add_cleanup(() => {
108+
window.removeEventListener('error', errorHandler);
109+
});
110+
111+
await document.modelContext.registerTool({
112+
name,
113+
description: `A tool that returns ${description}`,
114+
execute
115+
});
116+
117+
const tools = await document.modelContext.getTools();
118+
const tool = tools.find(t => t.name === name);
119+
assert_true(!!tool, 'Should find the registered tool');
120+
121+
await promise_rejects_dom(t, 'OperationError',
122+
document.modelContext.executeTool(tool),
123+
`executeTool() rejects when the tool execution returns ${description}`);
124+
125+
assert_false(errorFired, 'window.onerror/error event should not be fired');
126+
}, `Tool execution returning ${description} rejects and does not trigger window.onerror`);
127+
}
74128
</script>
75129
</body>
76130
</html>

0 commit comments

Comments
 (0)