From a95874be4611bf568aee8d61b594c4dd8b497256 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Tue, 17 Nov 2026 12:10:34 -0500 Subject: [PATCH 01/26] fix: plain input schemas for ui_snapshot and ui_action (#145) ui_snapshot.window and ui_action.value used anyOf, which some MCP clients (Grok connector) reject, dropping both tools from their list. Both are now a single {"type":"string"}; the descriptions tell clients to send strings. The runtime parsers are unchanged and still accept a native integer window index and a native number/bool value for existing callers. Adds ToolSchemaShapeTests: walks every ToolCatalog.local inputSchema and fails on anyOf/oneOf/allOf/not or a type array; plus parser tests for the old argument shapes. Verified: swift test on macOS 26 and macOS 27 hosts, clones under /private/tmp, 733 tests, 0 failures on both. The walker fails when anyOf is put back (remote copy only). check-no-private-identifiers.sh ok; markdownlint-cli2 on docs/ui-tools.md: 0 errors. --- .../InstanceMCPCore/Tools/UIActionTool.swift | 5 +- .../Tools/UISnapshotTool.swift | 4 +- .../ToolSchemaShapeTests.swift | 75 +++++++++++++++++++ docs/ui-tools.md | 4 +- 4 files changed, 81 insertions(+), 7 deletions(-) create mode 100644 Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift diff --git a/Sources/InstanceMCPCore/Tools/UIActionTool.swift b/Sources/InstanceMCPCore/Tools/UIActionTool.swift index 95dd886..d70c28f 100644 --- a/Sources/InstanceMCPCore/Tools/UIActionTool.swift +++ b/Sources/InstanceMCPCore/Tools/UIActionTool.swift @@ -26,9 +26,8 @@ public struct UIActionTool: Tool { "snapshot_id": ["type": "string", "description": "The snapshot_id of the ui_snapshot the ref came from."], "ref": ["type": "string", "pattern": .string(UIActionTool.refPattern), "description": "A node ref from that snapshot (e1, e2, …)."], "action": ["type": "string", "enum": .array(UIActionKind.allCases.map { .string($0.rawValue) })], - "value": ["anyOf": [["type": "string", "maxLength": .number(Double(UIActionTool.maxValueLength))], - ["type": "number"], ["type": "boolean"]], - "description": "The new value; set_value only. Never logged or echoed."], + "value": ["type": "string", "maxLength": .number(Double(UIActionTool.maxValueLength)), + "description": "The new value, passed as a string (for example '3' or 'true'); set_value only. Never logged or echoed. A string is set as is. Existing callers that send a native JSON number or boolean are still accepted and set as that number or boolean."], "activate": ["type": "boolean", "default": false, "description": "Bring the app to the front first (and raise the ref's window). Default false: no focus stealing."], "timeout_ms": ["type": "integer", "description": "Total time budget for the call; the action itself gets what is left after the checks.", diff --git a/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift b/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift index 29cea07..3e7e31a 100644 --- a/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift +++ b/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift @@ -20,8 +20,8 @@ public struct UISnapshotTool: Tool { "properties": [ "app": ["type": "string", "description": "Bundle id (com.apple.TextEdit) or app name (TextEdit). Default: frontmost app."], "pid": ["type": "integer", "description": "Process id. Use instead of app when several apps match."], - "window": ["anyOf": [["type": "string"], ["type": "integer", "minimum": 0]], - "description": "Window title (exact, else case-insensitive substring) or index into the app's window list. Default: focused window."], + "window": ["type": "string", + "description": "Window title as a string (exact, else case-insensitive substring); a string is always read as a title, even when it looks like a number. Existing callers that send a native JSON integer ≥ 0 still select that index in the app's window list. Default: focused window."], "all_windows": ["type": "boolean", "description": "Walk every window of the app.", "default": false], "include_menu_bar": ["type": "boolean", "description": "Also walk the app's menu bar, after the windows (it shares max_nodes), so menu items get refs for ui_action.", "default": false], "max_depth": ["type": "integer", "description": "Levels below the window.", diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift new file mode 100644 index 0000000..cf6a72f --- /dev/null +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -0,0 +1,75 @@ +import Foundation +import XCTest +@testable import InstanceMCPCore + +/// Some MCP clients (Grok's connector, many function-calling validators) drop a tool whose +/// input schema uses composition keywords or a `type` array inside a property. ui_snapshot +/// and ui_action vanished from Grok's tool list that way. Every advertised property must +/// have one plain type. +final class ToolSchemaShapeTests: XCTestCase { + static let banned: Set = ["anyOf", "oneOf", "allOf", "not"] + + /// Paths of banned constructs in a schema. A key named like a banned keyword under + /// `properties` is a property name, not a keyword, so it is skipped. + static func violations(_ v: JSONValue, path: String, inPropertyMap: Bool = false) -> [String] { + var out: [String] = [] + switch v { + case .object(let o): + for (k, child) in o.sorted(by: { $0.key < $1.key }) { + if !inPropertyMap { + if banned.contains(k) { out.append("\(path).\(k)") } + if k == "type", child.arrayValue != nil { out.append("\(path).type is an array") } + } + out += violations(child, path: "\(path).\(k)", inPropertyMap: !inPropertyMap && k == "properties") + } + case .array(let a): + for (i, child) in a.enumerated() { out += violations(child, path: "\(path)[\(i)]") } + default: break + } + return out + } + + func testNoLocalToolSchemaUsesCompositionOrTypeArrays() { + let tools = ToolCatalog.local(agentVersion: "test") + XCTAssertGreaterThan(tools.count, 10) + for t in tools { + XCTAssertEqual(t.inputSchema["type"]?.stringValue, "object", "\(t.name): top-level type") + let bad = Self.violations(t.inputSchema, path: t.name) + XCTAssertTrue(bad.isEmpty, "\(t.name) uses a construct some MCP clients reject: \(bad)") + } + } + + func testEveryPropertyHasAPlainType() { + for t in ToolCatalog.local(agentVersion: "test") { + for (name, schema) in t.inputSchema["properties"]?.objectValue ?? [:] { + XCTAssertNotNil(schema["type"]?.stringValue, "\(t.name).\(name) has no single string type") + } + } + } + + func testWalkerCatchesBannedConstructs() { + XCTAssertEqual(Self.violations(["properties": ["a": ["anyOf": [["type": "string"]]]]], path: "t"), + ["t.properties.a.anyOf"]) + XCTAssertEqual(Self.violations(["properties": ["a": ["type": ["string", "null"]]]], path: "t"), + ["t.properties.a.type is an array"]) + XCTAssertEqual(Self.violations(["properties": ["not": ["type": "string"]]], path: "t"), []) + } + + // The runtime parsers keep the shapes the old schemas allowed. + func testSnapshotWindowAcceptsTitleAndIndex() throws { + XCTAssertEqual(try UISnapshotTool.parse(["window": "Untitled"]).window, .title("Untitled")) + XCTAssertEqual(try UISnapshotTool.parse(["window": 2]).window, .index(2)) + XCTAssertEqual(try UISnapshotTool.parse(["window": 0]).window, .index(0)) + XCTAssertThrowsError(try UISnapshotTool.parse(["window": -1])) + } + + func testActionValueAcceptsStringNumberAndBool() throws { + func value(_ v: JSONValue) throws -> UIAttrValue? { + try UIActionTool.parse(["snapshot_id": "s", "ref": "e1", "action": "set_value", "value": v]).value + } + XCTAssertEqual(try value("hello"), .string("hello")) + XCTAssertEqual(try value(12), .number(12)) + XCTAssertEqual(try value(true), .bool(true)) + XCTAssertThrowsError(try value(["a": 1])) + } +} diff --git a/docs/ui-tools.md b/docs/ui-tools.md index 46477e7..a2ef682 100644 --- a/docs/ui-tools.md +++ b/docs/ui-tools.md @@ -9,7 +9,7 @@ has the summary. Both tools are macOS only; the Linux AT-SPI port is deferred Accessibility tree of a native app's window (AXUIElement), read-only. `owner` only. - **Target.** Default: the frontmost app's focused window. `app` (bundle id or name) or `pid` - selects an app; `window` (title or index) or `all_windows` selects windows. + selects an app; `window` (a title string; existing callers may still send a native JSON integer index) or `all_windows` selects windows. `include_menu_bar` also walks the app's menu bar, so menu items get refs. - **Per node.** Role, subrole, title, value (secure fields always masked), state, frame in display points (the `screenshot`/`mouse` space, with display index), and a `ref` valid within @@ -28,7 +28,7 @@ Acts on a `ui_snapshot` node by ref through the Accessibility API, without movin - **Arguments.** `snapshot_id` + `ref` + `action`. - **Actions.** - `press` (AXPress). - - `set_value` (AXValue, with `value`: string, number or bool; replaces the whole value). + - `set_value` (AXValue, with `value`, advertised and passed as a string, e.g. `"3"` or `"true"`; existing callers' native JSON number or bool are still accepted; replaces the whole value). - `focus` (sets AXFocused; never raises a window; refused where AXFocused is not settable). - `show_menu`, `confirm`, `cancel`, `increment`, `decrement`. - **Unsupported actions.** An action the element does not support is refused before anything is From 08c525aac9a59575390a916c46ea812a388d5684 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:48:25 -0500 Subject: [PATCH 02/26] fix: ui_action set_value type fallback and ui_snapshot window_index Review fixes for PR #146, final report issues 1, 2, 5, 6 and 10. Issue 1: a string set_value that a numeric or boolean control refuses with kAXErrorIllegalArgument (-25201) is written again as the native value the string spells ("3" becomes 3, "true" becomes true). A refused write changes nothing, so the second write is safe. If the retry also fails, or the string has no native form, the error names the type mismatch and the retry that works. -25201 on set_value no longer reaches the "does not support set_value" message. Focus keeps its previous path. Issue 2 (choice): ui_snapshot gets a flat `window_index` integer, minimum 0. Reason: a string encoding of an index needs a parsing rule a strict client cannot check, while an integer property is valid under the plain-type schema. Native JSON integers in `window` still select an index for existing callers. Sending both `window` and `window_index` is invalid params. The window index error now points at window_index. Issues 5 and 6: the ui_snapshot tool description and the window and value property descriptions state only what a model can send. The compatibility sentences moved out of the descriptions. Issue 10: the parse sites for window and value carry comments naming #145 and the intentional asymmetry with the schema. docs/ui-tools.md documents window_index. Commands (one run at the series head, macOS test host, copy of the worktree without .agents, .git, .build): swift test Suites touched: UIActionToolTests 44 passed; UISnapshotToolTests 11 passed. Failures: 0. Full run: 751 executed, 0 failures, 5 skipped (default-port launch test skipped while the installed agent holds 8795; real Playwright install gated by OAB_REAL_INSTALL; two snapshot renders gated by OAB_SNAPSHOT_DIR; one release-binary check). --- .../InstanceMCPCore/Tools/UIActionTool.swift | 14 +++++- .../Tools/UISnapshotTool.swift | 17 +++++-- .../InstanceMCPCore/UISnapshot/UIAction.swift | 22 ++++++++- .../UISnapshot/UIElementProvider.swift | 3 ++ .../InstanceMCPCoreTests/UIActionTests.swift | 48 +++++++++++++++++++ .../UISnapshotTests.swift | 5 +- docs/ui-tools.md | 3 +- 7 files changed, 105 insertions(+), 7 deletions(-) diff --git a/Sources/InstanceMCPCore/Tools/UIActionTool.swift b/Sources/InstanceMCPCore/Tools/UIActionTool.swift index d70c28f..c0758a1 100644 --- a/Sources/InstanceMCPCore/Tools/UIActionTool.swift +++ b/Sources/InstanceMCPCore/Tools/UIActionTool.swift @@ -27,7 +27,7 @@ public struct UIActionTool: Tool { "ref": ["type": "string", "pattern": .string(UIActionTool.refPattern), "description": "A node ref from that snapshot (e1, e2, …)."], "action": ["type": "string", "enum": .array(UIActionKind.allCases.map { .string($0.rawValue) })], "value": ["type": "string", "maxLength": .number(Double(UIActionTool.maxValueLength)), - "description": "The new value, passed as a string (for example '3' or 'true'); set_value only. Never logged or echoed. A string is set as is. Existing callers that send a native JSON number or boolean are still accepted and set as that number or boolean."], + "description": "The new value as a string, for example '3' or 'true'. set_value only. It replaces the whole value and is never logged or echoed."], "activate": ["type": "boolean", "default": false, "description": "Bring the app to the front first (and raise the ref's window). Default false: no focus stealing."], "timeout_ms": ["type": "integer", "description": "Total time budget for the call; the action itself gets what is left after the checks.", @@ -72,6 +72,14 @@ public struct UIActionTool: Tool { (supported.isEmpty ? "No ui_action action is supported on it; use screenshot + mouse" : "Supported on it: \(supported.joined(separator: ", "))") } + /// AX refused the value's type (kAXErrorIllegalArgument) on `set_value`. Not an + /// unsupported action, so the supported list is not shown. + public static func valueTypeRejected(ref: String, role: String, retried: Bool) -> String { + if retried { + return "\(ref) (\(role)) rejected the value as text and as a number or boolean (AX error -25201). Take a new ui_snapshot to check the control's current value type" + } + return "\(ref) (\(role)) rejected the value's type (AX error -25201). A numeric or boolean control takes a native JSON number or boolean (for example 3 or true), not a string; a text control takes a string" + } public static func unconfirmed(action: String, ref: String, app: String) -> String { "ui_action \(action) [\(ref)]: \(app) did not confirm in time. The action may have happened (a press that opens a dialog or menu often answers late); take a new ui_snapshot to check, and do not repeat it blindly" } @@ -150,6 +158,10 @@ public struct UIActionTool: Tool { r.action = kind if let v = a["value"], !v.isNull { guard kind == .setValue else { throw JSONRPCError.invalidParams("value is only accepted with set_value") } + // The schema advertises only a string. A native JSON number or boolean is still + // parsed for existing callers (#145, which replaced the anyOf schema). This + // asymmetry is intentional: do not narrow this switch to the schema without + // checking those callers. switch v { case .string(let s): guard s.count <= maxValueLength else { diff --git a/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift b/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift index 3e7e31a..5d28fd7 100644 --- a/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift +++ b/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift @@ -8,7 +8,7 @@ public struct UISnapshotTool: Tool { public let description = """ Read the accessibility tree of a native macOS app window (read-only): roles, titles, values, \ state and frames. Default target: the frontmost app's focused window; pass `app` (bundle id or \ - name) or `pid`, and `window` (title or index) or `all_windows`. Frames are display POINTS relative \ + name) or `pid`, and `window` (a title) or `window_index` (an index), or `all_windows`. Frames are display POINTS relative \ to `display`, the same space `screenshot` and `mouse` use. Each node has a `ref` valid only within \ this `snapshot_id`; `ui_action` acts on a node by `{snapshot_id, ref}` (the last 4 snapshots stay \ usable for 5 minutes). Pass `include_menu_bar` to also walk the app's menu bar. Secure text fields \ @@ -21,7 +21,9 @@ public struct UISnapshotTool: Tool { "app": ["type": "string", "description": "Bundle id (com.apple.TextEdit) or app name (TextEdit). Default: frontmost app."], "pid": ["type": "integer", "description": "Process id. Use instead of app when several apps match."], "window": ["type": "string", - "description": "Window title as a string (exact, else case-insensitive substring); a string is always read as a title, even when it looks like a number. Existing callers that send a native JSON integer ≥ 0 still select that index in the app's window list. Default: focused window."], + "description": "Window title: exact match, else case-insensitive substring. A string is always read as a title, even when it looks like a number. Default: focused window."], + "window_index": ["type": "integer", "minimum": .number(0), + "description": "Index in the app's window list, starting at 0. Use it for an untitled window or when titles repeat. Do not send with window."], "all_windows": ["type": "boolean", "description": "Walk every window of the app.", "default": false], "include_menu_bar": ["type": "boolean", "description": "Also walk the app's menu bar, after the windows (it shares max_nodes), so menu items get refs for ui_action.", "default": false], "max_depth": ["type": "integer", "description": "Levels below the window.", @@ -122,14 +124,23 @@ public struct UISnapshotTool: Tool { r.pid = Int32(p) } if let v = a["window"], !v.isNull { + // The schema advertises only a title string (#145, which replaced the anyOf + // schema). A native JSON integer is still read as an index for existing callers. + // This asymmetry is intentional: do not narrow this branch to the schema without + // checking those callers. if let i = v.intValue, i >= 0 { r.window = .index(i) } else if let s = v.stringValue, !s.isEmpty { r.window = .title(s) } else { - throw JSONRPCError.invalidParams("window must be a non-empty title or a window index ≥ 0") + throw JSONRPCError.invalidParams("window must be a non-empty title, or use window_index for an index ≥ 0") } } + if let v = a["window_index"], !v.isNull { + guard let i = v.intValue, i >= 0 else { throw JSONRPCError.invalidParams("window_index must be an integer ≥ 0") } + guard r.window == nil else { throw JSONRPCError.invalidParams("pass window or window_index, not both") } + r.window = .index(i) + } if let v = a["all_windows"], !v.isNull { guard let b = v.boolValue else { throw JSONRPCError.invalidParams("all_windows must be a boolean") } r.allWindows = b diff --git a/Sources/InstanceMCPCore/UISnapshot/UIAction.swift b/Sources/InstanceMCPCore/UISnapshot/UIAction.swift index 233e104..bc7293f 100644 --- a/Sources/InstanceMCPCore/UISnapshot/UIAction.swift +++ b/Sources/InstanceMCPCore/UISnapshot/UIAction.swift @@ -202,11 +202,19 @@ struct UIActionEngine { // 4. The action. It gets the whole remaining budget: apps answer an AXPress only // after handling it. guard deadline.armAll(e) else { throw ToolError(E.appBusy(appName)) } - let done: Result + var done: Result + var retriedNative = false switch req.action { case .setValue: guard let v = req.value else { throw ToolError(E.unsupported(action: req.action.rawValue, ref: req.ref, role: role, supported: [])) } done = e.setValue(AXAttr.value, v) + // The schema advertises only strings, so a numeric or boolean control gets a + // string it refuses with kAXErrorIllegalArgument. A refused write changed nothing, + // so the same value is written once more as the native type the string spells. + if case .failure(.other(UIAXError.illegalArgumentCode)) = done, let native = Self.nativeValue(v) { + retriedNative = true + done = e.setValue(AXAttr.value, native) + } case .focus: done = e.setValue(AXAttr.focused, .bool(true)) default: @@ -217,6 +225,9 @@ struct UIActionEngine { case .failure(.timeout): throw ToolError(E.unconfirmed(action: req.action.rawValue, ref: req.ref, app: appName)) case .failure(.invalidElement): throw stale("vanished before the action ran") case .failure(.apiDisabled): throw ToolError(E.notTrusted) + // Checked before `isUnsupported`: a refused value type is not a missing action. + case .failure(.other(UIAXError.illegalArgumentCode)) where req.action == .setValue: + throw ToolError(E.valueTypeRejected(ref: req.ref, role: role, retried: retriedNative)) case .failure(let err) where err.isUnsupported: throw try unsupported() case .failure(.other(let code)): throw ToolError(E.failed(action: req.action.rawValue, ref: req.ref, code: code)) } @@ -275,6 +286,15 @@ struct UIActionEngine { return ToolResult(content: [.text(text)], structured: .object(o)) } + /// The native number or boolean a string spells (`"3"`, `"true"`), or nil. + static func nativeValue(_ v: UIAttrValue) -> UIAttrValue? { + guard case .string(let s) = v else { return nil } + if s == "true" { return .bool(true) } + if s == "false" { return .bool(false) } + if let d = Double(s), d.isFinite { return .number(d) } + return nil + } + private enum PostValue { case value(JSONValue, truncated: Bool), gone } /// The element's value after the action, as `ui_snapshot` would show it: a long diff --git a/Sources/InstanceMCPCore/UISnapshot/UIElementProvider.swift b/Sources/InstanceMCPCore/UISnapshot/UIElementProvider.swift index 27fa5b1..b9d2a2f 100644 --- a/Sources/InstanceMCPCore/UISnapshot/UIElementProvider.swift +++ b/Sources/InstanceMCPCore/UISnapshot/UIElementProvider.swift @@ -62,6 +62,9 @@ public protocol UIElement: AnyObject { } extension UIAXError { + /// kAXErrorIllegalArgument. A numeric or boolean control refuses a string value with it. + static let illegalArgumentCode: Int32 = -25201 + /// The element does not support the attribute or action asked for (or rejects the /// argument): attributeUnsupported, actionUnsupported, notImplemented, illegalArgument. var isUnsupported: Bool { diff --git a/Tests/InstanceMCPCoreTests/UIActionTests.swift b/Tests/InstanceMCPCoreTests/UIActionTests.swift index 90ff0ac..128eee1 100644 --- a/Tests/InstanceMCPCoreTests/UIActionTests.swift +++ b/Tests/InstanceMCPCoreTests/UIActionTests.swift @@ -330,6 +330,54 @@ final class UIActionToolTests: XCTestCase { assertNothingDone(f) } + func testStringRefusedByNumericControlIsRetriedAsNumber() async { + let f = Fixture() + let id = await f.snapshot() + f.textArea.settable = ["AXValue"] + f.textArea.refusesStrings = true + let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "3"]) + XCTAssertFalse(r.isToolError, r.text) + XCTAssertEqual(f.textArea.sets.map(\.1), [.number(3)]) + XCTAssertEqual(r.structured?["success"], true) + } + + func testStringRefusedByNumericControlIsRetriedAsBool() async { + let f = Fixture() + let id = await f.snapshot() + f.textArea.settable = ["AXValue"] + f.textArea.refusesStrings = true + let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "true"]) + XCTAssertFalse(r.isToolError, r.text) + XCTAssertEqual(f.textArea.sets.map(\.1), [.bool(true)]) + } + + func testValueTypeRefusalIsNotReportedAsUnsupported() async { + let f = Fixture() + let id = await f.snapshot() + f.textArea.settable = ["AXValue"] + f.textArea.refusesStrings = true + // "hello" has no native form, so there is nothing to retry: the refusal is named as a type + // mismatch, not as an unsupported action, and the supported list is not shown. + let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "hello"]) + XCTAssertTrue(r.isToolError) + XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: false)) + XCTAssertFalse(r.text.contains("does not support"), r.text) + XCTAssertFalse(r.text.contains("Supported on it"), r.text) + assertNothingDone(f) + } + + func testValueTypeRefusedInBothFormsSaysSo() async { + let f = Fixture() + let id = await f.snapshot() + f.textArea.settable = ["AXValue"] + f.textArea.setError = .other(UIAXError.illegalArgumentCode) + let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "3"]) + XCTAssertTrue(r.isToolError) + XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: true)) + XCTAssertFalse(r.text.contains("3"), "the value is never echoed: \(r.text)") + assertNothingDone(f) + } + func testNoSupportedActionPointsToMouse() async { let f = Fixture() let id = await f.snapshot() diff --git a/Tests/InstanceMCPCoreTests/UISnapshotTests.swift b/Tests/InstanceMCPCoreTests/UISnapshotTests.swift index 3f9e048..dc62a4b 100644 --- a/Tests/InstanceMCPCoreTests/UISnapshotTests.swift +++ b/Tests/InstanceMCPCoreTests/UISnapshotTests.swift @@ -37,6 +37,8 @@ final class FakeUIElement: UIElement, @unchecked Sendable { var settableError: UIAXError? var performError: UIAXError? var setError: UIAXError? + /// A numeric or boolean control: a string value is refused with kAXErrorIllegalArgument. + var refusesStrings = false /// Actions performed and attributes set, in order. var performed: [String] = [] var sets: [(String, UIAttrValue)] = [] @@ -140,6 +142,7 @@ final class FakeUIElement: UIElement, @unchecked Sendable { calls.append(("set " + name, timeouts.last)) if spend() { return .failure(.timeout) } if let setError { return .failure(setError) } + if refusesStrings, case .string = value { return .failure(.other(UIAXError.illegalArgumentCode)) } sets.append((name, value)) attrs[name] = value onPerform?() @@ -879,7 +882,7 @@ final class UISnapshotToolTests: XCTestCase { let cases: [(JSONValue, String)] = [(["app": "TextEdit", "pid": 20], "pass app or pid, not both"), (["window": "x", "all_windows": true], "pass window or all_windows, not both"), (["max_nodes": 1.5], "max_nodes must be an integer"), - (["window": -1], "window must be a non-empty title or a window index ≥ 0"), + (["window": -1], "window must be a non-empty title, or use window_index for an index ≥ 0"), (["app": ""], "app must be a non-empty string")] for (args, why) in cases { let r = await call(args) diff --git a/docs/ui-tools.md b/docs/ui-tools.md index a2ef682..0ef7ffe 100644 --- a/docs/ui-tools.md +++ b/docs/ui-tools.md @@ -9,7 +9,8 @@ has the summary. Both tools are macOS only; the Linux AT-SPI port is deferred Accessibility tree of a native app's window (AXUIElement), read-only. `owner` only. - **Target.** Default: the frontmost app's focused window. `app` (bundle id or name) or `pid` - selects an app; `window` (a title string; existing callers may still send a native JSON integer index) or `all_windows` selects windows. + selects an app; `window` (a title string) or `window_index` (an integer index, for an untitled or + duplicate-title window; `window` also still takes a native JSON integer for existing callers) or `all_windows` selects windows. `include_menu_bar` also walks the app's menu bar, so menu items get refs. - **Per node.** Role, subrole, title, value (secure fields always masked), state, frame in display points (the `screenshot`/`mouse` space, with display index), and a `ref` valid within From a655bebdd582ec6780750e228edbdb7a739d0380 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:48:35 -0500 Subject: [PATCH 03/26] test: schema guard covers forwarded upstream schemas, every banned keyword, and nested types Review fixes for PR #146, final report issues 3, 7, 8 and 9. Issue 7: $ref, $defs and definitions join anyOf, oneOf, allOf and not as banned keywords. Array-valued type stays banned. Issue 8: one test per banned keyword (seven tests), plus a test that the banned set is exactly those seven. Deleting any entry fails its own test. Issue 9: the plain-type check is recursive. Every schema position (root, properties values, items in object or tuple form, additionalProperties schema) must carry one plain string type. The walk enters only schema positions. Data keywords (default, enum, const, examples) are not inspected, and a property named like a keyword is a name, not a keyword. A boolean additionalProperties is not a schema. Issue 3: UpstreamTool forwards each Playwright inputSchema unchanged, so the guard runs over eight browser_* descriptors written as fixtures in the shape the Playwright MCP server publishes. A fixture with anyOf is shown to be caught. The live upstream tools/list was not queried: no local Playwright server was contacted for this change. The first run failed one fixture that also lacked `type`, which the walker correctly reported. The fixture now carries `type: string`, and the rerun is clean. Commands (one run at the series head, macOS test host, copy of the worktree without .agents, .git, .build): swift test Suite touched: ToolSchemaShapeTests 19 passed, 0 failures. Full run: 751 executed, 0 failures, 5 skipped (same skips as the previous commit). --- .../ToolSchemaShapeTests.swift | 246 +++++++++++++++--- 1 file changed, 214 insertions(+), 32 deletions(-) diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index cf6a72f..1138b2e 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -3,66 +3,248 @@ import XCTest @testable import InstanceMCPCore /// Some MCP clients (Grok's connector, many function-calling validators) drop a tool whose -/// input schema uses composition keywords or a `type` array inside a property. ui_snapshot -/// and ui_action vanished from Grok's tool list that way. Every advertised property must -/// have one plain type. +/// input schema uses a union, a negation or a reference keyword, or a `type` array, at any +/// depth. ui_snapshot and ui_action vanished from Grok's tool list that way. Every schema +/// position must carry one plain `type` string. The guard runs over the local catalog, over +/// the upstream (Playwright) descriptors that UpstreamTool forwards unchanged, and over the +/// Linux daemon's list in tool_schema_shape_tests.rs. final class ToolSchemaShapeTests: XCTestCase { - static let banned: Set = ["anyOf", "oneOf", "allOf", "not"] + /// Keywords no guarded schema may use at a schema position. + static let banned: Set = ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"] - /// Paths of banned constructs in a schema. A key named like a banned keyword under - /// `properties` is a property name, not a keyword, so it is skipped. - static func violations(_ v: JSONValue, path: String, inPropertyMap: Bool = false) -> [String] { + /// Every schema node reachable from `schema` through a schema position: the node itself, + /// the values of `properties`, `items` (object or tuple form) and `additionalProperties`. + /// Data keywords (`default`, `enum`, `const`, `examples`) are never entered, so a payload + /// that happens to contain `anyOf` is not a finding. A property named `not` is a name, not + /// a keyword: only the values under `properties` are walked. + static func schemaNodes(_ schema: JSONValue, path: String) -> [(String, [String: JSONValue])] { + guard case .object(let node) = schema else { return [] } + var out: [(String, [String: JSONValue])] = [(path, node)] + for (name, sub) in (node["properties"]?.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) { + out += schemaNodes(sub, path: "\(path).properties.\(name)") + } + if let items = node["items"] { + if let tuple = items.arrayValue { + for (i, sub) in tuple.enumerated() { out += schemaNodes(sub, path: "\(path).items[\(i)]") } + } else { + out += schemaNodes(items, path: "\(path).items") + } + } + if let extra = node["additionalProperties"] { + out += schemaNodes(extra, path: "\(path).additionalProperties") + } + return out + } + + /// Findings for one guarded schema, by path: a banned keyword, a `type` array, or a schema + /// position without one plain `type` string. + static func problems(_ schema: JSONValue, root: String) -> [String] { var out: [String] = [] - switch v { - case .object(let o): - for (k, child) in o.sorted(by: { $0.key < $1.key }) { - if !inPropertyMap { - if banned.contains(k) { out.append("\(path).\(k)") } - if k == "type", child.arrayValue != nil { out.append("\(path).type is an array") } - } - out += violations(child, path: "\(path).\(k)", inPropertyMap: !inPropertyMap && k == "properties") + for (path, node) in schemaNodes(schema, path: root) { + for k in node.keys.sorted() where banned.contains(k) { out.append("\(path).\(k)") } + if node["type"]?.arrayValue != nil { + out.append("\(path).type is an array") + } else if node["type"]?.stringValue == nil { + out.append("\(path) has no single string type") } - case .array(let a): - for (i, child) in a.enumerated() { out += violations(child, path: "\(path)[\(i)]") } - default: break } return out } + /// A one-property object schema whose property `a` carries `keyword`. + private func fixture(_ keyword: String, _ value: JSONValue) -> JSONValue { + var a: [String: JSONValue] = ["type": .string("string")] + a[keyword] = value + return ["type": "object", "properties": ["a": .object(a)]] + } + func testNoLocalToolSchemaUsesCompositionOrTypeArrays() { let tools = ToolCatalog.local(agentVersion: "test") XCTAssertGreaterThan(tools.count, 10) for t in tools { XCTAssertEqual(t.inputSchema["type"]?.stringValue, "object", "\(t.name): top-level type") - let bad = Self.violations(t.inputSchema, path: t.name) - XCTAssertTrue(bad.isEmpty, "\(t.name) uses a construct some MCP clients reject: \(bad)") + XCTAssertEqual(Self.problems(t.inputSchema, root: t.name), [], "\(t.name) uses a construct some MCP clients reject") } } - func testEveryPropertyHasAPlainType() { - for t in ToolCatalog.local(agentVersion: "test") { - for (name, schema) in t.inputSchema["properties"]?.objectValue ?? [:] { - XCTAssertNotNil(schema["type"]?.stringValue, "\(t.name).\(name) has no single string type") - } + // Upstream (Playwright) descriptors. UpstreamTool forwards each inputSchema unchanged, so the + // same guard must hold for them. These fixtures are written in the shape the Playwright MCP + // server publishes; the live tools/list was not queried. + + private static func plain(_ type: String) -> JSONValue { ["type": .string(type)] } + + private static func oneOf(_ values: [String]) -> JSONValue { + ["type": "string", "enum": .array(values.map { .string($0) })] + } + + private static func descriptor(_ name: String, _ properties: [String: JSONValue], required: [String]) -> JSONValue { + [ + "name": .string(name), + "description": "fixture", + "inputSchema": [ + "type": "object", + "properties": .object(properties), + "required": .array(required.map { .string($0) }), + "additionalProperties": .bool(false), + ], + ] + } + + static let upstreamDescriptors: [JSONValue] = [ + descriptor("browser_navigate", ["url": plain("string")], required: ["url"]), + descriptor("browser_snapshot", [:], required: []), + descriptor("browser_click", [ + "element": plain("string"), + "ref": plain("string"), + "doubleClick": plain("boolean"), + "button": oneOf(["left", "right", "middle"]), + ], required: ["element", "ref"]), + descriptor("browser_type", [ + "element": plain("string"), + "ref": plain("string"), + "text": plain("string"), + "submit": plain("boolean"), + ], required: ["element", "ref", "text"]), + descriptor("browser_fill_form", [ + "fields": ["type": "array", "items": [ + "type": "object", + "properties": [ + "name": plain("string"), + "type": oneOf(["textbox", "checkbox", "radio", "combobox", "slider"]), + "ref": plain("string"), + "value": plain("string"), + ], + "required": ["name", "type", "ref", "value"], + "additionalProperties": .bool(false), + ]], + ], required: ["fields"]), + descriptor("browser_tabs", [ + "action": oneOf(["list", "new", "close", "select"]), + "index": ["type": "integer", "minimum": .number(0)], + ], required: ["action"]), + descriptor("browser_wait_for", [ + "time": plain("number"), + "text": plain("string"), + "textGone": plain("string"), + ], required: []), + descriptor("browser_file_upload", ["paths": ["type": "array", "items": plain("string")]], required: ["paths"]), + ] + + func testForwardedUpstreamSchemasObeyTheSameRules() { + let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) + XCTAssertEqual(Self.upstreamDescriptors.count, 8) + for d in Self.upstreamDescriptors { + let t = UpstreamTool(descriptorValue: d, upstream: upstream) + XCTAssertEqual(t.inputSchema["type"]?.stringValue, "object", "\(t.name): top-level type") + XCTAssertEqual(Self.problems(t.inputSchema, root: t.name), [], "\(t.name) uses a construct some MCP clients reject") } } - func testWalkerCatchesBannedConstructs() { - XCTAssertEqual(Self.violations(["properties": ["a": ["anyOf": [["type": "string"]]]]], path: "t"), - ["t.properties.a.anyOf"]) - XCTAssertEqual(Self.violations(["properties": ["a": ["type": ["string", "null"]]]], path: "t"), - ["t.properties.a.type is an array"]) - XCTAssertEqual(Self.violations(["properties": ["not": ["type": "string"]]], path: "t"), []) + func testForwardedUpstreamSchemaWithAUnionIsCaught() { + let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) + let d = Self.descriptor("browser_bad", ["x": ["type": "string", "anyOf": [["type": "string"], ["type": "null"]]]], required: []) + let t = UpstreamTool(descriptorValue: d, upstream: upstream) + XCTAssertEqual(Self.problems(t.inputSchema, root: t.name), ["browser_bad.properties.x.anyOf"]) } - // The runtime parsers keep the shapes the old schemas allowed. + // One test per banned keyword, so deleting an entry from `banned` fails its own test. + + func testBannedSetIsExactlyTheSevenKeywords() { + XCTAssertEqual(Self.banned, ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"]) + } + + func testBansAnyOf() { + XCTAssertEqual(Self.problems(fixture("anyOf", [["type": "string"]]), root: "t"), ["t.properties.a.anyOf"]) + } + + func testBansOneOf() { + XCTAssertEqual(Self.problems(fixture("oneOf", [["type": "string"]]), root: "t"), ["t.properties.a.oneOf"]) + } + + func testBansAllOf() { + XCTAssertEqual(Self.problems(fixture("allOf", [["type": "string"]]), root: "t"), ["t.properties.a.allOf"]) + } + + func testBansSchemaKeywordNot() { + XCTAssertEqual(Self.problems(fixture("not", ["type": "string"]), root: "t"), ["t.properties.a.not"]) + } + + func testBansRef() { + XCTAssertEqual(Self.problems(fixture("$ref", "#/$defs/x"), root: "t"), ["t.properties.a.$ref"]) + } + + func testBansDefs() { + XCTAssertEqual(Self.problems(fixture("$defs", ["x": ["type": "string"]]), root: "t"), ["t.properties.a.$defs"]) + } + + func testBansDefinitions() { + XCTAssertEqual(Self.problems(fixture("definitions", ["x": ["type": "string"]]), root: "t"), ["t.properties.a.definitions"]) + } + + func testBansArrayValuedType() { + let schema: JSONValue = ["type": "object", "properties": ["a": ["type": ["string", "null"]]]] + XCTAssertEqual(Self.problems(schema, root: "t"), ["t.properties.a.type is an array"]) + } + + // Plain-type check: recursive over every schema position, and nothing else. + + func testPlainTypeIsCheckedAtEveryDepth() { + let nested: JSONValue = ["type": "object", "properties": ["outer": ["type": "object", + "properties": ["inner": ["description": "no type here"]]]]] + XCTAssertEqual(Self.problems(nested, root: "t"), ["t.properties.outer.properties.inner has no single string type"]) + + let items: JSONValue = ["type": "object", "properties": ["list": ["type": "array", + "items": ["properties": ["x": ["type": "string"]]]]]] + XCTAssertEqual(Self.problems(items, root: "t"), ["t.properties.list.items has no single string type"]) + + let extra: JSONValue = ["type": "object", "properties": ["map": ["type": "object", + "additionalProperties": ["description": "no type"]]]] + XCTAssertEqual(Self.problems(extra, root: "t"), ["t.properties.map.additionalProperties has no single string type"]) + } + + func testBooleanAdditionalPropertiesIsNotASchema() { + let schema: JSONValue = ["type": "object", "properties": ["map": ["type": "object", "additionalProperties": .bool(false)]]] + XCTAssertEqual(Self.problems(schema, root: "t"), []) + } + + func testDataPayloadsAreNotInspected() { + // `default`, `enum` and `const` hold values, not schemas: keys that look like keywords there are fine. + let schema: JSONValue = ["type": "object", "properties": ["a": [ + "type": "object", + "default": ["anyOf": [["type": "string"]]], + "const": ["oneOf": 1], + ]]] + XCTAssertEqual(Self.problems(schema, root: "t"), []) + } + + func testPropertyNamedLikeAKeywordIsAName() { + let schema: JSONValue = ["type": "object", "properties": ["not": ["type": "string"], "anyOf": ["type": "string"]]] + XCTAssertEqual(Self.problems(schema, root: "t"), []) + } + + // The runtime parsers keep the shapes the old schemas allowed, and the new integer field. + func testSnapshotWindowAcceptsTitleAndIndex() throws { XCTAssertEqual(try UISnapshotTool.parse(["window": "Untitled"]).window, .title("Untitled")) + XCTAssertEqual(try UISnapshotTool.parse(["window": "2026"]).window, .title("2026")) XCTAssertEqual(try UISnapshotTool.parse(["window": 2]).window, .index(2)) XCTAssertEqual(try UISnapshotTool.parse(["window": 0]).window, .index(0)) XCTAssertThrowsError(try UISnapshotTool.parse(["window": -1])) } + func testSnapshotWindowIndexIsAFlatInteger() throws { + let props = UISnapshotTool().inputSchema["properties"] + XCTAssertEqual(props?["window_index"]?["type"]?.stringValue, "integer") + XCTAssertEqual(props?["window"]?["type"]?.stringValue, "string") + XCTAssertEqual(try UISnapshotTool.parse(["window_index": 1]).window, .index(1)) + XCTAssertEqual(try UISnapshotTool.parse(["window_index": 0]).window, .index(0)) + XCTAssertThrowsError(try UISnapshotTool.parse(["window_index": "1"])) + XCTAssertThrowsError(try UISnapshotTool.parse(["window_index": -1])) + XCTAssertThrowsError(try UISnapshotTool.parse(["window": "Untitled", "window_index": 0])) + XCTAssertThrowsError(try UISnapshotTool.parse(["window": 2, "window_index": 0])) + XCTAssertThrowsError(try UISnapshotTool.parse(["window_index": 0, "all_windows": true])) + } + func testActionValueAcceptsStringNumberAndBool() throws { func value(_ v: JSONValue) throws -> UIAttrValue? { try UIActionTool.parse(["snapshot_id": "s", "ref": "e1", "action": "set_value", "value": v]).value From 54d6db1e09f61f6c920415018de8a8ea7e453308 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:48:35 -0500 Subject: [PATCH 04/26] test(rust): schema guard over the Linux daemon's tool lists Review fix for PR #146, final report issue 4. Adds tool_schema_shape_tests.rs, which applies the same rules as the Swift ToolSchemaShapeTests to every tool list the daemon builds: - tool_list_with for the owner and observe profiles (local tools and job tools, no upstreams), and jobs::tools::tool_specs on its own. - The banned keywords (one test per keyword), array-valued type, a plain string type at every schema position, boolean additionalProperties, data payloads, and property names that look like keywords. Upstream schemas are not in these lists; the Swift test covers them. The live upstream tools/list was not queried. Commands (one run at the series head, arm64 Linux test host, copy of the whole worktree without .agents, .git, .build, target, because the crate include_str!s conformance/ and release/ from the repo root): cargo test (from poc/reverse-attach-linux, toolchain 1.96.0). Result: 384 passed, 1 failed, 10 ignored. The 16 new tests in tool_schema_shape_tests all pass. Failure: proc::tests:: a_pid_that_does_not_exist_signals_nothing_and_does_not_panic, which hits a rustix debug assertion on kill_pid_checked(u32::MAX). It fails identically at a95874be (the base of this PR), and this change does not touch proc.rs. --- poc/reverse-attach-linux/src/main.rs | 2 + .../src/tool_schema_shape_tests.rs | 183 ++++++++++++++++++ 2 files changed, 185 insertions(+) create mode 100644 poc/reverse-attach-linux/src/tool_schema_shape_tests.rs diff --git a/poc/reverse-attach-linux/src/main.rs b/poc/reverse-attach-linux/src/main.rs index f4aefeb..77b9796 100644 --- a/poc/reverse-attach-linux/src/main.rs +++ b/poc/reverse-attach-linux/src/main.rs @@ -53,6 +53,8 @@ mod tools; mod unit; #[cfg(test)] mod wire_conformance; +#[cfg(test)] +mod tool_schema_shape_tests; /// Install rustls's ring provider as the process default, once. tungstenite builds /// its rustls `ClientConfig` from the process default; with no provider a wss:// diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs new file mode 100644 index 0000000..dfa6340 --- /dev/null +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -0,0 +1,183 @@ +//! Schema shape guard for the tool lists this daemon serves: `tool_list_with` (the local +//! tools and the job tools, for the owner and observe profiles) and `jobs::tools::tool_specs` +//! on their own. The rules match the Swift `ToolSchemaShapeTests`: no union, negation or +//! reference keyword, and no `type` array, at any schema position, and every schema position +//! carries one plain `type` string. Upstream (Playwright) schemas are forwarded unchanged and +//! are not in these lists; the Swift test covers them with fixtures. The live upstream +//! tools/list was not queried. + +use serde_json::{json, Value}; + +use crate::mcp::tool_list_with; + +/// Keywords no guarded schema may use at a schema position. +const BANNED: &[&str] = &["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"]; + +/// Schema positions under `schema`, as (path, node): the node itself, the values of +/// `properties`, `items` (object or tuple form) and `additionalProperties`. Data keywords +/// (`default`, `enum`, `const`, `examples`) are never entered, and a property named like a +/// keyword is a name, not a keyword. +fn schema_nodes<'a>(schema: &'a Value, path: String, out: &mut Vec<(String, &'a Value)>) { + if !schema.is_object() { + return; + } + out.push((path.clone(), schema)); + if let Some(props) = schema.get("properties").and_then(Value::as_object) { + for (name, sub) in props { + schema_nodes(sub, format!("{path}.properties.{name}"), out); + } + } + match schema.get("items") { + Some(Value::Array(tuple)) => { + for (i, sub) in tuple.iter().enumerate() { + schema_nodes(sub, format!("{path}.items[{i}]"), out); + } + } + Some(items) => schema_nodes(items, format!("{path}.items"), out), + None => {} + } + if let Some(extra) = schema.get("additionalProperties") { + schema_nodes(extra, format!("{path}.additionalProperties"), out); + } +} + +/// Findings for one guarded schema, by path. An empty result means the schema passes. +fn problems(schema: &Value, root: &str) -> Vec { + if !schema.is_object() { + return vec![format!("{root} is not an object schema")]; + } + let mut nodes = Vec::new(); + schema_nodes(schema, root.to_string(), &mut nodes); + let mut out = Vec::new(); + for (path, node) in nodes { + for keyword in BANNED { + if node.get(*keyword).is_some() { + out.push(format!("{path}.{keyword}")); + } + } + match node.get("type") { + Some(Value::String(_)) => {} + Some(Value::Array(_)) => out.push(format!("{path}.type is an array")), + _ => out.push(format!("{path} has no single string type")), + } + } + out +} + +/// A schema `{type: object, properties: {a: {type: string, : value}}}`. +fn with_property_keyword(keyword: &str, value: Value) -> Value { + let mut a = json!({ "type": "string" }); + a.as_object_mut().unwrap().insert(keyword.to_string(), value); + json!({ "type": "object", "properties": { "a": a } }) +} + +fn assert_tool_passes(tool: &Value, context: &str) { + let name = tool["name"].as_str().unwrap_or("?"); + assert_eq!(tool["inputSchema"]["type"], "object", "{context}/{name}: top-level type"); + assert_eq!(problems(&tool["inputSchema"], name), Vec::::new(), "{context}/{name}"); +} + +#[test] +fn banned_set_is_exactly_the_seven_keywords() { + assert_eq!(BANNED, ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"]); +} + +// One test per banned keyword, so dropping an entry from BANNED fails its own test. +macro_rules! bans { + ($($test:ident => $keyword:literal),* $(,)?) => { + $( + #[test] + fn $test() { + let schema = with_property_keyword($keyword, json!("x")); + assert_eq!(problems(&schema, "t"), vec![format!("t.properties.a.{}", $keyword)]); + } + )* + }; +} + +bans! { + bans_any_of => "anyOf", + bans_one_of => "oneOf", + bans_all_of => "allOf", + bans_schema_not => "not", + bans_ref => "$ref", + bans_defs => "$defs", + bans_definitions => "definitions", +} + +#[test] +fn bans_array_valued_type() { + let schema = json!({ "type": "object", "properties": { "a": { "type": ["string", "null"] } } }); + assert_eq!(problems(&schema, "t"), vec!["t.properties.a.type is an array".to_string()]); +} + +#[test] +fn plain_type_is_checked_at_every_depth() { + let nested = json!({ "type": "object", "properties": { "outer": { "type": "object", + "properties": { "inner": { "description": "no type" } } } } }); + assert_eq!(problems(&nested, "t"), vec!["t.properties.outer.properties.inner has no single string type".to_string()]); + + let items = json!({ "type": "object", "properties": { "list": { "type": "array", + "items": { "properties": { "x": { "type": "string" } } } } } }); + assert_eq!(problems(&items, "t"), vec!["t.properties.list.items has no single string type".to_string()]); + + let extra = json!({ "type": "object", "properties": { "map": { "type": "object", + "additionalProperties": { "description": "no type" } } } }); + assert_eq!(problems(&extra, "t"), vec!["t.properties.map.additionalProperties has no single string type".to_string()]); +} + +#[test] +fn boolean_additional_properties_is_not_a_schema() { + let schema = json!({ "type": "object", "properties": { "map": { "type": "object", "additionalProperties": false } } }); + assert_eq!(problems(&schema, "t"), Vec::::new()); +} + +#[test] +fn data_payloads_are_not_inspected() { + let schema = json!({ "type": "object", "properties": { "a": { + "type": "object", + "default": { "anyOf": [{ "type": "string" }] }, + "const": { "oneOf": 1 } + } } }); + assert_eq!(problems(&schema, "t"), Vec::::new()); +} + +#[test] +fn property_named_like_a_keyword_is_a_name() { + let schema = json!({ "type": "object", "properties": { "not": { "type": "string" }, "anyOf": { "type": "string" } } }); + assert_eq!(problems(&schema, "t"), Vec::::new()); +} + +#[test] +fn root_must_be_an_object_schema() { + assert_eq!(problems(&json!("x"), "t"), vec!["t is not an object schema".to_string()]); +} + +#[test] +fn local_tool_lists_obey_the_schema_rules() { + // owner gets every local and job tool; observe is the read-only subset. Both lists are + // built with no upstreams, so only this daemon's own schemas are checked. + let owner = tool_list_with("owner", &[]); + let owner = owner.as_array().expect("tools/list is an array"); + let names: Vec<&str> = owner.iter().filter_map(|t| t["name"].as_str()).collect(); + assert!(names.contains(&"screenshot") && names.contains(&"exec_start"), "owner list: {names:?}"); + for tool in owner { + assert_tool_passes(tool, "owner"); + } + + let observe = tool_list_with("observe", &[]); + let observe = observe.as_array().expect("tools/list is an array"); + assert!(!observe.is_empty(), "observe list is empty"); + for tool in observe { + assert_tool_passes(tool, "observe"); + } +} + +#[test] +fn job_tool_specs_obey_the_schema_rules() { + let specs = crate::jobs::tools::tool_specs(); + assert_eq!(specs.len(), 4, "exec_start, exec_poll, exec_list, exec_cancel"); + for tool in &specs { + assert_tool_passes(tool, "jobs"); + } +} From 97f7a9e496de86889c98b5805e272b5fec0890ea Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:56:36 -0500 Subject: [PATCH 05/26] fix: make ui_snapshot window title-only in the schema, drop window_index Review fix for PR #146, final report issue 2 (gate finding: window index choice). Choice: document a title-only contract instead of adding a window_index integer. Reason: it is the smaller change under the brief. It adds no parameter, no mutual-exclusion rule and no error path, and the schema stays a single string. Native JSON integers in `window` still select an index for existing callers, so nothing that worked before is removed. Cost, stated in docs/ui-tools.md: strict clients cannot pick an untitled or duplicate-title window by index. They must use the title. The ui_snapshot tool description, the window property and the window error text name only the title. The parse-site comment (#145) is unchanged. Commands (one run at the series head, macOS test host, scratch copy of the worktree without .agents, .git, .build): swift test Result: 751 executed, 5 skipped, 0 failures (full run; the default output prints no per-suite counts). ToolSchemaShapeTests includes testSnapshotWindowSchemaIsTitleOnly, which replaces the window_index test. --- Sources/InstanceMCPCore/Tools/UISnapshotTool.swift | 11 ++--------- .../InstanceMCPCoreTests/ToolSchemaShapeTests.swift | 13 ++++--------- Tests/InstanceMCPCoreTests/UISnapshotTests.swift | 2 +- docs/ui-tools.md | 5 +++-- 4 files changed, 10 insertions(+), 21 deletions(-) diff --git a/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift b/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift index 5d28fd7..818f4f2 100644 --- a/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift +++ b/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift @@ -8,7 +8,7 @@ public struct UISnapshotTool: Tool { public let description = """ Read the accessibility tree of a native macOS app window (read-only): roles, titles, values, \ state and frames. Default target: the frontmost app's focused window; pass `app` (bundle id or \ - name) or `pid`, and `window` (a title) or `window_index` (an index), or `all_windows`. Frames are display POINTS relative \ + name) or `pid`, and `window` (a title) or `all_windows`. Frames are display POINTS relative \ to `display`, the same space `screenshot` and `mouse` use. Each node has a `ref` valid only within \ this `snapshot_id`; `ui_action` acts on a node by `{snapshot_id, ref}` (the last 4 snapshots stay \ usable for 5 minutes). Pass `include_menu_bar` to also walk the app's menu bar. Secure text fields \ @@ -22,8 +22,6 @@ public struct UISnapshotTool: Tool { "pid": ["type": "integer", "description": "Process id. Use instead of app when several apps match."], "window": ["type": "string", "description": "Window title: exact match, else case-insensitive substring. A string is always read as a title, even when it looks like a number. Default: focused window."], - "window_index": ["type": "integer", "minimum": .number(0), - "description": "Index in the app's window list, starting at 0. Use it for an untitled window or when titles repeat. Do not send with window."], "all_windows": ["type": "boolean", "description": "Walk every window of the app.", "default": false], "include_menu_bar": ["type": "boolean", "description": "Also walk the app's menu bar, after the windows (it shares max_nodes), so menu items get refs for ui_action.", "default": false], "max_depth": ["type": "integer", "description": "Levels below the window.", @@ -133,14 +131,9 @@ public struct UISnapshotTool: Tool { } else if let s = v.stringValue, !s.isEmpty { r.window = .title(s) } else { - throw JSONRPCError.invalidParams("window must be a non-empty title, or use window_index for an index ≥ 0") + throw JSONRPCError.invalidParams("window must be a non-empty title") } } - if let v = a["window_index"], !v.isNull { - guard let i = v.intValue, i >= 0 else { throw JSONRPCError.invalidParams("window_index must be an integer ≥ 0") } - guard r.window == nil else { throw JSONRPCError.invalidParams("pass window or window_index, not both") } - r.window = .index(i) - } if let v = a["all_windows"], !v.isNull { guard let b = v.boolValue else { throw JSONRPCError.invalidParams("all_windows must be a boolean") } r.allWindows = b diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 1138b2e..2fc81ee 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -232,17 +232,12 @@ final class ToolSchemaShapeTests: XCTestCase { XCTAssertThrowsError(try UISnapshotTool.parse(["window": -1])) } - func testSnapshotWindowIndexIsAFlatInteger() throws { + func testSnapshotWindowSchemaIsTitleOnly() throws { let props = UISnapshotTool().inputSchema["properties"] - XCTAssertEqual(props?["window_index"]?["type"]?.stringValue, "integer") XCTAssertEqual(props?["window"]?["type"]?.stringValue, "string") - XCTAssertEqual(try UISnapshotTool.parse(["window_index": 1]).window, .index(1)) - XCTAssertEqual(try UISnapshotTool.parse(["window_index": 0]).window, .index(0)) - XCTAssertThrowsError(try UISnapshotTool.parse(["window_index": "1"])) - XCTAssertThrowsError(try UISnapshotTool.parse(["window_index": -1])) - XCTAssertThrowsError(try UISnapshotTool.parse(["window": "Untitled", "window_index": 0])) - XCTAssertThrowsError(try UISnapshotTool.parse(["window": 2, "window_index": 0])) - XCTAssertThrowsError(try UISnapshotTool.parse(["window_index": 0, "all_windows": true])) + XCTAssertNil(props?["window_index"], "index selection is not advertised: strict clients send a title") + XCTAssertEqual(try UISnapshotTool.parse(["window": 1]).window, .index(1), "a native integer still selects an index for existing callers") + XCTAssertEqual(try UISnapshotTool.parse(["window": "1"]).window, .title("1")) } func testActionValueAcceptsStringNumberAndBool() throws { diff --git a/Tests/InstanceMCPCoreTests/UISnapshotTests.swift b/Tests/InstanceMCPCoreTests/UISnapshotTests.swift index dc62a4b..ef5629e 100644 --- a/Tests/InstanceMCPCoreTests/UISnapshotTests.swift +++ b/Tests/InstanceMCPCoreTests/UISnapshotTests.swift @@ -882,7 +882,7 @@ final class UISnapshotToolTests: XCTestCase { let cases: [(JSONValue, String)] = [(["app": "TextEdit", "pid": 20], "pass app or pid, not both"), (["window": "x", "all_windows": true], "pass window or all_windows, not both"), (["max_nodes": 1.5], "max_nodes must be an integer"), - (["window": -1], "window must be a non-empty title, or use window_index for an index ≥ 0"), + (["window": -1], "window must be a non-empty title"), (["app": ""], "app must be a non-empty string")] for (args, why) in cases { let r = await call(args) diff --git a/docs/ui-tools.md b/docs/ui-tools.md index 0ef7ffe..3682262 100644 --- a/docs/ui-tools.md +++ b/docs/ui-tools.md @@ -9,8 +9,9 @@ has the summary. Both tools are macOS only; the Linux AT-SPI port is deferred Accessibility tree of a native app's window (AXUIElement), read-only. `owner` only. - **Target.** Default: the frontmost app's focused window. `app` (bundle id or name) or `pid` - selects an app; `window` (a title string) or `window_index` (an integer index, for an untitled or - duplicate-title window; `window` also still takes a native JSON integer for existing callers) or `all_windows` selects windows. + selects an app; `window` (a title string) or `all_windows` selects windows. Strict clients can only send a + title, so they cannot pick an untitled or duplicate-title window by index. A native JSON integer in `window` still + selects an index for existing callers (#145). `include_menu_bar` also walks the app's menu bar, so menu items get refs. - **Per node.** Role, subrole, title, value (secure fields always masked), state, frame in display points (the `screenshot`/`mouse` space, with display index), and a `ref` valid within From e1a0fa0a76e933eed2a4ff0972eaec04cac8567d Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:56:39 -0500 Subject: [PATCH 06/26] fix: value-type refusal names the mismatch, no native-number advice Review fix for PR #146, final report issues 1 and 6 (gate finding: the value-type error asks for a native number). UIActionTool.Errors.valueTypeRejected, for a string with no number or boolean form, no longer tells the model to send a JSON number or boolean. Strict clients cannot send one, so that advice named a form the schema forbids. The message now names the type mismatch (AX error -25201) and the next step: take a new ui_snapshot to check the control's value type, then send a value of that type. The retry path message is unchanged. UIActionTests asserts the exact no-native-form text and that it does not mention JSON. The compatibility comment at the value parse site (#145) is unchanged. Commands (one run at the series head, macOS test host, scratch copy of the worktree without .agents, .git, .build): swift test Result: 751 executed, 5 skipped, 0 failures (full run; the default output prints no per-suite counts). --- Sources/InstanceMCPCore/Tools/UIActionTool.swift | 2 +- Tests/InstanceMCPCoreTests/UIActionTests.swift | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/InstanceMCPCore/Tools/UIActionTool.swift b/Sources/InstanceMCPCore/Tools/UIActionTool.swift index c0758a1..9267d5e 100644 --- a/Sources/InstanceMCPCore/Tools/UIActionTool.swift +++ b/Sources/InstanceMCPCore/Tools/UIActionTool.swift @@ -78,7 +78,7 @@ public struct UIActionTool: Tool { if retried { return "\(ref) (\(role)) rejected the value as text and as a number or boolean (AX error -25201). Take a new ui_snapshot to check the control's current value type" } - return "\(ref) (\(role)) rejected the value's type (AX error -25201). A numeric or boolean control takes a native JSON number or boolean (for example 3 or true), not a string; a text control takes a string" + return "\(ref) (\(role)) rejected the value's type (AX error -25201). The value has no number or boolean form, so it does not fit this control. Take a new ui_snapshot to check the control's value type, then send a value of that type" } public static func unconfirmed(action: String, ref: String, app: String) -> String { "ui_action \(action) [\(ref)]: \(app) did not confirm in time. The action may have happened (a press that opens a dialog or menu often answers late); take a new ui_snapshot to check, and do not repeat it blindly" diff --git a/Tests/InstanceMCPCoreTests/UIActionTests.swift b/Tests/InstanceMCPCoreTests/UIActionTests.swift index 128eee1..b50a460 100644 --- a/Tests/InstanceMCPCoreTests/UIActionTests.swift +++ b/Tests/InstanceMCPCoreTests/UIActionTests.swift @@ -361,6 +361,8 @@ final class UIActionToolTests: XCTestCase { let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "hello"]) XCTAssertTrue(r.isToolError) XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: false)) + XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the value's type (AX error -25201). The value has no number or boolean form, so it does not fit this control. Take a new ui_snapshot to check the control's value type, then send a value of that type") + XCTAssertFalse(r.text.contains("JSON"), r.text) XCTAssertFalse(r.text.contains("does not support"), r.text) XCTAssertFalse(r.text.contains("Supported on it"), r.text) assertNothingDone(f) From 07647ad35038d49e44989626de173a7810d2e4b2 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:49:30 -0500 Subject: [PATCH 07/26] fix: forward browser_emulate_media overrides as plain enums; pin upstream tools Review fix for PR #146, final report issue 3 (gate finding: upstream Playwright schemas are hand-written). Owner chose option B. Recorded evidence: the pinned @playwright/mcp 0.0.82 tools/list, taken from a fresh stdio process with the app's flags (--browser chromium --shared-browser-context --caps vision,pdf --headless). It lists 32 tools. The running service on the browser port was not queried. The recording is Tests/Fixtures/playwright-mcp-0.0.82-tools-list.json. Finding: browser_emulate_media uses anyOf [enum string, {type: null}] in five properties (colorScheme, reducedMotion, forcedColors, contrast, media). The other 31 tools were clean. Change: UpstreamTool.forwardedSchema keeps only the string branch for those five properties and drops the null branch. Clients can no longer send null to clear those overrides; omitting a field still leaves it unchanged. Every other upstream schema is forwarded unchanged. Tests: testRecordedPlaywrightToolsAreAllPlainAfterForwarding (32 tools pass the guard), testEmulateMediaOverridesAreForwardedAsPlainEnums (pins the five enums and descriptions), testOtherRecordedPlaywrightToolsAreForwardedUnchanged. Commands (one run at the series head, macOS test host, scratch copy of the worktree without .agents, .git, .build): swift test Result: 754 executed, 5 skipped, 0 failures (full run; previously 751, plus the three new tests). Rust is not touched by this commit; the Rust results are in the PR notes. --- Sources/InstanceMCPCore/UpstreamMCP.swift | 21 +- .../playwright-mcp-0.0.82-tools-list.json | 1135 +++++++++++++++++ .../ToolSchemaShapeTests.swift | 52 +- 3 files changed, 1204 insertions(+), 4 deletions(-) create mode 100644 Tests/Fixtures/playwright-mcp-0.0.82-tools-list.json diff --git a/Sources/InstanceMCPCore/UpstreamMCP.swift b/Sources/InstanceMCPCore/UpstreamMCP.swift index 1bc70f9..8d3e7b8 100644 --- a/Sources/InstanceMCPCore/UpstreamMCP.swift +++ b/Sources/InstanceMCPCore/UpstreamMCP.swift @@ -155,9 +155,28 @@ struct UpstreamTool: Tool { var name: String { descriptorValue["name"]?.stringValue ?? "?" } var description: String { descriptorValue["description"]?.stringValue ?? "" } - var inputSchema: JSONValue { descriptorValue["inputSchema"] ?? ["type": "object"] } + var inputSchema: JSONValue { Self.forwardedSchema(name: name, descriptorValue["inputSchema"] ?? ["type": "object"]) } var descriptor: JSONValue { descriptorValue } + /// browser_emulate_media's five overrides are `anyOf: [enum string, null]`, a union that strict + /// MCP clients drop (#145). Only that branch is kept: each property becomes its plain enum + /// string. Owner decision on PR #146 (option B): clients can no longer send null to clear + /// these overrides. Every other upstream schema is forwarded unchanged. + static func forwardedSchema(name: String, _ schema: JSONValue) -> JSONValue { + guard name == "browser_emulate_media", var root = schema.objectValue, + var props = root["properties"]?.objectValue else { return schema } + for (key, prop) in props { + guard var p = prop.objectValue, let branches = p["anyOf"]?.arrayValue, + let string = branches.first(where: { $0["type"]?.stringValue == "string" })?.objectValue + else { continue } + p.removeValue(forKey: "anyOf") + for (k, v) in string { p[k] = v } + props[key] = .object(p) + } + root["properties"] = .object(props) + return .object(root) + } + func call(arguments: JSONValue) async throws -> ToolResult { let r = try await upstream.call(name, arguments: arguments) // Pass the upstream's result through verbatim: content blocks, isError, diff --git a/Tests/Fixtures/playwright-mcp-0.0.82-tools-list.json b/Tests/Fixtures/playwright-mcp-0.0.82-tools-list.json new file mode 100644 index 0000000..d4fb5b3 --- /dev/null +++ b/Tests/Fixtures/playwright-mcp-0.0.82-tools-list.json @@ -0,0 +1,1135 @@ +{ + "source": "@playwright/mcp@0.0.82 stdio tools/list, flags as ManagedPlaywright (--browser chromium --shared-browser-context --caps vision,pdf --headless); a fresh process, not the running service", + "result": { + "tools": [ + { + "name": "browser_close", + "description": "Close the page", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": {}, + "additionalProperties": false + }, + "annotations": { + "title": "Close browser", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_resize", + "description": "Resize the browser window", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "width": { + "type": "number", + "description": "Width of the browser window" + }, + "height": { + "type": "number", + "description": "Height of the browser window" + } + }, + "required": [ + "width", + "height" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Resize browser window", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_console_messages", + "description": "Returns all console messages", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "level": { + "default": "info", + "description": "Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to \"info\".", + "type": "string", + "enum": [ + "error", + "warning", + "info", + "debug" + ] + }, + "all": { + "description": "Return all console messages since the beginning of the session, not just since the last navigation. Defaults to false.", + "type": "boolean" + }, + "filename": { + "description": "File name to save the console messages to. Relative file names are resolved against the workspace root. If not provided, messages are returned as text.", + "type": "string" + } + }, + "required": [ + "level" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Get console messages", + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": true + } + }, + { + "name": "browser_handle_dialog", + "description": "Handle a dialog", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "accept": { + "type": "boolean", + "description": "Whether to accept the dialog." + }, + "promptText": { + "description": "The text of the prompt in case of a prompt dialog.", + "type": "string" + } + }, + "required": [ + "accept" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Handle a dialog", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_emulate_media", + "description": "Emulate CSS media features for the page, for example switch between the light and dark color scheme. Omitted parameters are left unchanged; null clears an override.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "colorScheme": { + "description": "Emulates the prefers-color-scheme media feature", + "anyOf": [ + { + "type": "string", + "enum": [ + "light", + "dark" + ] + }, + { + "type": "null" + } + ] + }, + "reducedMotion": { + "description": "Emulates the prefers-reduced-motion media feature", + "anyOf": [ + { + "type": "string", + "enum": [ + "reduce", + "no-preference" + ] + }, + { + "type": "null" + } + ] + }, + "forcedColors": { + "description": "Emulates the forced-colors media feature", + "anyOf": [ + { + "type": "string", + "enum": [ + "active", + "none" + ] + }, + { + "type": "null" + } + ] + }, + "contrast": { + "description": "Emulates the prefers-contrast media feature", + "anyOf": [ + { + "type": "string", + "enum": [ + "more", + "no-preference" + ] + }, + { + "type": "null" + } + ] + }, + "media": { + "description": "Changes the CSS media type of the page", + "anyOf": [ + { + "type": "string", + "enum": [ + "screen", + "print" + ] + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Emulate media features", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_evaluate", + "description": "Evaluate JavaScript expression on page or element", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "element": { + "description": "Human-readable element description used to obtain permission to interact with the element", + "type": "string" + }, + "target": { + "description": "Exact target element reference from the page snapshot, or a unique element selector", + "type": "string" + }, + "function": { + "type": "string", + "description": "() => { /* code */ } or (element) => { /* code */ } when element is provided" + }, + "filename": { + "description": "File name to save the result to. Relative file names are resolved against the workspace root. If not provided, result is returned as text.", + "type": "string" + } + }, + "required": [ + "function" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Evaluate JavaScript", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_file_upload", + "description": "Upload one or multiple files", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "paths": { + "description": "The absolute paths to the files to upload. Can be single file or multiple files. If omitted, file chooser is cancelled.", + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Upload files", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_drop", + "description": "Drop files or MIME-typed data onto an element, as if dragged from outside the page. At least one of \"paths\" or \"data\" must be provided.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "element": { + "description": "Human-readable element description used to obtain permission to interact with the element", + "type": "string" + }, + "target": { + "type": "string", + "description": "Exact target element reference from the page snapshot, or a unique element selector" + }, + "paths": { + "description": "Absolute paths to files to drop onto the element.", + "type": "array", + "items": { + "type": "string" + } + }, + "data": { + "description": "Data to drop, as a map of MIME type to string value (e.g. {\"text/plain\": \"hello\", \"text/uri-list\": \"https://example.com\"}).", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "target" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Drop files or data onto an element", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_find", + "description": "Search the accessibility snapshot of the current page for text or a regular expression. Returns matching snapshot nodes with a few lines of surrounding context (like search snippets), each shown under its path from the root of the tree, which is cheaper than capturing the whole snapshot when you only need to locate an element and its ref.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "text": { + "description": "Plain text to search for in the page snapshot (case-insensitive substring match). Provide either text or regex, not both.", + "type": "string" + }, + "regex": { + "description": "Regular expression to search for in the page snapshot. Matching is case-sensitive by default; wrap the pattern in slashes to add flags, e.g. \"/error/i\" for case-insensitive. Provide either text or regex, not both.", + "type": "string" + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Find in page snapshot", + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": true + } + }, + { + "name": "browser_fill_form", + "description": "Fill multiple form fields", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "fields": { + "type": "array", + "items": { + "type": "object", + "properties": { + "element": { + "description": "Human-readable element description used to obtain permission to interact with the element", + "type": "string" + }, + "target": { + "type": "string", + "description": "Exact target element reference from the page snapshot, or a unique element selector" + }, + "name": { + "type": "string", + "description": "Human-readable field name" + }, + "type": { + "type": "string", + "enum": [ + "textbox", + "checkbox", + "radio", + "combobox", + "slider" + ], + "description": "Type of the field" + }, + "value": { + "type": "string", + "description": "Value to fill in the field. If the field is a checkbox, the value should be `true` or `false`. If the field is a combobox, the value should be the text of the option." + } + }, + "required": [ + "target", + "name", + "type", + "value" + ], + "additionalProperties": false + }, + "description": "Fields to fill in" + } + }, + "required": [ + "fields" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Fill form", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_press_key", + "description": "Press a key on the keyboard", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "Name of the key to press or a character to generate, such as `ArrowLeft` or `a`" + } + }, + "required": [ + "key" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Press a key", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_type", + "description": "Type text into editable element", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "element": { + "description": "Human-readable element description used to obtain permission to interact with the element", + "type": "string" + }, + "target": { + "type": "string", + "description": "Exact target element reference from the page snapshot, or a unique element selector" + }, + "text": { + "type": "string", + "description": "Text to type into the element" + }, + "submit": { + "description": "Whether to submit entered text (press Enter after)", + "type": "boolean" + }, + "slowly": { + "description": "Whether to type one character at a time. Useful for triggering key handlers in the page. By default entire text is filled in at once.", + "type": "boolean" + } + }, + "required": [ + "target", + "text" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Type text", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_mouse_move_xy", + "description": "Move mouse to a given position", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "x": { + "type": "number", + "description": "X coordinate" + }, + "y": { + "type": "number", + "description": "Y coordinate" + } + }, + "required": [ + "x", + "y" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Move mouse", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_mouse_click_xy", + "description": "Click mouse button at a given position", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "x": { + "type": "number", + "description": "X coordinate" + }, + "y": { + "type": "number", + "description": "Y coordinate" + }, + "button": { + "description": "Button to click, defaults to left", + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "clickCount": { + "description": "Number of clicks, defaults to 1", + "type": "number" + }, + "delay": { + "description": "Time to wait between mouse down and mouse up in milliseconds, defaults to 0", + "type": "number" + } + }, + "required": [ + "x", + "y" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Click", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_mouse_drag_xy", + "description": "Drag left mouse button to a given position", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "startX": { + "type": "number", + "description": "Start X coordinate" + }, + "startY": { + "type": "number", + "description": "Start Y coordinate" + }, + "endX": { + "type": "number", + "description": "End X coordinate" + }, + "endY": { + "type": "number", + "description": "End Y coordinate" + } + }, + "required": [ + "startX", + "startY", + "endX", + "endY" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Drag mouse", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_mouse_down", + "description": "Press mouse down", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "button": { + "description": "Button to press, defaults to left", + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Press mouse down", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_mouse_up", + "description": "Press mouse up", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "button": { + "description": "Button to press, defaults to left", + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Press mouse up", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_mouse_wheel", + "description": "Scroll mouse wheel", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "deltaX": { + "default": 0, + "description": "X delta", + "type": "number" + }, + "deltaY": { + "default": 0, + "description": "Y delta", + "type": "number" + } + }, + "required": [ + "deltaX", + "deltaY" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Scroll mouse wheel", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_navigate", + "description": "Navigate to a URL", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The URL to navigate to" + } + }, + "required": [ + "url" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Navigate to a URL", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_navigate_back", + "description": "Go back to the previous page in the history", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": {}, + "additionalProperties": false + }, + "annotations": { + "title": "Go back", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_network_requests", + "description": "Returns a numbered list of network requests since loading the page. Use browser_network_request with the number to get full details.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "static": { + "default": false, + "description": "Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.", + "type": "boolean" + }, + "filter": { + "description": "Only return requests whose URL matches this regexp (e.g. \"/api/.*user\").", + "type": "string" + }, + "filename": { + "description": "File name to save the network requests to. Relative file names are resolved against the workspace root. If not provided, requests are returned as text.", + "type": "string" + } + }, + "required": [ + "static" + ], + "additionalProperties": false + }, + "annotations": { + "title": "List network requests", + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": true + } + }, + { + "name": "browser_network_request", + "description": "Returns full details (headers and body) of a single network request, or a single part if `part` is set. Use the number from browser_network_requests.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "index": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "1-based index of the request, as printed by browser_network_requests." + }, + "part": { + "description": "Return only this part of the request. Omit to return full details.", + "type": "string", + "enum": [ + "request-headers", + "request-body", + "response-headers", + "response-body" + ] + }, + "filename": { + "description": "File name to save the result to. Relative file names are resolved against the workspace root. If not provided, output is returned as text.", + "type": "string" + } + }, + "required": [ + "index" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Show network request details", + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": true + } + }, + { + "name": "browser_pdf_save", + "description": "Save page as PDF", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "filename": { + "description": "File name to save the pdf to. Relative file names are resolved against the workspace root. If not specified, the pdf is saved into the output directory as `page-{timestamp}.pdf`.", + "type": "string" + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Save as PDF", + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": true + } + }, + { + "name": "browser_run_code_unsafe", + "description": "Run a Playwright code snippet. Unsafe: executes arbitrary JavaScript in the Playwright server process and is RCE-equivalent.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "description": "A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction. For example: `async (page) => { await page.getByRole('button', { name: 'Submit' }).click(); return await page.title(); }`", + "type": "string" + }, + "filename": { + "description": "Load code from the specified file. Relative file names are resolved against the workspace root. If both code and filename are provided, code will be ignored.", + "type": "string" + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Run Playwright code (unsafe)", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_take_screenshot", + "description": "Take a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "element": { + "description": "Human-readable element description used to obtain permission to interact with the element", + "type": "string" + }, + "target": { + "description": "Exact target element reference from the page snapshot, or a unique element selector", + "type": "string" + }, + "type": { + "description": "Image format for the screenshot. If unset, inferred from the filename extension, otherwise png.", + "type": "string", + "enum": [ + "png", + "jpeg", + "webp" + ] + }, + "filename": { + "description": "File name to save the screenshot to. Relative file names are resolved against the workspace root. If not specified, the screenshot is saved into the output directory as `page-{timestamp}.{png|jpeg|webp}`.", + "type": "string" + }, + "fullPage": { + "description": "When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Cannot be used with element screenshots.", + "type": "boolean" + }, + "scale": { + "default": "css", + "description": "Image resolution scale. \"css\" produces a screenshot sized in CSS pixels (smaller, consistent across devices). \"device\" produces a high-resolution screenshot using device pixels (larger, accounts for the device pixel ratio). Default is css.", + "type": "string", + "enum": [ + "css", + "device" + ] + } + }, + "required": [ + "scale" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Take a screenshot", + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": true + } + }, + { + "name": "browser_snapshot", + "description": "Capture accessibility snapshot of the current page, this is better than screenshot", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "target": { + "description": "Exact target element reference from the page snapshot, or a unique element selector", + "type": "string" + }, + "filename": { + "description": "Save snapshot to a file instead of returning it in the response. Relative file names are resolved against the workspace root.", + "type": "string" + }, + "depth": { + "description": "Limit the depth of the snapshot tree", + "type": "number" + }, + "boxes": { + "description": "Include each element's bounding box as [box=x,y,width,height] in the snapshot. Coordinates are viewport-relative, in CSS pixels (Element.getBoundingClientRect)", + "type": "boolean" + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Page snapshot", + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": true + } + }, + { + "name": "browser_click", + "description": "Perform click on a web page", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "element": { + "description": "Human-readable element description used to obtain permission to interact with the element", + "type": "string" + }, + "target": { + "type": "string", + "description": "Exact target element reference from the page snapshot, or a unique element selector" + }, + "doubleClick": { + "description": "Whether to perform a double click instead of a single click", + "type": "boolean" + }, + "button": { + "description": "Button to click, defaults to left", + "type": "string", + "enum": [ + "left", + "right", + "middle" + ] + }, + "modifiers": { + "description": "Modifier keys to press", + "type": "array", + "items": { + "type": "string", + "enum": [ + "Alt", + "Control", + "ControlOrMeta", + "Meta", + "Shift" + ] + } + } + }, + "required": [ + "target" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Click", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_drag", + "description": "Perform drag and drop between two elements", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "startElement": { + "description": "Human-readable source element description used to obtain the permission to interact with the element", + "type": "string" + }, + "startTarget": { + "type": "string", + "description": "Exact target element reference from the page snapshot, or a unique element selector" + }, + "endElement": { + "description": "Human-readable target element description used to obtain the permission to interact with the element", + "type": "string" + }, + "endTarget": { + "type": "string", + "description": "Exact target element reference from the page snapshot, or a unique element selector" + } + }, + "required": [ + "startTarget", + "endTarget" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Drag mouse", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_hover", + "description": "Hover over element on page", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "element": { + "description": "Human-readable element description used to obtain permission to interact with the element", + "type": "string" + }, + "target": { + "type": "string", + "description": "Exact target element reference from the page snapshot, or a unique element selector" + } + }, + "required": [ + "target" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Hover mouse", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_select_option", + "description": "Select an option in a dropdown", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "element": { + "description": "Human-readable element description used to obtain permission to interact with the element", + "type": "string" + }, + "target": { + "type": "string", + "description": "Exact target element reference from the page snapshot, or a unique element selector" + }, + "values": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Array of values to select in the dropdown. This can be a single value or multiple values." + } + }, + "required": [ + "target", + "values" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Select option", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_tabs", + "description": "List, create, close, or select a browser tab.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": [ + "list", + "new", + "close", + "select" + ], + "description": "Operation to perform" + }, + "index": { + "description": "Tab index, used for close/select. If omitted for close, current tab is closed.", + "type": "number" + }, + "url": { + "description": "URL to navigate to in the new tab, used for new.", + "type": "string" + } + }, + "required": [ + "action" + ], + "additionalProperties": false + }, + "annotations": { + "title": "Manage tabs", + "readOnlyHint": false, + "destructiveHint": true, + "openWorldHint": true + } + }, + { + "name": "browser_wait_for", + "description": "Wait for text to appear or disappear or a specified time to pass", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "time": { + "description": "The time to wait in seconds", + "type": "number" + }, + "text": { + "description": "The text to wait for", + "type": "string" + }, + "textGone": { + "description": "The text to wait for to disappear", + "type": "string" + } + }, + "additionalProperties": false + }, + "annotations": { + "title": "Wait for", + "readOnlyHint": true, + "destructiveHint": false, + "openWorldHint": true + } + } + ] + } +} diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 2fc81ee..294f9d6 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -67,9 +67,9 @@ final class ToolSchemaShapeTests: XCTestCase { } } - // Upstream (Playwright) descriptors. UpstreamTool forwards each inputSchema unchanged, so the - // same guard must hold for them. These fixtures are written in the shape the Playwright MCP - // server publishes; the live tools/list was not queried. + // Upstream (Playwright) descriptors. UpstreamTool forwards each inputSchema, so the same guard + // must hold for them. These hand-written fixtures are in the shape the Playwright MCP server + // publishes. The recorded list below is the real one. private static func plain(_ type: String) -> JSONValue { ["type": .string(type)] } @@ -147,6 +147,52 @@ final class ToolSchemaShapeTests: XCTestCase { XCTAssertEqual(Self.problems(t.inputSchema, root: t.name), ["browser_bad.properties.x.anyOf"]) } + // The recorded tools/list of the pinned @playwright/mcp 0.0.82 (Tests/Fixtures). It was taken from + // a fresh stdio process with the app's flags; the running service on the browser port was not queried. + static func recordedUpstreamTools() throws -> [JSONValue] { + let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("Fixtures/playwright-mcp-0.0.82-tools-list.json") + let root = try JSONDecoder().decode(JSONValue.self, from: Data(contentsOf: url)) + return root["result"]?["tools"]?.arrayValue ?? [] + } + + func testRecordedPlaywrightToolsAreAllPlainAfterForwarding() throws { + let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) + let tools = try Self.recordedUpstreamTools() + XCTAssertEqual(tools.count, 32) + for d in tools { + let t = UpstreamTool(descriptorValue: d, upstream: upstream) + XCTAssertEqual(Self.problems(t.inputSchema, root: t.name), [], "\(t.name) uses a construct some MCP clients reject") + } + } + + func testEmulateMediaOverridesAreForwardedAsPlainEnums() throws { + let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) + let d = try XCTUnwrap(Self.recordedUpstreamTools().first { $0["name"]?.stringValue == "browser_emulate_media" }) + let props = UpstreamTool(descriptorValue: d, upstream: upstream).inputSchema["properties"] + let expected = [ + "colorScheme": ["light", "dark"], + "reducedMotion": ["reduce", "no-preference"], + "forcedColors": ["active", "none"], + "contrast": ["more", "no-preference"], + "media": ["screen", "print"], + ] + for (key, values) in expected { + XCTAssertNil(props?[key]?["anyOf"], "\(key) still carries anyOf") + XCTAssertEqual(props?[key]?["type"]?.stringValue, "string", key) + XCTAssertEqual(props?[key]?["enum"]?.arrayValue?.compactMap(\.stringValue), values, key) + XCTAssertNotNil(props?[key]?["description"], "\(key) lost its description") + } + } + + func testOtherRecordedPlaywrightToolsAreForwardedUnchanged() throws { + let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) + for d in try Self.recordedUpstreamTools() where d["name"]?.stringValue != "browser_emulate_media" { + let t = UpstreamTool(descriptorValue: d, upstream: upstream) + XCTAssertEqual(t.inputSchema, d["inputSchema"] ?? ["type": "object"], t.name) + } + } + // One test per banned keyword, so deleting an entry from `banned` fails its own test. func testBannedSetIsExactlyTheSevenKeywords() { From dc7786e6f2d79a68c7211a64c2f3d6e2eff0bc9b Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:40:11 -0500 Subject: [PATCH 08/26] fix(schema): serve option B for browser_emulate_media on every tools/list path tools/list served the raw upstream descriptor on three Swift paths (UpstreamTool.descriptor, the browser router's tools(), and the Playwright backend list it wraps) and on the Linux daemon (upstream_tools_for_with). The inputSchema getter was rewritten, but the wire was not, so browser_emulate_media still carried anyOf with a null branch on five properties. Fix: UpstreamTool.forwardedDescriptor applies forwardedSchema to the descriptor; UpstreamTool.descriptor and BrowserRouter.tools use it. On Linux, forwarded_descriptor applies the same rule in upstream_tools_for_with, so every tool list built from upstreams is covered. tool_schema_shape_tests.rs is rustfmt-clean (the file was failing cargo fmt --check). New tests (each calls the real tools/list handler on its platform and fails on the unfixed code): - Swift ToolSchemaShapeTests.testServedToolsListCarriesOptionBForUpstreamEmulateMedia: MCPServer.handle with an UpstreamMCP to a fake upstream serving the recorded 32-tool fixture. - Swift ToolSchemaShapeTests.testServedToolsListCarriesOptionBForBrowserRouterEmulateMedia: MCPServer.handle with a BrowserRouter over a Playwright backend serving the recorded list. - Rust tool_schema_shape_tests::served_owner_list_carries_option_b_for_upstream_emulate_media: tool_list_with(owner) over the recorded list. Before the fix: both Swift tests failed (24 assertion failures, browser_emulate_media anyOf on all five properties); the Rust test failed with the served anyOf in the output. After the fix, on the Apple build host, swift test: 756 executed, 5 skipped, 0 failures (ToolSchemaShapeTests: 24 executed, 0 failures). Command: swift test in a copy of the worktree (Package.swift at the root). After the fix, on the Linux build host, cargo test served_owner_list: 1 passed. cargo test tool_schema_shape: 17 passed. cargo test (full): 385 passed, 1 failed, 10 ignored; the failure is proc::tests::a_pid_that_does_not_exist_signals_nothing_and_does_not_panic, which the branch history already records as failing at a95874b and which this change does not touch. rustfmt --check: tool_schema_shape_tests.rs and mcp.rs clean. main.rs still has pre-existing fmt diffs, not changed here. --- .../Browser/BrowserRouter.swift | 6 +- Sources/InstanceMCPCore/UpstreamMCP.swift | 11 +- .../BrowserTestSupport.swift | 5 +- .../ToolSchemaShapeTests.swift | 44 +++++ .../UpstreamMCPTests.swift | 7 +- poc/reverse-attach-linux/src/mcp.rs | 41 ++++- .../src/tool_schema_shape_tests.rs | 158 ++++++++++++++++-- 7 files changed, 247 insertions(+), 25 deletions(-) diff --git a/Sources/InstanceMCPCore/Browser/BrowserRouter.swift b/Sources/InstanceMCPCore/Browser/BrowserRouter.swift index 7c85fd9..15eba65 100644 --- a/Sources/InstanceMCPCore/Browser/BrowserRouter.swift +++ b/Sources/InstanceMCPCore/Browser/BrowserRouter.swift @@ -74,9 +74,9 @@ public actor BrowserRouter { /// The catalog names the active backend serves now. Empty with no ready backend. public func tools(_ conn: BrowserConnection) async -> [JSONValue] { guard case .active(let b) = await select(conn) else { return [] } - return await b.tools().filter { - guard let n = $0["name"]?.stringValue else { return false } - return BrowserToolCatalog.allNameSet.contains(n) + return await b.tools().compactMap { + guard let n = $0["name"]?.stringValue, BrowserToolCatalog.allNameSet.contains(n) else { return nil } + return UpstreamTool.forwardedDescriptor($0) } } diff --git a/Sources/InstanceMCPCore/UpstreamMCP.swift b/Sources/InstanceMCPCore/UpstreamMCP.swift index 8d3e7b8..56c9f41 100644 --- a/Sources/InstanceMCPCore/UpstreamMCP.swift +++ b/Sources/InstanceMCPCore/UpstreamMCP.swift @@ -156,7 +156,16 @@ struct UpstreamTool: Tool { var name: String { descriptorValue["name"]?.stringValue ?? "?" } var description: String { descriptorValue["description"]?.stringValue ?? "" } var inputSchema: JSONValue { Self.forwardedSchema(name: name, descriptorValue["inputSchema"] ?? ["type": "object"]) } - var descriptor: JSONValue { descriptorValue } + /// What `tools/list` serves: the upstream descriptor with its inputSchema forwarded. + var descriptor: JSONValue { Self.forwardedDescriptor(descriptorValue) } + + /// A descriptor with `inputSchema` run through `forwardedSchema`. Every field other than + /// `inputSchema` is kept. Used for the upstream tools and for the browser router's tools. + static func forwardedDescriptor(_ descriptor: JSONValue) -> JSONValue { + guard var o = descriptor.objectValue, let schema = o["inputSchema"] else { return descriptor } + o["inputSchema"] = forwardedSchema(name: o["name"]?.stringValue ?? "", schema) + return .object(o) + } /// browser_emulate_media's five overrides are `anyOf: [enum string, null]`, a union that strict /// MCP clients drop (#145). Only that branch is kept: each property becomes its plain enum diff --git a/Tests/InstanceMCPCoreTests/BrowserTestSupport.swift b/Tests/InstanceMCPCoreTests/BrowserTestSupport.swift index d25c7b7..323c8cb 100644 --- a/Tests/InstanceMCPCoreTests/BrowserTestSupport.swift +++ b/Tests/InstanceMCPCoreTests/BrowserTestSupport.swift @@ -24,8 +24,11 @@ final class FakeBrowserBackend: BrowserBackend, @unchecked Sendable { var calls: [String] { lock.withLock { _calls } } func status() async -> BrowserBackendStatus { lock.withLock { _statusCalls += 1 }; return status_ } + /// When set, `tools()` returns these descriptors verbatim (for schema-shape tests). + var served: [JSONValue]? func tools() async -> [JSONValue] { - lock.withLock { _names }.map { ["name": .string($0), "description": "fake", "inputSchema": ["type": "object"]] } + if let served { return served } + return lock.withLock { _names }.map { ["name": .string($0), "description": "fake", "inputSchema": ["type": "object"]] } } func call(_ name: String, arguments: JSONValue) async throws -> JSONValue { lock.withLock { _calls.append(name) } diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 294f9d6..321cc30 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -185,6 +185,50 @@ final class ToolSchemaShapeTests: XCTestCase { } } + static let emulateMediaEnums: [String: [String]] = [ + "colorScheme": ["light", "dark"], + "reducedMotion": ["reduce", "no-preference"], + "forcedColors": ["active", "none"], + "contrast": ["more", "no-preference"], + "media": ["screen", "print"], + ] + + /// Checks the browser_emulate_media entry of a `tools/list` result as a client receives it: + /// no anyOf anywhere, and each of the five overrides is a plain string enum with no null. + static func assertServedOptionB(_ result: JSONValue?, file: StaticString = #filePath, line: UInt = #line) { + guard let entry = result?["tools"]?.arrayValue?.first(where: { $0["name"]?.stringValue == "browser_emulate_media" }) else { + return XCTFail("browser_emulate_media is not in tools/list", file: file, line: line) + } + let schema = entry["inputSchema"] ?? .null + let text = String(decoding: (try? JSONCoding.encoder.encode(schema)) ?? Data(), as: UTF8.self) + XCTAssertFalse(text.contains("anyOf"), "served browser_emulate_media schema still has anyOf", file: file, line: line) + XCTAssertEqual(problems(schema, root: "browser_emulate_media"), [], "served schema uses a banned construct", file: file, line: line) + for (key, values) in emulateMediaEnums { + let prop = schema["properties"]?[key] + XCTAssertEqual(prop?["type"]?.stringValue, "string", "\(key) is not a plain string", file: file, line: line) + XCTAssertEqual(prop?["enum"]?.arrayValue?.map { $0.stringValue ?? "" }, values, + "\(key) enum is not option B", file: file, line: line) + } + } + + // The real tools/list handler (MCPServer.handle), on the upstream path: the fake upstream + // serves the recorded Playwright list, and the server forwards it to the client. + func testServedToolsListCarriesOptionBForUpstreamEmulateMedia() async throws { + let up = try FakeUpstream(descriptors: try Self.recordedUpstreamTools()); defer { up.stop() } + let server = MCPServer(name: "t", version: "0", tools: [], + upstreams: [UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:\(up.port)/mcp")!)]) + Self.assertServedOptionB(try await serverRequest(server, "tools/list")?.result) + } + + // The real tools/list handler, on the browser router path (Playwright backend, recorded list). + func testServedToolsListCarriesOptionBForBrowserRouterEmulateMedia() async throws { + let backend = FakeBrowserBackend(.playwright) + backend.served = try Self.recordedUpstreamTools() + let server = MCPServer(name: "t", version: "0", tools: [], + browser: BrowserRouter(playwright: backend, store: MemoryPreferenceStore())) + Self.assertServedOptionB(try await serverRequest(server, "tools/list")?.result) + } + func testOtherRecordedPlaywrightToolsAreForwardedUnchanged() throws { let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) for d in try Self.recordedUpstreamTools() where d["name"]?.stringValue != "browser_emulate_media" { diff --git a/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift b/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift index 189918c..4d0b0e2 100644 --- a/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift +++ b/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift @@ -19,9 +19,11 @@ final class FakeUpstream: @unchecked Sendable { /// nil ⇒ the default three `browser_*` tools plus a `screenshot` that collides /// with the local one. private let toolNames: [String]? + private let descriptors: [JSONValue]? - init(toolNames: [String]? = nil) throws { + init(toolNames: [String]? = nil, descriptors: [JSONValue]? = nil) throws { self.toolNames = toolNames + self.descriptors = descriptors listener = try NWListener(using: .tcp, on: .any) let sem = DispatchSemaphore(value: 0) listener.stateUpdateHandler = { [weak self] st in @@ -77,6 +79,9 @@ final class FakeUpstream: @unchecked Sendable { } switch rpc.method { case "tools/list": + if let descriptors { + return sse(["jsonrpc": "2.0", "id": id, "result": ["tools": .array(descriptors)]]) + } if let toolNames { return sse(["jsonrpc": "2.0", "id": id, "result": ["tools": .array(toolNames.map { ["name": .string($0), "description": "fixture", "inputSchema": ["type": "object"]] diff --git a/poc/reverse-attach-linux/src/mcp.rs b/poc/reverse-attach-linux/src/mcp.rs index 5863f9f..31f9c5e 100644 --- a/poc/reverse-attach-linux/src/mcp.rs +++ b/poc/reverse-attach-linux/src/mcp.rs @@ -187,12 +187,51 @@ pub(crate) fn upstream_tools_for_with( if local_names.contains(&name) || !upstream_tool_allowed(name, profile) { continue; } - out.push((up.clone(), t)); + out.push((up.clone(), forwarded_descriptor(t))); } } out } +/// browser_emulate_media's five overrides are `anyOf: [enum string, null]` upstream (#145). Option B +/// (owner decision, PR #146): only the string branch is kept, so each property becomes its plain enum. +/// Mirrors `UpstreamTool.forwardedDescriptor` on the Swift side. Every other descriptor passes unchanged. +pub(crate) fn forwarded_descriptor(mut t: Value) -> Value { + if t.get("name").and_then(Value::as_str) != Some("browser_emulate_media") { + return t; + } + let Some(props) = t + .get_mut("inputSchema") + .and_then(|s| s.get_mut("properties")) + .and_then(Value::as_object_mut) + else { + return t; + }; + for prop in props.values_mut() { + let Some(obj) = prop.as_object_mut() else { + continue; + }; + let string = obj + .get("anyOf") + .and_then(Value::as_array) + .and_then(|branches| { + branches + .iter() + .find(|b| b.get("type").and_then(Value::as_str) == Some("string")) + }) + .and_then(Value::as_object) + .cloned(); + let Some(string) = string else { + continue; + }; + obj.remove("anyOf"); + for (k, v) in string { + obj.insert(k, v); + } + } + t +} + pub(crate) fn upstream_owning_with( name: &str, profile: &str, diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index dfa6340..8eadee8 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -1,17 +1,27 @@ //! Schema shape guard for the tool lists this daemon serves: `tool_list_with` (the local -//! tools and the job tools, for the owner and observe profiles) and `jobs::tools::tool_specs` -//! on their own. The rules match the Swift `ToolSchemaShapeTests`: no union, negation or -//! reference keyword, and no `type` array, at any schema position, and every schema position -//! carries one plain `type` string. Upstream (Playwright) schemas are forwarded unchanged and -//! are not in these lists; the Swift test covers them with fixtures. The live upstream -//! tools/list was not queried. +//! tools and the job tools, for the owner and observe profiles), `jobs::tools::tool_specs` +//! on their own, and the owner list with the recorded Playwright upstream. The rules match +//! the Swift `ToolSchemaShapeTests`: no union, negation or reference keyword, and no `type` +//! array, at any schema position, and every schema position carries one plain `type` string. +//! browser_emulate_media is also pinned to option B, as on the Swift side. + +use std::sync::Arc; use serde_json::{json, Value}; +use crate::backend::{BackendStatus, Upstream}; use crate::mcp::tool_list_with; /// Keywords no guarded schema may use at a schema position. -const BANNED: &[&str] = &["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"]; +const BANNED: &[&str] = &[ + "anyOf", + "oneOf", + "allOf", + "not", + "$ref", + "$defs", + "definitions", +]; /// Schema positions under `schema`, as (path, node): the node itself, the values of /// `properties`, `items` (object or tuple form) and `additionalProperties`. Data keywords @@ -67,19 +77,39 @@ fn problems(schema: &Value, root: &str) -> Vec { /// A schema `{type: object, properties: {a: {type: string, : value}}}`. fn with_property_keyword(keyword: &str, value: Value) -> Value { let mut a = json!({ "type": "string" }); - a.as_object_mut().unwrap().insert(keyword.to_string(), value); + a.as_object_mut() + .unwrap() + .insert(keyword.to_string(), value); json!({ "type": "object", "properties": { "a": a } }) } fn assert_tool_passes(tool: &Value, context: &str) { let name = tool["name"].as_str().unwrap_or("?"); - assert_eq!(tool["inputSchema"]["type"], "object", "{context}/{name}: top-level type"); - assert_eq!(problems(&tool["inputSchema"], name), Vec::::new(), "{context}/{name}"); + assert_eq!( + tool["inputSchema"]["type"], "object", + "{context}/{name}: top-level type" + ); + assert_eq!( + problems(&tool["inputSchema"], name), + Vec::::new(), + "{context}/{name}" + ); } #[test] fn banned_set_is_exactly_the_seven_keywords() { - assert_eq!(BANNED, ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"]); + assert_eq!( + BANNED, + [ + "anyOf", + "oneOf", + "allOf", + "not", + "$ref", + "$defs", + "definitions" + ] + ); } // One test per banned keyword, so dropping an entry from BANNED fails its own test. @@ -108,22 +138,34 @@ bans! { #[test] fn bans_array_valued_type() { let schema = json!({ "type": "object", "properties": { "a": { "type": ["string", "null"] } } }); - assert_eq!(problems(&schema, "t"), vec!["t.properties.a.type is an array".to_string()]); + assert_eq!( + problems(&schema, "t"), + vec!["t.properties.a.type is an array".to_string()] + ); } #[test] fn plain_type_is_checked_at_every_depth() { let nested = json!({ "type": "object", "properties": { "outer": { "type": "object", "properties": { "inner": { "description": "no type" } } } } }); - assert_eq!(problems(&nested, "t"), vec!["t.properties.outer.properties.inner has no single string type".to_string()]); + assert_eq!( + problems(&nested, "t"), + vec!["t.properties.outer.properties.inner has no single string type".to_string()] + ); let items = json!({ "type": "object", "properties": { "list": { "type": "array", "items": { "properties": { "x": { "type": "string" } } } } } }); - assert_eq!(problems(&items, "t"), vec!["t.properties.list.items has no single string type".to_string()]); + assert_eq!( + problems(&items, "t"), + vec!["t.properties.list.items has no single string type".to_string()] + ); let extra = json!({ "type": "object", "properties": { "map": { "type": "object", "additionalProperties": { "description": "no type" } } } }); - assert_eq!(problems(&extra, "t"), vec!["t.properties.map.additionalProperties has no single string type".to_string()]); + assert_eq!( + problems(&extra, "t"), + vec!["t.properties.map.additionalProperties has no single string type".to_string()] + ); } #[test] @@ -150,7 +192,10 @@ fn property_named_like_a_keyword_is_a_name() { #[test] fn root_must_be_an_object_schema() { - assert_eq!(problems(&json!("x"), "t"), vec!["t is not an object schema".to_string()]); + assert_eq!( + problems(&json!("x"), "t"), + vec!["t is not an object schema".to_string()] + ); } #[test] @@ -160,7 +205,10 @@ fn local_tool_lists_obey_the_schema_rules() { let owner = tool_list_with("owner", &[]); let owner = owner.as_array().expect("tools/list is an array"); let names: Vec<&str> = owner.iter().filter_map(|t| t["name"].as_str()).collect(); - assert!(names.contains(&"screenshot") && names.contains(&"exec_start"), "owner list: {names:?}"); + assert!( + names.contains(&"screenshot") && names.contains(&"exec_start"), + "owner list: {names:?}" + ); for tool in owner { assert_tool_passes(tool, "owner"); } @@ -176,8 +224,82 @@ fn local_tool_lists_obey_the_schema_rules() { #[test] fn job_tool_specs_obey_the_schema_rules() { let specs = crate::jobs::tools::tool_specs(); - assert_eq!(specs.len(), 4, "exec_start, exec_poll, exec_list, exec_cancel"); + assert_eq!( + specs.len(), + 4, + "exec_start, exec_poll, exec_list, exec_cancel" + ); for tool in &specs { assert_tool_passes(tool, "jobs"); } } + +/// The recorded tools/list of the pinned @playwright/mcp 0.0.82. The same file the Swift tests read. +const RECORDED_PLAYWRIGHT_TOOLS: &str = + include_str!("../../../Tests/Fixtures/playwright-mcp-0.0.82-tools-list.json"); + +/// An upstream that serves a fixed descriptor list, as the managed Playwright backend does. +struct RecordedUpstream(Vec); + +impl Upstream for RecordedUpstream { + fn tools(&self) -> Vec { + self.0.clone() + } + fn call(&self, _name: &str, _arguments: Value) -> Result { + Err("not called by this test".to_string()) + } + fn status(&self) -> BackendStatus { + BackendStatus { + backend: "managed", + reason: String::new(), + containment: String::new(), + display: "", + } + } +} + +/// browser_emulate_media as a client receives it: no anyOf, and each override is a plain +/// string enum with no null branch (option B). +fn assert_option_b_emulate_media(schema: &Value) { + let text = schema.to_string(); + assert!( + !text.contains("anyOf"), + "served browser_emulate_media schema still has anyOf: {text}" + ); + assert!( + problems(schema, "browser_emulate_media").is_empty(), + "served browser_emulate_media schema uses a banned construct: {:?}", + problems(schema, "browser_emulate_media") + ); + let expected = [ + ("colorScheme", json!(["light", "dark"])), + ("reducedMotion", json!(["reduce", "no-preference"])), + ("forcedColors", json!(["active", "none"])), + ("contrast", json!(["more", "no-preference"])), + ("media", json!(["screen", "print"])), + ]; + for (key, values) in expected { + let prop = &schema["properties"][key]; + assert_eq!(prop["type"], json!("string"), "{key} is not a plain string"); + assert_eq!(prop["enum"], values, "{key} enum is not option B"); + } +} + +#[test] +fn served_owner_list_carries_option_b_for_upstream_emulate_media() { + let fixture: Value = serde_json::from_str(RECORDED_PLAYWRIGHT_TOOLS).expect("fixture parses"); + let tools = fixture["result"]["tools"] + .as_array() + .expect("fixture has result.tools") + .clone(); + assert_eq!(tools.len(), 32); + let ups: Vec> = vec![Arc::new(RecordedUpstream(tools))]; + let owner = tool_list_with("owner", &ups); + let entry = owner + .as_array() + .expect("tools/list is an array") + .iter() + .find(|t| t["name"].as_str() == Some("browser_emulate_media")) + .expect("browser_emulate_media is served to owner"); + assert_option_b_emulate_media(&entry["inputSchema"]); +} From 33260360a0795596787bb98f9a00c1827916a2eb Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:43:50 -0500 Subject: [PATCH 09/26] test(schema): shape guard covers forwarded upstream tools The Linux shape guard checked the owner list only for browser_emulate_media. The other forwarded upstream tools were never run through assert_tool_passes, so an anyOf, oneOf, allOf, $ref, $defs, definitions or array-valued type on any of them would pass. New test every_served_owner_tool_obeys_the_schema_rules_with_recorded_upstream walks every tool that tool_list_with("owner") returns over the recorded 32-tool upstream fixture, and asserts each recorded upstream name is served. The existing option B test is unchanged. Verification, Linux build host, cargo test tool_schema_shape_tests: - base 07647ad35038d49e44989626de173a7810d2e4b2 with this file: 16 passed, 2 failed. every_served_owner_tool...: browser_emulate_media, anyOf on colorScheme, contrast, forcedColors, media, reducedMotion (plus "no single string type" on those nodes). served_owner_list_carries_option_b...: same tool, anyOf in the served schema. - HEAD dc7786e with this file: 18 passed, 0 failed. - rustfmt --check on this file: clean. --- .../src/tool_schema_shape_tests.rs | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index 8eadee8..b131c6b 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -303,3 +303,32 @@ fn served_owner_list_carries_option_b_for_upstream_emulate_media() { .expect("browser_emulate_media is served to owner"); assert_option_b_emulate_media(&entry["inputSchema"]); } + +/// Every forwarded upstream tool in the owner list, not only browser_emulate_media, passes the +/// shape rules. Each recorded upstream name must be served, so a dropped tool cannot hide a schema. +#[test] +fn every_served_owner_tool_obeys_the_schema_rules_with_recorded_upstream() { + let fixture: Value = serde_json::from_str(RECORDED_PLAYWRIGHT_TOOLS).expect("fixture parses"); + let tools = fixture["result"]["tools"] + .as_array() + .expect("fixture has result.tools") + .clone(); + let upstream_names: Vec = tools + .iter() + .filter_map(|t| t["name"].as_str().map(str::to_string)) + .collect(); + let ups: Vec> = vec![Arc::new(RecordedUpstream(tools))]; + let owner = tool_list_with("owner", &ups); + let owner = owner.as_array().expect("tools/list is an array"); + for name in &upstream_names { + assert!( + owner + .iter() + .any(|t| t["name"].as_str() == Some(name.as_str())), + "upstream tool {name} is not served to owner" + ); + } + for tool in owner { + assert_tool_passes(tool, "owner+upstream"); + } +} From 9fce1bba3be6a50b8edfa5b2eba34c7287c53ecd Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:45:50 -0500 Subject: [PATCH 10/26] fix(ui): title-only window error text in ui_snapshot The window-not-found error listed window indexes as [n], which strict clients cannot send. The error now tells the caller to match the window by its title and lists the titles without indexes. docs/ui-tools.md states that windows are matched by title only, and the long paragraph is rewrapped. Checks (remote Swift verification copy in /private/tmp/schema-anyof-verify): - swift build: Build complete, exit 0 - swift test: Executed 757 tests, 5 skipped, 0 failures (0 unexpected) - New test testWindowNotFoundErrorIsTitleOnly passes; testWindowSelection pins the new exact error text. --- Sources/InstanceMCPCore/Tools/UISnapshotTool.swift | 5 +++-- Tests/InstanceMCPCoreTests/UISnapshotTests.swift | 8 +++++++- docs/ui-tools.md | 7 ++++--- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift b/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift index 818f4f2..40f1911 100644 --- a/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift +++ b/Sources/InstanceMCPCore/Tools/UISnapshotTool.swift @@ -55,8 +55,9 @@ public struct UISnapshotTool: Tool { } public static func noWindows(_ app: String) -> String { "\(app) has no open windows" } public static func windowNotFound(_ w: String, app: String, titles: [String]) -> String { - "window '\(w)' not found in \(app); windows: " + - titles.enumerated().map { "[\($0.offset)] \"\($0.element)\"" }.joined(separator: ", ") + "window '\(w)' not found in \(app); match the window by its title " + + "(exact, else case-insensitive substring). Window titles: " + + titles.map { "\"\($0)\"" }.joined(separator: ", ") } public static func appBusy(_ app: String) -> String { "\(app) did not answer the Accessibility request in time (it may be busy or hung); retry, or raise timeout_ms" diff --git a/Tests/InstanceMCPCoreTests/UISnapshotTests.swift b/Tests/InstanceMCPCoreTests/UISnapshotTests.swift index ef5629e..bc17833 100644 --- a/Tests/InstanceMCPCoreTests/UISnapshotTests.swift +++ b/Tests/InstanceMCPCoreTests/UISnapshotTests.swift @@ -680,7 +680,7 @@ final class UISnapshotTargetTests: XCTestCase { XCTAssertTrue(same(try pick(app, all: true), ws)) XCTAssertThrowsError(try pick(app, .title("x"))) { e in XCTAssertEqual((e as? ToolError)?.description, - #"window 'x' not found in TextEdit; windows: [0] "Notes", [1] "notes draft""#) + #"window 'x' not found in TextEdit; match the window by its title (exact, else case-insensitive substring). Window titles: "Notes", "notes draft""#) } XCTAssertThrowsError(try pick(app, .index(5))) { e in XCTAssertTrue((e as? ToolError)?.description.hasPrefix("window '5' not found in TextEdit") == true) @@ -693,6 +693,12 @@ final class UISnapshotTargetTests: XCTestCase { XCTAssertThrowsError(try pick(appElement(), all: true)) } + func testWindowNotFoundErrorIsTitleOnly() { + let text = UISnapshotTool.Errors.windowNotFound("x", app: "TextEdit", titles: ["Notes", "notes draft"]) + XCTAssertTrue(text.contains("match the window by its title")) + XCTAssertFalse(text.contains("["), "no index brackets: strict clients cannot send indexes") + } + func testWindowLookupErrors() { let busy = appElement(windows: [el("AXWindow", "w")]) busy.elementError = .timeout diff --git a/docs/ui-tools.md b/docs/ui-tools.md index 3682262..065224b 100644 --- a/docs/ui-tools.md +++ b/docs/ui-tools.md @@ -9,9 +9,10 @@ has the summary. Both tools are macOS only; the Linux AT-SPI port is deferred Accessibility tree of a native app's window (AXUIElement), read-only. `owner` only. - **Target.** Default: the frontmost app's focused window. `app` (bundle id or name) or `pid` - selects an app; `window` (a title string) or `all_windows` selects windows. Strict clients can only send a - title, so they cannot pick an untitled or duplicate-title window by index. A native JSON integer in `window` still - selects an index for existing callers (#145). + selects an app. Windows are matched by title only: `window` (a title string) or `all_windows` + selects windows. Strict clients can only send a title, so they cannot pick an untitled or + duplicate-title window by index. A native JSON integer in `window` still selects an index for + existing callers (#145). `include_menu_bar` also walks the app's menu bar, so menu items get refs. - **Per node.** Role, subrole, title, value (secure fields always masked), state, frame in display points (the `screenshot`/`mouse` space, with display index), and a `ref` valid within From e5c2e53516840c34009332e6005a1ca31f851eda Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:48:07 -0500 Subject: [PATCH 11/26] fix(ui): name the field in valueTypeRejected and match value parse error to schema valueTypeRejected now names the `value` property, the key the request used. The value parse error lists only the type the ui_action schema declares for `value` (string), not number or boolean. The parser still accepts a native number or boolean for existing callers, so that error only fires for arrays, objects and non-finite numbers. Tests: new testValueTypeRejectedNamesTheValueField and testValueParseErrorNamesOnlyTheSchemaType; testValueTypeRefusedInBothFormsSaysSo and testInvalidParams updated to the new wording. Verification: swift build exit 0; swift test (full suite) exit 0, Executed 759 tests, 5 skipped, 0 failures, run over ssh on the verification host in a copy of the worktree. --- .../InstanceMCPCore/Tools/UIActionTool.swift | 6 +++--- .../InstanceMCPCoreTests/UIActionTests.swift | 21 +++++++++++++++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/Sources/InstanceMCPCore/Tools/UIActionTool.swift b/Sources/InstanceMCPCore/Tools/UIActionTool.swift index 9267d5e..e14f469 100644 --- a/Sources/InstanceMCPCore/Tools/UIActionTool.swift +++ b/Sources/InstanceMCPCore/Tools/UIActionTool.swift @@ -76,9 +76,9 @@ public struct UIActionTool: Tool { /// unsupported action, so the supported list is not shown. public static func valueTypeRejected(ref: String, role: String, retried: Bool) -> String { if retried { - return "\(ref) (\(role)) rejected the value as text and as a number or boolean (AX error -25201). Take a new ui_snapshot to check the control's current value type" + return "\(ref) (\(role)) rejected the `value` property as text and as a number or boolean (AX error -25201). Take a new ui_snapshot to check the control's current value type" } - return "\(ref) (\(role)) rejected the value's type (AX error -25201). The value has no number or boolean form, so it does not fit this control. Take a new ui_snapshot to check the control's value type, then send a value of that type" + return "\(ref) (\(role)) rejected the `value` property's type (AX error -25201). The `value` has no number or boolean form, so it does not fit this control. Take a new ui_snapshot to check the control's value type, then send a `value` of that type" } public static func unconfirmed(action: String, ref: String, app: String) -> String { "ui_action \(action) [\(ref)]: \(app) did not confirm in time. The action may have happened (a press that opens a dialog or menu often answers late); take a new ui_snapshot to check, and do not repeat it blindly" @@ -170,7 +170,7 @@ public struct UIActionTool: Tool { r.value = .string(s) case .number(let d) where d.isFinite: r.value = .number(d) case .bool(let b): r.value = .bool(b) - default: throw JSONRPCError.invalidParams("value must be a string, number or boolean") + default: throw JSONRPCError.invalidParams("value must be a string") } } else if kind == .setValue { throw JSONRPCError.invalidParams("value is required for set_value") diff --git a/Tests/InstanceMCPCoreTests/UIActionTests.swift b/Tests/InstanceMCPCoreTests/UIActionTests.swift index b50a460..6890a59 100644 --- a/Tests/InstanceMCPCoreTests/UIActionTests.swift +++ b/Tests/InstanceMCPCoreTests/UIActionTests.swift @@ -361,7 +361,7 @@ final class UIActionToolTests: XCTestCase { let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "hello"]) XCTAssertTrue(r.isToolError) XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: false)) - XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the value's type (AX error -25201). The value has no number or boolean form, so it does not fit this control. Take a new ui_snapshot to check the control's value type, then send a value of that type") + XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's type (AX error -25201). The `value` has no number or boolean form, so it does not fit this control. Take a new ui_snapshot to check the control's value type, then send a `value` of that type") XCTAssertFalse(r.text.contains("JSON"), r.text) XCTAssertFalse(r.text.contains("does not support"), r.text) XCTAssertFalse(r.text.contains("Supported on it"), r.text) @@ -380,6 +380,23 @@ final class UIActionToolTests: XCTestCase { assertNothingDone(f) } + func testValueTypeRejectedNamesTheValueField() { + for retried in [false, true] { + let text = UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: retried) + XCTAssertTrue(text.contains("the `value` property"), text) + } + } + + func testValueParseErrorNamesOnlyTheSchemaType() async { + let f = Fixture() + let id = await f.snapshot() + // The schema declares `value` as a string only, so the error names that type alone. + let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": ["a"]]) + XCTAssertEqual(r.error?.code, JSONRPCError.invalidParams) + XCTAssertEqual(r.error?.message, "Invalid params: value must be a string") + assertNothingDone(f) + } + func testNoSupportedActionPointsToMouse() async { let f = Fixture() let id = await f.snapshot() @@ -790,7 +807,7 @@ final class UIActionToolTests: XCTestCase { "action must be one of press, set_value, focus, show_menu, confirm, cancel, increment, decrement"), (["snapshot_id": sid, "ref": "e2", "action": "set_value"], "value is required for set_value"), (["snapshot_id": sid, "ref": "e3", "action": "press", "value": "x"], "value is only accepted with set_value"), - (["snapshot_id": sid, "ref": "e2", "action": "set_value", "value": ["a"]], "value must be a string, number or boolean"), + (["snapshot_id": sid, "ref": "e2", "action": "set_value", "value": ["a"]], "value must be a string"), (["snapshot_id": sid, "ref": "e2", "action": "set_value", "value": .string(String(repeating: "x", count: 65_537))], "value is longer than 65536 characters"), (["snapshot_id": sid, "ref": "e3", "action": "press", "activate": "yes"], "activate must be a boolean"), From faa323bec4dd44ce25ac352120ee85c74374ee9a Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:48:46 -0500 Subject: [PATCH 12/26] style(linux): cargo fmt Apply cargo fmt to poc/reverse-attach-linux/src/main.rs. The only change moves the `#[cfg(test)] mod tool_schema_shape_tests;` declaration above `mod tools;` into rustfmt's sorted module order. No code changes. Toolchain: stable, rustc 1.98.1 / rustfmt 1.9.0-stable (CI uses dtolnay/rust-toolchain@stable, no pin in repo). cargo fmt --check before: exit 1 (main.rs:49 and main.rs:55 diffs). cargo fmt --check after: exit 0. --- poc/reverse-attach-linux/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/poc/reverse-attach-linux/src/main.rs b/poc/reverse-attach-linux/src/main.rs index 77b9796..7d2a0c7 100644 --- a/poc/reverse-attach-linux/src/main.rs +++ b/poc/reverse-attach-linux/src/main.rs @@ -49,12 +49,12 @@ mod sigstop; mod state; mod stdio_client; mod sweep; +#[cfg(test)] +mod tool_schema_shape_tests; mod tools; mod unit; #[cfg(test)] mod wire_conformance; -#[cfg(test)] -mod tool_schema_shape_tests; /// Install rustls's ring provider as the process default, once. tungstenite builds /// its rustls `ClientConfig` from the process default; with no provider a wss:// From d4297ef3fb19b9047383e8e3475c7ccb6f604b45 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:06:56 -0500 Subject: [PATCH 13/26] test(schema): cover runtime refusal, native value wording and emulate description Tests only. No production code changes in this commit. Schema behavior chosen for finding 1: refuse. A forwarded schema that still carries a banned construct after option B is hidden from tools/list, and a call to it is not routed upstream. The fix commit logs the tool name. New or changed tests (expected to fail on faa323b; read from the code, not run): - Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift testServedToolsListHidesUpstreamToolsWithBannedSchemas (finding 1) testUpstreamToolWithBannedSchemaIsNotCalled (finding 1) testBrowserRouterHidesToolWithBannedSchema (finding 1) testBrowserRouterRefusesCallToToolWithBannedSchema (finding 1) testForwardedEmulateMediaDescriptionDoesNotMentionNull (finding 2) assertServedOptionB also checks the served description has no null (finding 2) - Tests/InstanceMCPCoreTests/UIActionTests.swift testValueTypeRefusedForNativeNumberSaysTheControlRefusesNumbers (finding 3) testValueTypeRefusedForNativeBoolSaysTheControlRefusesBooleans (finding 3) testValueTypeRefusedForNativeNumber... string-case expectation rewritten (finding 3, wording) testValueParseErrorNamesTheAcceptedTypes (renamed from testValueParseErrorNamesOnlyTheSchemaType; wording) - poc/reverse-attach-linux/src/tool_schema_shape_tests.rs served_owner_list_hides_upstream_tools_with_banned_schemas (finding 1) forwarded_upstream_list_refuses_banned_tools_and_keeps_recorded_tools (finding 3) upstream_does_not_own_a_call_to_a_banned_schema_tool (finding 1) served_owner_list_carries_option_b_for_upstream_emulate_media now checks the description (finding 2) Not verified: nothing was compiled or run on the laptop. Swift and Rust suites have not been run against this commit. --- .../ToolSchemaShapeTests.swift | 69 +++++++++++ .../InstanceMCPCoreTests/UIActionTests.swift | 37 +++++- .../src/tool_schema_shape_tests.rs | 111 +++++++++++++++++- 3 files changed, 207 insertions(+), 10 deletions(-) diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 321cc30..3cd03dc 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -203,6 +203,8 @@ final class ToolSchemaShapeTests: XCTestCase { let text = String(decoding: (try? JSONCoding.encoder.encode(schema)) ?? Data(), as: UTF8.self) XCTAssertFalse(text.contains("anyOf"), "served browser_emulate_media schema still has anyOf", file: file, line: line) XCTAssertEqual(problems(schema, root: "browser_emulate_media"), [], "served schema uses a banned construct", file: file, line: line) + let description = entry["description"]?.stringValue ?? "" + XCTAssertFalse(description.contains("null"), "served browser_emulate_media description still mentions null: \(description)", file: file, line: line) for (key, values) in emulateMediaEnums { let prop = schema["properties"]?[key] XCTAssertEqual(prop?["type"]?.stringValue, "string", "\(key) is not a plain string", file: file, line: line) @@ -237,6 +239,73 @@ final class ToolSchemaShapeTests: XCTestCase { } } + // Runtime refusal (finding 1). A forwarded schema that still carries a banned construct is hidden + // from tools/list and cannot be called, on the upstream path and on the browser router path. Option B + // covers browser_emulate_media only, so these fixtures use other names. + + private static func rawTool(_ name: String, _ inputSchema: JSONValue) -> JSONValue { + ["name": .string(name), "description": "fixture", "inputSchema": inputSchema] + } + + private static let bannedUpstreamTools: [JSONValue] = [ + rawTool("browser_union", ["type": "object", "properties": ["x": ["type": "string", + "anyOf": [["type": "string"], ["type": "null"]]]]]), + rawTool("browser_ref", ["type": "object", "properties": ["x": ["$ref": "#/$defs/x"]]]), + rawTool("browser_defs", ["type": "object", "$defs": ["x": ["type": "string"]], + "properties": ["x": ["type": "string"]]]), + ] + + func testServedToolsListHidesUpstreamToolsWithBannedSchemas() async throws { + let up = try FakeUpstream(descriptors: [Self.descriptor("browser_navigate", ["url": Self.plain("string")], required: ["url"])] + + Self.bannedUpstreamTools) + defer { up.stop() } + let server = MCPServer(name: "t", version: "0", tools: [], + upstreams: [UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:\(up.port)/mcp")!)]) + let names = listedNames(try await serverRequest(server, "tools/list")) + XCTAssertTrue(names.contains("browser_navigate"), "\(names)") + for name in ["browser_union", "browser_ref", "browser_defs"] { + XCTAssertFalse(names.contains(name), "\(name) is served with a banned schema: \(names)") + } + } + + func testUpstreamToolWithBannedSchemaIsNotCalled() async throws { + let up = try FakeUpstream(descriptors: Self.bannedUpstreamTools) + defer { up.stop() } + let server = MCPServer(name: "t", version: "0", tools: [], + upstreams: [UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:\(up.port)/mcp")!)]) + _ = try await serverRequest(server, "tools/call", params: ["name": "browser_union", "arguments": [:]]) + XCTAssertTrue(up.calls.isEmpty, "the upstream ran browser_union, whose schema is refused") + } + + func testBrowserRouterHidesToolWithBannedSchema() async throws { + let backend = FakeBrowserBackend(.playwright) + backend.served = [Self.rawTool("browser_navigate", ["type": "object", "properties": ["x": ["type": "string", + "anyOf": [["type": "string"], ["type": "null"]]]]]), + Self.rawTool("browser_snapshot", ["type": "object"])] + let server = MCPServer(name: "t", version: "0", tools: [], + browser: BrowserRouter(playwright: backend, store: MemoryPreferenceStore())) + let names = listedNames(try await serverRequest(server, "tools/list")) + XCTAssertTrue(names.contains("browser_snapshot"), "\(names)") + XCTAssertFalse(names.contains("browser_navigate"), "browser_navigate is served with a banned schema: \(names)") + } + + func testBrowserRouterRefusesCallToToolWithBannedSchema() async { + let backend = FakeBrowserBackend(.playwright) + backend.served = [Self.rawTool("browser_navigate", ["type": "object", "properties": ["x": ["$ref": "#/$defs/x"]]])] + let router = BrowserRouter(playwright: backend, store: MemoryPreferenceStore()) + let result = await router.call("browser_navigate", arguments: [:], BrowserConnection(key: "c1")) + XCTAssertEqual(result["isError"]?.boolValue, true, "\(result)") + XCTAssertTrue(backend.calls.isEmpty, "the backend ran browser_navigate, whose schema is refused") + } + + func testForwardedEmulateMediaDescriptionDoesNotMentionNull() throws { + let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) + let d = try XCTUnwrap(Self.recordedUpstreamTools().first { $0["name"]?.stringValue == "browser_emulate_media" }) + let served = UpstreamTool(descriptorValue: d, upstream: upstream).descriptor["description"]?.stringValue ?? "" + XCTAssertFalse(served.contains("null"), "served description still mentions null: \(served)") + XCTAssertTrue(served.contains("Omitted parameters are left unchanged"), served) + } + // One test per banned keyword, so deleting an entry from `banned` fails its own test. func testBannedSetIsExactlyTheSevenKeywords() { diff --git a/Tests/InstanceMCPCoreTests/UIActionTests.swift b/Tests/InstanceMCPCoreTests/UIActionTests.swift index 6890a59..ec0954f 100644 --- a/Tests/InstanceMCPCoreTests/UIActionTests.swift +++ b/Tests/InstanceMCPCoreTests/UIActionTests.swift @@ -361,13 +361,40 @@ final class UIActionToolTests: XCTestCase { let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "hello"]) XCTAssertTrue(r.isToolError) XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: false)) - XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's type (AX error -25201). The `value` has no number or boolean form, so it does not fit this control. Take a new ui_snapshot to check the control's value type, then send a `value` of that type") + XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's type (AX error -25201). The `value` is text with no number or boolean form, and this control cannot take text. Take a new ui_snapshot to check the control's current value") XCTAssertFalse(r.text.contains("JSON"), r.text) XCTAssertFalse(r.text.contains("does not support"), r.text) XCTAssertFalse(r.text.contains("Supported on it"), r.text) assertNothingDone(f) } + func testValueTypeRefusedForNativeNumberSaysTheControlRefusesNumbers() async { + let f = Fixture() + let id = await f.snapshot() + f.textArea.settable = ["AXValue"] + f.textArea.setError = .other(UIAXError.illegalArgumentCode) + // The caller sent a native number, so there is no string form to retry and the message must not + // say the value has no number form. + let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": .number(3)]) + XCTAssertTrue(r.isToolError) + XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's number type (AX error -25201). This control does not accept a number `value`. Take a new ui_snapshot to check the control's current value") + XCTAssertFalse(r.text.contains("no number or boolean form"), r.text) + XCTAssertFalse(r.text.contains("3"), "the value is never echoed: \(r.text)") + assertNothingDone(f) + } + + func testValueTypeRefusedForNativeBoolSaysTheControlRefusesBooleans() async { + let f = Fixture() + let id = await f.snapshot() + f.textArea.settable = ["AXValue"] + f.textArea.setError = .other(UIAXError.illegalArgumentCode) + let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": .bool(true)]) + XCTAssertTrue(r.isToolError) + XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's boolean type (AX error -25201). This control does not accept a boolean `value`. Take a new ui_snapshot to check the control's current value") + XCTAssertFalse(r.text.contains("no number or boolean form"), r.text) + assertNothingDone(f) + } + func testValueTypeRefusedInBothFormsSaysSo() async { let f = Fixture() let id = await f.snapshot() @@ -387,13 +414,13 @@ final class UIActionToolTests: XCTestCase { } } - func testValueParseErrorNamesOnlyTheSchemaType() async { + func testValueParseErrorNamesTheAcceptedTypes() async { let f = Fixture() let id = await f.snapshot() - // The schema declares `value` as a string only, so the error names that type alone. + // The parser accepts a string, a number or a boolean, and the error names all three. let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": ["a"]]) XCTAssertEqual(r.error?.code, JSONRPCError.invalidParams) - XCTAssertEqual(r.error?.message, "Invalid params: value must be a string") + XCTAssertEqual(r.error?.message, "Invalid params: value must be a string, number or boolean") assertNothingDone(f) } @@ -807,7 +834,7 @@ final class UIActionToolTests: XCTestCase { "action must be one of press, set_value, focus, show_menu, confirm, cancel, increment, decrement"), (["snapshot_id": sid, "ref": "e2", "action": "set_value"], "value is required for set_value"), (["snapshot_id": sid, "ref": "e3", "action": "press", "value": "x"], "value is only accepted with set_value"), - (["snapshot_id": sid, "ref": "e2", "action": "set_value", "value": ["a"]], "value must be a string"), + (["snapshot_id": sid, "ref": "e2", "action": "set_value", "value": ["a"]], "value must be a string, number or boolean"), (["snapshot_id": sid, "ref": "e2", "action": "set_value", "value": .string(String(repeating: "x", count: 65_537))], "value is longer than 65536 characters"), (["snapshot_id": sid, "ref": "e3", "action": "press", "activate": "yes"], "activate must be a boolean"), diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index b131c6b..6a9c2ea 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use serde_json::{json, Value}; use crate::backend::{BackendStatus, Upstream}; -use crate::mcp::tool_list_with; +use crate::mcp::{tool_list_with, upstream_owning_with, upstream_tools_for_with}; /// Keywords no guarded schema may use at a schema position. const BANNED: &[&str] = &[ @@ -258,9 +258,10 @@ impl Upstream for RecordedUpstream { } } -/// browser_emulate_media as a client receives it: no anyOf, and each override is a plain -/// string enum with no null branch (option B). -fn assert_option_b_emulate_media(schema: &Value) { +/// browser_emulate_media as a client receives it: no anyOf, each override is a plain string enum +/// with no null branch (option B), and the description no longer offers null. +fn assert_option_b_emulate_media(entry: &Value) { + let schema = &entry["inputSchema"]; let text = schema.to_string(); assert!( !text.contains("anyOf"), @@ -271,6 +272,11 @@ fn assert_option_b_emulate_media(schema: &Value) { "served browser_emulate_media schema uses a banned construct: {:?}", problems(schema, "browser_emulate_media") ); + let description = entry["description"].as_str().unwrap_or_default(); + assert!( + !description.contains("null"), + "served browser_emulate_media description still mentions null: {description}" + ); let expected = [ ("colorScheme", json!(["light", "dark"])), ("reducedMotion", json!(["reduce", "no-preference"])), @@ -301,7 +307,7 @@ fn served_owner_list_carries_option_b_for_upstream_emulate_media() { .iter() .find(|t| t["name"].as_str() == Some("browser_emulate_media")) .expect("browser_emulate_media is served to owner"); - assert_option_b_emulate_media(&entry["inputSchema"]); + assert_option_b_emulate_media(entry); } /// Every forwarded upstream tool in the owner list, not only browser_emulate_media, passes the @@ -332,3 +338,98 @@ fn every_served_owner_tool_obeys_the_schema_rules_with_recorded_upstream() { assert_tool_passes(tool, "owner+upstream"); } } + +fn recorded_tools() -> Vec { + let fixture: Value = serde_json::from_str(RECORDED_PLAYWRIGHT_TOOLS).expect("fixture parses"); + fixture["result"]["tools"] + .as_array() + .expect("fixture has result.tools") + .clone() +} + +/// Upstream descriptors whose schemas still carry a banned construct after forwarding. Option B +/// covers browser_emulate_media only, so these other names must be refused by the runtime guard. +fn banned_upstream_tools() -> Vec { + vec![ + json!({ "name": "browser_union", "description": "fixture", "inputSchema": { + "type": "object", + "properties": { "x": { "type": "string", "anyOf": [{ "type": "string" }, { "type": "null" }] } } + } }), + json!({ "name": "browser_ref", "description": "fixture", "inputSchema": { + "type": "object", + "properties": { "x": { "$ref": "#/$defs/x" } } + } }), + json!({ "name": "browser_defs", "description": "fixture", "inputSchema": { + "type": "object", + "$defs": { "x": { "type": "string" } }, + "properties": { "x": { "type": "string" } } + } }), + ] +} + +const BANNED_NAMES: [&str; 3] = ["browser_union", "browser_ref", "browser_defs"]; + +/// An upstream tool whose schema has a banned construct is not served to the owner profile, and its +/// name is not left in the list. Covers anyOf, $ref and $defs. +#[test] +fn served_owner_list_hides_upstream_tools_with_banned_schemas() { + let mut tools = recorded_tools(); + tools.extend(banned_upstream_tools()); + let ups: Vec> = vec![Arc::new(RecordedUpstream(tools))]; + let owner = tool_list_with("owner", &ups); + let owner = owner.as_array().expect("tools/list is an array"); + let names: Vec<&str> = owner.iter().filter_map(|t| t["name"].as_str()).collect(); + assert!(names.contains(&"browser_navigate"), "owner list: {names:?}"); + for name in BANNED_NAMES { + assert!( + !names.contains(&name), + "{name} is served with a banned schema: {names:?}" + ); + } + for tool in owner { + assert_tool_passes(tool, "owner+banned"); + } +} + +/// The forwarded upstream list is shape-checked: every recorded tool is still forwarded, and the +/// banned tools are dropped. The recorded list is live only for the pinned fixture; a query to a +/// running @playwright/mcp is not part of the unit tests. +#[test] +fn forwarded_upstream_list_refuses_banned_tools_and_keeps_recorded_tools() { + let recorded: Vec = recorded_tools() + .iter() + .filter_map(|t| t["name"].as_str().map(str::to_string)) + .collect(); + let mut tools = recorded_tools(); + tools.extend(banned_upstream_tools()); + let ups: Vec> = vec![Arc::new(RecordedUpstream(tools))]; + let forwarded = upstream_tools_for_with("owner", &[], &ups); + let names: Vec<&str> = forwarded + .iter() + .filter_map(|(_, t)| t["name"].as_str()) + .collect(); + for name in &recorded { + assert!(names.contains(&name.as_str()), "{name} was dropped: {names:?}"); + } + for name in BANNED_NAMES { + assert!(!names.contains(&name), "{name} is forwarded: {names:?}"); + } + for (_, tool) in &forwarded { + let name = tool["name"].as_str().unwrap_or("?"); + assert_eq!( + problems(&tool["inputSchema"], name), + Vec::::new(), + "{name} forwarded with a banned construct" + ); + } +} + +/// A call to a refused upstream tool is not routed upstream, so the upstream never runs it. +#[test] +fn upstream_does_not_own_a_call_to_a_banned_schema_tool() { + let ups: Vec> = vec![Arc::new(RecordedUpstream(banned_upstream_tools()))]; + assert!( + upstream_owning_with("browser_union", "owner", &ups).is_none(), + "a call to a refused tool is routed to the upstream" + ); +} From 507e2f9dc1555f647cccd52aa9bea7ead0d6dfe3 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:10:16 -0500 Subject: [PATCH 14/26] fix(schema): refuse forwarded tools whose schema breaks the shape rules; fix value-type and emulate wording Schema behavior chosen for finding 1: refuse, not normalize. A forwarded upstream tool whose inputSchema still has a banned keyword (anyOf, oneOf, allOf, not, $ref, $defs, definitions) or a non-plain type after option B is hidden from tools/list and its call is not routed upstream. The refusal is logged with the tool name and the first offending path. Option B stays limited to browser_emulate_media. The other pinned upstream tools already pass, so their served output is unchanged. Refusal applies on the Swift UpstreamMCP and browser router paths and in the Linux upstream_tools_for_with and upstream_owning_with paths. Shape rules now live in one place per platform: ToolSchemaShape.swift and src/schema_shape.rs. The test helpers forward to them. Finding 2: browser_emulate_media's served description drops the sentence about null (option B removed the null branch), on both platforms. Finding 3 (wording): valueTypeRejected takes the sent value. A string with no native form keeps the "no number or boolean form" text, without advice to send a number or boolean. A native number or boolean gets a message that the control does not accept that type. The retried text is unchanged. Finding 4 (wording): "value must be a string, number or boolean" replaces "value must be a string", matching what the parser accepts. docs/ui-tools.md splits the window contract (title-only for strict clients, native integer still an index) and documents the one string-to-native retry in set_value. Tests for these changes were added in the preceding commit (HEAD~1). Not run: nothing was compiled or tested on the laptop, and cargo fmt --check was not run here. The Swift and Rust suites, and rustfmt, must run remotely before merge. Not fixed: the prefixed-name keying of option B (Sol LOW 6, latent, production uses an empty prefix), extending the banned keyword list (Sol NIT 8), and the window -1 message (Sol NIT 7, Opus NIT 4; reviewers accepted it). --- .../Browser/BrowserRouter.swift | 6 +- Sources/InstanceMCPCore/ToolSchemaShape.swift | 49 +++++++++++++ .../InstanceMCPCore/Tools/UIActionTool.swift | 17 +++-- .../InstanceMCPCore/UISnapshot/UIAction.swift | 3 +- Sources/InstanceMCPCore/UpstreamMCP.swift | 34 +++++++-- .../ToolSchemaShapeTests.swift | 41 ++--------- .../InstanceMCPCoreTests/UIActionTests.swift | 6 +- docs/ui-tools.md | 9 ++- poc/reverse-attach-linux/src/main.rs | 1 + poc/reverse-attach-linux/src/mcp.rs | 54 +++++++++++++-- poc/reverse-attach-linux/src/schema_shape.rs | 69 +++++++++++++++++++ .../src/tool_schema_shape_tests.rs | 63 +---------------- 12 files changed, 229 insertions(+), 123 deletions(-) create mode 100644 Sources/InstanceMCPCore/ToolSchemaShape.swift create mode 100644 poc/reverse-attach-linux/src/schema_shape.rs diff --git a/Sources/InstanceMCPCore/Browser/BrowserRouter.swift b/Sources/InstanceMCPCore/Browser/BrowserRouter.swift index 15eba65..991289d 100644 --- a/Sources/InstanceMCPCore/Browser/BrowserRouter.swift +++ b/Sources/InstanceMCPCore/Browser/BrowserRouter.swift @@ -76,6 +76,10 @@ public actor BrowserRouter { guard case .active(let b) = await select(conn) else { return [] } return await b.tools().compactMap { guard let n = $0["name"]?.stringValue, BrowserToolCatalog.allNameSet.contains(n) else { return nil } + if let why = UpstreamTool.refusal($0) { + log("browser backend \(b.id.rawValue): tool \(n) is not served: \(why)") + return nil + } return UpstreamTool.forwardedDescriptor($0) } } @@ -97,7 +101,7 @@ public actor BrowserRouter { + "OAB-Browser-Backend header.", backend: nil) case .active(let b): backend = b } - let served = await backend.tools().compactMap { $0["name"]?.stringValue } + let served = await backend.tools().filter { UpstreamTool.refusal($0) == nil }.compactMap { $0["name"]?.stringValue } guard served.contains(name) else { return Self.errorResult("\(name) is not available with the \(backend.id.rawValue) backend. " + "Install Playwright or select it in OpenAB Computer, Browser tools.", backend: backend.id) diff --git a/Sources/InstanceMCPCore/ToolSchemaShape.swift b/Sources/InstanceMCPCore/ToolSchemaShape.swift new file mode 100644 index 0000000..458010e --- /dev/null +++ b/Sources/InstanceMCPCore/ToolSchemaShape.swift @@ -0,0 +1,49 @@ +import Foundation + +/// The schema rules every served tool must meet. Some MCP clients (Grok's connector, many +/// function-calling validators) drop a tool whose input schema uses a union, a negation or a +/// reference keyword, or a `type` array, at any depth. Every schema position must carry one plain +/// `type` string. The runtime uses these rules to refuse a forwarded tool that breaks them (see +/// `UpstreamTool.refusal`), and the tests use them over the local catalog. +enum ToolSchemaShape { + /// Keywords no served schema may use at a schema position. + static let banned: Set = ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"] + + /// Findings for one schema, by path: a banned keyword, a `type` array, or a schema position + /// without one plain `type` string. Empty when the schema passes. + static func problems(_ schema: JSONValue, root: String) -> [String] { + guard schema.objectValue != nil else { return ["\(root) is not an object schema"] } + var out: [String] = [] + for (path, node) in nodes(schema, path: root) { + for k in node.keys.sorted() where banned.contains(k) { out.append("\(path).\(k)") } + if node["type"]?.arrayValue != nil { + out.append("\(path).type is an array") + } else if node["type"]?.stringValue == nil { + out.append("\(path) has no single string type") + } + } + return out + } + + /// Every schema node reachable from `schema` through a schema position: the node itself, + /// the values of `properties`, `items` (object or tuple form) and `additionalProperties`. + /// Data keywords (`default`, `enum`, `const`, `examples`) are never entered. + static func nodes(_ schema: JSONValue, path: String) -> [(String, [String: JSONValue])] { + guard case .object(let node) = schema else { return [] } + var out: [(String, [String: JSONValue])] = [(path, node)] + for (name, sub) in (node["properties"]?.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) { + out += nodes(sub, path: "\(path).properties.\(name)") + } + if let items = node["items"] { + if let tuple = items.arrayValue { + for (i, sub) in tuple.enumerated() { out += nodes(sub, path: "\(path).items[\(i)]") } + } else { + out += nodes(items, path: "\(path).items") + } + } + if let extra = node["additionalProperties"] { + out += nodes(extra, path: "\(path).additionalProperties") + } + return out + } +} diff --git a/Sources/InstanceMCPCore/Tools/UIActionTool.swift b/Sources/InstanceMCPCore/Tools/UIActionTool.swift index e14f469..35cf109 100644 --- a/Sources/InstanceMCPCore/Tools/UIActionTool.swift +++ b/Sources/InstanceMCPCore/Tools/UIActionTool.swift @@ -73,12 +73,21 @@ public struct UIActionTool: Tool { : "Supported on it: \(supported.joined(separator: ", "))") } /// AX refused the value's type (kAXErrorIllegalArgument) on `set_value`. Not an - /// unsupported action, so the supported list is not shown. - public static func valueTypeRejected(ref: String, role: String, retried: Bool) -> String { + /// unsupported action, so the supported list is not shown. `sent` is the value the caller + /// sent: the text names its type, and a native number or boolean is never described as + /// having no number or boolean form. + public static func valueTypeRejected(ref: String, role: String, sent: UIAttrValue, retried: Bool) -> String { if retried { return "\(ref) (\(role)) rejected the `value` property as text and as a number or boolean (AX error -25201). Take a new ui_snapshot to check the control's current value type" } - return "\(ref) (\(role)) rejected the `value` property's type (AX error -25201). The `value` has no number or boolean form, so it does not fit this control. Take a new ui_snapshot to check the control's value type, then send a `value` of that type" + switch sent { + case .number: + return "\(ref) (\(role)) rejected the `value` property's number type (AX error -25201). This control does not accept a number `value`. Take a new ui_snapshot to check the control's current value" + case .bool: + return "\(ref) (\(role)) rejected the `value` property's boolean type (AX error -25201). This control does not accept a boolean `value`. Take a new ui_snapshot to check the control's current value" + default: + return "\(ref) (\(role)) rejected the `value` property's type (AX error -25201). The `value` is text with no number or boolean form, and this control cannot take text. Take a new ui_snapshot to check the control's current value" + } } public static func unconfirmed(action: String, ref: String, app: String) -> String { "ui_action \(action) [\(ref)]: \(app) did not confirm in time. The action may have happened (a press that opens a dialog or menu often answers late); take a new ui_snapshot to check, and do not repeat it blindly" @@ -170,7 +179,7 @@ public struct UIActionTool: Tool { r.value = .string(s) case .number(let d) where d.isFinite: r.value = .number(d) case .bool(let b): r.value = .bool(b) - default: throw JSONRPCError.invalidParams("value must be a string") + default: throw JSONRPCError.invalidParams("value must be a string, number or boolean") } } else if kind == .setValue { throw JSONRPCError.invalidParams("value is required for set_value") diff --git a/Sources/InstanceMCPCore/UISnapshot/UIAction.swift b/Sources/InstanceMCPCore/UISnapshot/UIAction.swift index bc7293f..b35e3e8 100644 --- a/Sources/InstanceMCPCore/UISnapshot/UIAction.swift +++ b/Sources/InstanceMCPCore/UISnapshot/UIAction.swift @@ -227,7 +227,8 @@ struct UIActionEngine { case .failure(.apiDisabled): throw ToolError(E.notTrusted) // Checked before `isUnsupported`: a refused value type is not a missing action. case .failure(.other(UIAXError.illegalArgumentCode)) where req.action == .setValue: - throw ToolError(E.valueTypeRejected(ref: req.ref, role: role, retried: retriedNative)) + // set_value always carries a value: the guard above rejects a missing one. + throw ToolError(E.valueTypeRejected(ref: req.ref, role: role, sent: req.value ?? .string(""), retried: retriedNative)) case .failure(let err) where err.isUnsupported: throw try unsupported() case .failure(.other(let code)): throw ToolError(E.failed(action: req.action.rawValue, ref: req.ref, code: code)) } diff --git a/Sources/InstanceMCPCore/UpstreamMCP.swift b/Sources/InstanceMCPCore/UpstreamMCP.swift index 56c9f41..986d9c9 100644 --- a/Sources/InstanceMCPCore/UpstreamMCP.swift +++ b/Sources/InstanceMCPCore/UpstreamMCP.swift @@ -45,9 +45,16 @@ public actor UpstreamMCP { o["name"] = .string(prefix + n) return .object(o) } - cachedTools = (Date(), list) + // A tool whose forwarded schema still breaks the shape rules is not served, and its call is + // not routed upstream (UpstreamTool.refusal). The name is logged. + let served = list.filter { t in + guard let why = UpstreamTool.refusal(t) else { return true } + log("upstream \(name): tool \(t["name"]?.stringValue ?? "?") is not served: \(why)") + return false + } + cachedTools = (Date(), served) lastError = nil - return list + return served } catch { lastError = "\(error)" log("upstream \(name): tools/list failed: \(error)") @@ -160,13 +167,30 @@ struct UpstreamTool: Tool { var descriptor: JSONValue { Self.forwardedDescriptor(descriptorValue) } /// A descriptor with `inputSchema` run through `forwardedSchema`. Every field other than - /// `inputSchema` is kept. Used for the upstream tools and for the browser router's tools. + /// `inputSchema` is kept, except that browser_emulate_media's description loses the sentence about + /// null, which option B no longer accepts. Used for the upstream tools and for the browser router's tools. static func forwardedDescriptor(_ descriptor: JSONValue) -> JSONValue { - guard var o = descriptor.objectValue, let schema = o["inputSchema"] else { return descriptor } - o["inputSchema"] = forwardedSchema(name: o["name"]?.stringValue ?? "", schema) + guard var o = descriptor.objectValue else { return descriptor } + let name = o["name"]?.stringValue ?? "" + if let schema = o["inputSchema"] { o["inputSchema"] = forwardedSchema(name: name, schema) } + if name == "browser_emulate_media", let d = o["description"]?.stringValue { + o["description"] = .string(d.replacingOccurrences(of: nullClause, with: "")) + } return .object(o) } + /// The sentence option B removes from browser_emulate_media's description. + private static let nullClause = "; null clears an override" + + /// Why a forwarded descriptor must not be served, or nil. A schema that still has a banned + /// construct, or a `type` array, after `forwardedDescriptor` is refused: the tool is hidden from + /// tools/list and its call is not routed. The reason names the first offending path. + static func refusal(_ descriptor: JSONValue) -> String? { + let served = forwardedDescriptor(descriptor) + return ToolSchemaShape.problems(served["inputSchema"] ?? ["type": "object"], + root: served["name"]?.stringValue ?? "?").first + } + /// browser_emulate_media's five overrides are `anyOf: [enum string, null]`, a union that strict /// MCP clients drop (#145). Only that branch is kept: each property becomes its plain enum /// string. Owner decision on PR #146 (option B): clients can no longer send null to clear diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 3cd03dc..5e1e83e 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -10,45 +10,12 @@ import XCTest /// Linux daemon's list in tool_schema_shape_tests.rs. final class ToolSchemaShapeTests: XCTestCase { /// Keywords no guarded schema may use at a schema position. - static let banned: Set = ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"] - - /// Every schema node reachable from `schema` through a schema position: the node itself, - /// the values of `properties`, `items` (object or tuple form) and `additionalProperties`. - /// Data keywords (`default`, `enum`, `const`, `examples`) are never entered, so a payload - /// that happens to contain `anyOf` is not a finding. A property named `not` is a name, not - /// a keyword: only the values under `properties` are walked. - static func schemaNodes(_ schema: JSONValue, path: String) -> [(String, [String: JSONValue])] { - guard case .object(let node) = schema else { return [] } - var out: [(String, [String: JSONValue])] = [(path, node)] - for (name, sub) in (node["properties"]?.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) { - out += schemaNodes(sub, path: "\(path).properties.\(name)") - } - if let items = node["items"] { - if let tuple = items.arrayValue { - for (i, sub) in tuple.enumerated() { out += schemaNodes(sub, path: "\(path).items[\(i)]") } - } else { - out += schemaNodes(items, path: "\(path).items") - } - } - if let extra = node["additionalProperties"] { - out += schemaNodes(extra, path: "\(path).additionalProperties") - } - return out - } + static let banned: Set = ToolSchemaShape.banned - /// Findings for one guarded schema, by path: a banned keyword, a `type` array, or a schema - /// position without one plain `type` string. + /// Findings for one guarded schema, by path. The rules live in `ToolSchemaShape`, the same code the + /// runtime uses to refuse a forwarded tool. static func problems(_ schema: JSONValue, root: String) -> [String] { - var out: [String] = [] - for (path, node) in schemaNodes(schema, path: root) { - for k in node.keys.sorted() where banned.contains(k) { out.append("\(path).\(k)") } - if node["type"]?.arrayValue != nil { - out.append("\(path).type is an array") - } else if node["type"]?.stringValue == nil { - out.append("\(path) has no single string type") - } - } - return out + ToolSchemaShape.problems(schema, root: root) } /// A one-property object schema whose property `a` carries `keyword`. diff --git a/Tests/InstanceMCPCoreTests/UIActionTests.swift b/Tests/InstanceMCPCoreTests/UIActionTests.swift index ec0954f..fce0744 100644 --- a/Tests/InstanceMCPCoreTests/UIActionTests.swift +++ b/Tests/InstanceMCPCoreTests/UIActionTests.swift @@ -360,7 +360,7 @@ final class UIActionToolTests: XCTestCase { // mismatch, not as an unsupported action, and the supported list is not shown. let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "hello"]) XCTAssertTrue(r.isToolError) - XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: false)) + XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", sent: .string("hello"), retried: false)) XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's type (AX error -25201). The `value` is text with no number or boolean form, and this control cannot take text. Take a new ui_snapshot to check the control's current value") XCTAssertFalse(r.text.contains("JSON"), r.text) XCTAssertFalse(r.text.contains("does not support"), r.text) @@ -402,14 +402,14 @@ final class UIActionToolTests: XCTestCase { f.textArea.setError = .other(UIAXError.illegalArgumentCode) let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "3"]) XCTAssertTrue(r.isToolError) - XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: true)) + XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", sent: .string("3"), retried: true)) XCTAssertFalse(r.text.contains("3"), "the value is never echoed: \(r.text)") assertNothingDone(f) } func testValueTypeRejectedNamesTheValueField() { for retried in [false, true] { - let text = UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", retried: retried) + let text = UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", sent: .string("3"), retried: retried) XCTAssertTrue(text.contains("the `value` property"), text) } } diff --git a/docs/ui-tools.md b/docs/ui-tools.md index 065224b..f6060bc 100644 --- a/docs/ui-tools.md +++ b/docs/ui-tools.md @@ -9,10 +9,9 @@ has the summary. Both tools are macOS only; the Linux AT-SPI port is deferred Accessibility tree of a native app's window (AXUIElement), read-only. `owner` only. - **Target.** Default: the frontmost app's focused window. `app` (bundle id or name) or `pid` - selects an app. Windows are matched by title only: `window` (a title string) or `all_windows` - selects windows. Strict clients can only send a title, so they cannot pick an untitled or - duplicate-title window by index. A native JSON integer in `window` still selects an index for - existing callers (#145). + selects an app. `window` (a title string) or `all_windows` selects windows. Strict clients match + windows by title only, so they cannot pick an untitled or duplicate-title window by index. A + native JSON integer in `window` is still read as an index for existing callers (#145). `include_menu_bar` also walks the app's menu bar, so menu items get refs. - **Per node.** Role, subrole, title, value (secure fields always masked), state, frame in display points (the `screenshot`/`mouse` space, with display index), and a `ref` valid within @@ -31,7 +30,7 @@ Acts on a `ui_snapshot` node by ref through the Accessibility API, without movin - **Arguments.** `snapshot_id` + `ref` + `action`. - **Actions.** - `press` (AXPress). - - `set_value` (AXValue, with `value`, advertised and passed as a string, e.g. `"3"` or `"true"`; existing callers' native JSON number or bool are still accepted; replaces the whole value). + - `set_value` (AXValue, with `value`, advertised and passed as a string, e.g. `"3"` or `"true"`; existing callers' native JSON number or bool are still accepted; replaces the whole value). A string the control refuses (AX error -25201) is retried once as the native number or boolean it spells, and only if that also refuses does the call fail with the value-type error. A refused write changes nothing. - `focus` (sets AXFocused; never raises a window; refused where AXFocused is not settable). - `show_menu`, `confirm`, `cancel`, `increment`, `decrement`. - **Unsupported actions.** An action the element does not support is refused before anything is diff --git a/poc/reverse-attach-linux/src/main.rs b/poc/reverse-attach-linux/src/main.rs index 7d2a0c7..e0b19f2 100644 --- a/poc/reverse-attach-linux/src/main.rs +++ b/poc/reverse-attach-linux/src/main.rs @@ -45,6 +45,7 @@ mod procnet; #[cfg(test)] mod profile_conformance; mod run_record; +mod schema_shape; mod sigstop; mod state; mod stdio_client; diff --git a/poc/reverse-attach-linux/src/mcp.rs b/poc/reverse-attach-linux/src/mcp.rs index 31f9c5e..c91f09f 100644 --- a/poc/reverse-attach-linux/src/mcp.rs +++ b/poc/reverse-attach-linux/src/mcp.rs @@ -181,25 +181,58 @@ pub(crate) fn upstream_tools_for_with( let mut out = Vec::new(); for up in ups { for t in up.tools() { - let Some(name) = t.get("name").and_then(|n| n.as_str()) else { + let descriptor = forwarded_descriptor(t); + let Some(name) = descriptor.get("name").and_then(|n| n.as_str()) else { continue; }; if local_names.contains(&name) || !upstream_tool_allowed(name, profile) { continue; } - out.push((up.clone(), forwarded_descriptor(t))); + if let Some(why) = schema_refusal(&descriptor) { + eprintln!("upstream tool {name} is not served: {why}"); + continue; + } + out.push((up.clone(), descriptor)); } } out } +/// Why a forwarded descriptor must not be served, or nil: its inputSchema still has a banned +/// construct or a non-plain `type`. Takes the descriptor after `forwarded_descriptor`. A descriptor +/// without an inputSchema is checked as an empty object schema, as on the Swift side. +pub(crate) fn schema_refusal(descriptor: &Value) -> Option { + let name = descriptor + .get("name") + .and_then(Value::as_str) + .unwrap_or("?"); + let schema = descriptor + .get("inputSchema") + .cloned() + .unwrap_or_else(|| json!({ "type": "object" })); + crate::schema_shape::problems(&schema, name) + .into_iter() + .next() +} + +/// The sentence option B removes from browser_emulate_media's description. +const NULL_CLAUSE: &str = "; null clears an override"; + /// browser_emulate_media's five overrides are `anyOf: [enum string, null]` upstream (#145). Option B -/// (owner decision, PR #146): only the string branch is kept, so each property becomes its plain enum. -/// Mirrors `UpstreamTool.forwardedDescriptor` on the Swift side. Every other descriptor passes unchanged. +/// (owner decision, PR #146): only the string branch is kept, so each property becomes its plain enum, +/// and the description drops the sentence about null. Mirrors `UpstreamTool.forwardedDescriptor` on +/// the Swift side. Every other descriptor passes unchanged. pub(crate) fn forwarded_descriptor(mut t: Value) -> Value { if t.get("name").and_then(Value::as_str) != Some("browser_emulate_media") { return t; } + let description = t + .get("description") + .and_then(Value::as_str) + .map(|d| d.replace(NULL_CLAUSE, "")); + if let Some(d) = description { + t["description"] = Value::String(d); + } let Some(props) = t .get_mut("inputSchema") .and_then(|s| s.get_mut("properties")) @@ -240,7 +273,18 @@ pub(crate) fn upstream_owning_with( if !upstream_tool_allowed(name, profile) { return None; } - ups.iter().find(|up| up.owns(name)).cloned() + ups.iter() + .find(|up| up.owns(name) && !refused_upstream_tool(up, name)) + .cloned() +} + +/// True when `up` lists `name` and its forwarded schema is refused. Such a tool is neither served nor +/// routed, so a call to it is not sent upstream. +fn refused_upstream_tool(up: &Arc, name: &str) -> bool { + up.tools().iter().any(|t| { + t.get("name").and_then(Value::as_str) == Some(name) + && schema_refusal(&forwarded_descriptor(t.clone())).is_some() + }) } // --------------------------------------------------------------------------- diff --git a/poc/reverse-attach-linux/src/schema_shape.rs b/poc/reverse-attach-linux/src/schema_shape.rs new file mode 100644 index 0000000..aba4b06 --- /dev/null +++ b/poc/reverse-attach-linux/src/schema_shape.rs @@ -0,0 +1,69 @@ +//! The schema rules every tool this daemon serves must meet. Some MCP clients (Grok's connector, +//! many function-calling validators) drop a tool whose input schema uses a union, a negation or a +//! reference keyword, or a `type` array, at any depth. Every schema position must carry one plain +//! `type` string. `mcp::upstream_tools_for_with` uses these rules to refuse a forwarded tool that +//! breaks them. Mirrors `ToolSchemaShape` on the Swift side. + +use serde_json::Value; + +/// Keywords no served schema may use at a schema position. +pub(crate) const BANNED: &[&str] = &[ + "anyOf", + "oneOf", + "allOf", + "not", + "$ref", + "$defs", + "definitions", +]; + +/// Schema positions under `schema`, as (path, node): the node itself, the values of +/// `properties`, `items` (object or tuple form) and `additionalProperties`. Data keywords +/// (`default`, `enum`, `const`, `examples`) are never entered, and a property named like a +/// keyword is a name, not a keyword. +fn schema_nodes<'a>(schema: &'a Value, path: String, out: &mut Vec<(String, &'a Value)>) { + if !schema.is_object() { + return; + } + out.push((path.clone(), schema)); + if let Some(props) = schema.get("properties").and_then(Value::as_object) { + for (name, sub) in props { + schema_nodes(sub, format!("{path}.properties.{name}"), out); + } + } + match schema.get("items") { + Some(Value::Array(tuple)) => { + for (i, sub) in tuple.iter().enumerate() { + schema_nodes(sub, format!("{path}.items[{i}]"), out); + } + } + Some(items) => schema_nodes(items, format!("{path}.items"), out), + None => {} + } + if let Some(extra) = schema.get("additionalProperties") { + schema_nodes(extra, format!("{path}.additionalProperties"), out); + } +} + +/// Findings for one schema, by path. An empty result means the schema passes. +pub(crate) fn problems(schema: &Value, root: &str) -> Vec { + if !schema.is_object() { + return vec![format!("{root} is not an object schema")]; + } + let mut nodes = Vec::new(); + schema_nodes(schema, root.to_string(), &mut nodes); + let mut out = Vec::new(); + for (path, node) in nodes { + for keyword in BANNED { + if node.get(*keyword).is_some() { + out.push(format!("{path}.{keyword}")); + } + } + match node.get("type") { + Some(Value::String(_)) => {} + Some(Value::Array(_)) => out.push(format!("{path}.type is an array")), + _ => out.push(format!("{path} has no single string type")), + } + } + out +} diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index 6a9c2ea..5f038b4 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -11,68 +11,7 @@ use serde_json::{json, Value}; use crate::backend::{BackendStatus, Upstream}; use crate::mcp::{tool_list_with, upstream_owning_with, upstream_tools_for_with}; - -/// Keywords no guarded schema may use at a schema position. -const BANNED: &[&str] = &[ - "anyOf", - "oneOf", - "allOf", - "not", - "$ref", - "$defs", - "definitions", -]; - -/// Schema positions under `schema`, as (path, node): the node itself, the values of -/// `properties`, `items` (object or tuple form) and `additionalProperties`. Data keywords -/// (`default`, `enum`, `const`, `examples`) are never entered, and a property named like a -/// keyword is a name, not a keyword. -fn schema_nodes<'a>(schema: &'a Value, path: String, out: &mut Vec<(String, &'a Value)>) { - if !schema.is_object() { - return; - } - out.push((path.clone(), schema)); - if let Some(props) = schema.get("properties").and_then(Value::as_object) { - for (name, sub) in props { - schema_nodes(sub, format!("{path}.properties.{name}"), out); - } - } - match schema.get("items") { - Some(Value::Array(tuple)) => { - for (i, sub) in tuple.iter().enumerate() { - schema_nodes(sub, format!("{path}.items[{i}]"), out); - } - } - Some(items) => schema_nodes(items, format!("{path}.items"), out), - None => {} - } - if let Some(extra) = schema.get("additionalProperties") { - schema_nodes(extra, format!("{path}.additionalProperties"), out); - } -} - -/// Findings for one guarded schema, by path. An empty result means the schema passes. -fn problems(schema: &Value, root: &str) -> Vec { - if !schema.is_object() { - return vec![format!("{root} is not an object schema")]; - } - let mut nodes = Vec::new(); - schema_nodes(schema, root.to_string(), &mut nodes); - let mut out = Vec::new(); - for (path, node) in nodes { - for keyword in BANNED { - if node.get(*keyword).is_some() { - out.push(format!("{path}.{keyword}")); - } - } - match node.get("type") { - Some(Value::String(_)) => {} - Some(Value::Array(_)) => out.push(format!("{path}.type is an array")), - _ => out.push(format!("{path} has no single string type")), - } - } - out -} +use crate::schema_shape::{problems, BANNED}; /// A schema `{type: object, properties: {a: {type: string, : value}}}`. fn with_property_keyword(keyword: &str, value: Value) -> Value { From 79ea45a7ae22fe9c4a42e413f5edd0b6222b2692 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:18:26 -0500 Subject: [PATCH 15/26] Revert "test(schema): cover runtime refusal, native value wording and emulate description" This reverts commit d4297ef3fb19b9047383e8e3475c7ccb6f604b45. --- .../ToolSchemaShapeTests.swift | 69 ------------------- 1 file changed, 69 deletions(-) diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 5e1e83e..9e75ef1 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -170,8 +170,6 @@ final class ToolSchemaShapeTests: XCTestCase { let text = String(decoding: (try? JSONCoding.encoder.encode(schema)) ?? Data(), as: UTF8.self) XCTAssertFalse(text.contains("anyOf"), "served browser_emulate_media schema still has anyOf", file: file, line: line) XCTAssertEqual(problems(schema, root: "browser_emulate_media"), [], "served schema uses a banned construct", file: file, line: line) - let description = entry["description"]?.stringValue ?? "" - XCTAssertFalse(description.contains("null"), "served browser_emulate_media description still mentions null: \(description)", file: file, line: line) for (key, values) in emulateMediaEnums { let prop = schema["properties"]?[key] XCTAssertEqual(prop?["type"]?.stringValue, "string", "\(key) is not a plain string", file: file, line: line) @@ -206,73 +204,6 @@ final class ToolSchemaShapeTests: XCTestCase { } } - // Runtime refusal (finding 1). A forwarded schema that still carries a banned construct is hidden - // from tools/list and cannot be called, on the upstream path and on the browser router path. Option B - // covers browser_emulate_media only, so these fixtures use other names. - - private static func rawTool(_ name: String, _ inputSchema: JSONValue) -> JSONValue { - ["name": .string(name), "description": "fixture", "inputSchema": inputSchema] - } - - private static let bannedUpstreamTools: [JSONValue] = [ - rawTool("browser_union", ["type": "object", "properties": ["x": ["type": "string", - "anyOf": [["type": "string"], ["type": "null"]]]]]), - rawTool("browser_ref", ["type": "object", "properties": ["x": ["$ref": "#/$defs/x"]]]), - rawTool("browser_defs", ["type": "object", "$defs": ["x": ["type": "string"]], - "properties": ["x": ["type": "string"]]]), - ] - - func testServedToolsListHidesUpstreamToolsWithBannedSchemas() async throws { - let up = try FakeUpstream(descriptors: [Self.descriptor("browser_navigate", ["url": Self.plain("string")], required: ["url"])] - + Self.bannedUpstreamTools) - defer { up.stop() } - let server = MCPServer(name: "t", version: "0", tools: [], - upstreams: [UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:\(up.port)/mcp")!)]) - let names = listedNames(try await serverRequest(server, "tools/list")) - XCTAssertTrue(names.contains("browser_navigate"), "\(names)") - for name in ["browser_union", "browser_ref", "browser_defs"] { - XCTAssertFalse(names.contains(name), "\(name) is served with a banned schema: \(names)") - } - } - - func testUpstreamToolWithBannedSchemaIsNotCalled() async throws { - let up = try FakeUpstream(descriptors: Self.bannedUpstreamTools) - defer { up.stop() } - let server = MCPServer(name: "t", version: "0", tools: [], - upstreams: [UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:\(up.port)/mcp")!)]) - _ = try await serverRequest(server, "tools/call", params: ["name": "browser_union", "arguments": [:]]) - XCTAssertTrue(up.calls.isEmpty, "the upstream ran browser_union, whose schema is refused") - } - - func testBrowserRouterHidesToolWithBannedSchema() async throws { - let backend = FakeBrowserBackend(.playwright) - backend.served = [Self.rawTool("browser_navigate", ["type": "object", "properties": ["x": ["type": "string", - "anyOf": [["type": "string"], ["type": "null"]]]]]), - Self.rawTool("browser_snapshot", ["type": "object"])] - let server = MCPServer(name: "t", version: "0", tools: [], - browser: BrowserRouter(playwright: backend, store: MemoryPreferenceStore())) - let names = listedNames(try await serverRequest(server, "tools/list")) - XCTAssertTrue(names.contains("browser_snapshot"), "\(names)") - XCTAssertFalse(names.contains("browser_navigate"), "browser_navigate is served with a banned schema: \(names)") - } - - func testBrowserRouterRefusesCallToToolWithBannedSchema() async { - let backend = FakeBrowserBackend(.playwright) - backend.served = [Self.rawTool("browser_navigate", ["type": "object", "properties": ["x": ["$ref": "#/$defs/x"]]])] - let router = BrowserRouter(playwright: backend, store: MemoryPreferenceStore()) - let result = await router.call("browser_navigate", arguments: [:], BrowserConnection(key: "c1")) - XCTAssertEqual(result["isError"]?.boolValue, true, "\(result)") - XCTAssertTrue(backend.calls.isEmpty, "the backend ran browser_navigate, whose schema is refused") - } - - func testForwardedEmulateMediaDescriptionDoesNotMentionNull() throws { - let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) - let d = try XCTUnwrap(Self.recordedUpstreamTools().first { $0["name"]?.stringValue == "browser_emulate_media" }) - let served = UpstreamTool(descriptorValue: d, upstream: upstream).descriptor["description"]?.stringValue ?? "" - XCTAssertFalse(served.contains("null"), "served description still mentions null: \(served)") - XCTAssertTrue(served.contains("Omitted parameters are left unchanged"), served) - } - // One test per banned keyword, so deleting an entry from `banned` fails its own test. func testBannedSetIsExactlyTheSevenKeywords() { From 175278c1c0f895536f88fbc1b6a08dfd1e63c294 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:18:55 -0500 Subject: [PATCH 16/26] style: rustfmt tool_schema_shape_tests.rs Ran: cargo fmt --check in poc/reverse-attach-linux, passes after this commit. --- poc/reverse-attach-linux/src/tool_schema_shape_tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index 5f038b4..55fbd7e 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -348,7 +348,10 @@ fn forwarded_upstream_list_refuses_banned_tools_and_keeps_recorded_tools() { .filter_map(|(_, t)| t["name"].as_str()) .collect(); for name in &recorded { - assert!(names.contains(&name.as_str()), "{name} was dropped: {names:?}"); + assert!( + names.contains(&name.as_str()), + "{name} was dropped: {names:?}" + ); } for name in BANNED_NAMES { assert!(!names.contains(&name), "{name} is forwarded: {names:?}"); From b308f145a708e66bd3fe060385ef37ebbed16336 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:01:47 -0500 Subject: [PATCH 17/26] fix(schema): F1 prefix-aware emulate rewrite, F2 refuse null overrides at call F1 (review of PR #146): browser_emulate_media was matched on the prefixed name, so an upstream with a non-empty prefix kept its anyOf schema. The upstream tools() now forwards each descriptor on the upstream's own name and adds the prefix afterwards. F2: the served schema dropped null but tools/call still forwarded it. An explicit null for colorScheme, reducedMotion, forcedColors, contrast or media is now refused at the call on three paths: UpstreamMCP.call (Swift), BrowserRouter.call (Swift), and handle_tool_call_with (Linux). The reason names the key, never the value. No existing test sent null, so the refusal is kept rather than documented as advertised-only. Tests added or changed: - ToolSchemaShapeTests: testServedToolsListCarriesOptionBUnderAPrefix (F1), testNullEmulateMediaOverrideIsRefusedOnTheBrowserRouter (F2) - UpstreamMCPTests: testNullEmulateMediaOverrideIsRefusedBeforeTheUpstreamSeesIt (F2, prefixed name) - tool_schema_shape_tests.rs: emulate_media_null_override_is_refused_before_the_upstream_call, emulate_media_enum_value_still_reaches_the_upstream (F2) No test was run on this laptop; Swift and Rust verification runs on the other hosts. --- .../Browser/BrowserRouter.swift | 3 + Sources/InstanceMCPCore/UpstreamMCP.swift | 23 ++++++- .../ToolSchemaShapeTests.swift | 34 ++++++++-- .../UpstreamMCPTests.swift | 11 ++++ poc/reverse-attach-linux/src/mcp.rs | 30 ++++++++- .../src/tool_schema_shape_tests.rs | 65 ++++++++++++++++++- 6 files changed, 156 insertions(+), 10 deletions(-) diff --git a/Sources/InstanceMCPCore/Browser/BrowserRouter.swift b/Sources/InstanceMCPCore/Browser/BrowserRouter.swift index 7a402c5..bc9d58a 100644 --- a/Sources/InstanceMCPCore/Browser/BrowserRouter.swift +++ b/Sources/InstanceMCPCore/Browser/BrowserRouter.swift @@ -106,6 +106,9 @@ public actor BrowserRouter { return Self.errorResult("\(name) is not available with the \(backend.id.rawValue) backend. " + "Install Playwright or select it in OpenAB Computer, Browser tools.", backend: backend.id) } + if let why = UpstreamTool.nullOverrideRefusal(name, arguments) { + return Self.errorResult(why, backend: backend.id) + } last[conn.key] = (backend.id, clock()) do { let r = try await backend.call(name, arguments: arguments) diff --git a/Sources/InstanceMCPCore/UpstreamMCP.swift b/Sources/InstanceMCPCore/UpstreamMCP.swift index 986d9c9..cca221f 100644 --- a/Sources/InstanceMCPCore/UpstreamMCP.swift +++ b/Sources/InstanceMCPCore/UpstreamMCP.swift @@ -41,7 +41,10 @@ public actor UpstreamMCP { do { let r = try await rpc("tools/list", params: nil) let list = (r["result"]?["tools"]?.arrayValue ?? []).map { t -> JSONValue in - guard var o = t.objectValue, let n = o["name"]?.stringValue else { return t } + // Forwarded on the upstream's own name, before the prefix is added, so a prefix cannot make + // a schema rewrite miss (browser_emulate_media). + let forwarded = UpstreamTool.forwardedDescriptor(t) + guard var o = forwarded.objectValue, let n = o["name"]?.stringValue else { return forwarded } o["name"] = .string(prefix + n) return .object(o) } @@ -66,6 +69,7 @@ public actor UpstreamMCP { /// Forward a `tools/call`. `name` is the prefixed name the caller used. public func call(_ name: String, arguments: JSONValue) async throws -> JSONValue { let upstreamName = name.hasPrefix(prefix) ? String(name.dropFirst(prefix.count)) : name + if let why = UpstreamTool.nullOverrideRefusal(upstreamName, arguments) { throw JSONRPCError.invalidParams(why) } let r = try await rpc("tools/call", params: ["name": .string(upstreamName), "arguments": arguments]) if let e = r["error"] { throw JSONRPCError(code: e["code"]?.intValue ?? -32000, message: e["message"]?.stringValue ?? "upstream error") } return r["result"] ?? .null @@ -193,8 +197,8 @@ struct UpstreamTool: Tool { /// browser_emulate_media's five overrides are `anyOf: [enum string, null]`, a union that strict /// MCP clients drop (#145). Only that branch is kept: each property becomes its plain enum - /// string. Owner decision on PR #146 (option B): clients can no longer send null to clear - /// these overrides. Every other upstream schema is forwarded unchanged. + /// string. Owner decision on PR #146 (option B): the served schema no longer offers null, and + /// `nullOverrideRefusal` refuses a null at the call. Every other upstream schema is forwarded unchanged. static func forwardedSchema(name: String, _ schema: JSONValue) -> JSONValue { guard name == "browser_emulate_media", var root = schema.objectValue, var props = root["properties"]?.objectValue else { return schema } @@ -210,6 +214,19 @@ struct UpstreamTool: Tool { return .object(root) } + /// The five browser_emulate_media overrides, which take a string from their enum (option B). + static let emulateMediaOverrides = ["colorScheme", "reducedMotion", "forcedColors", "contrast", "media"] + + /// Why a `tools/call` must not be forwarded, or nil: browser_emulate_media's overrides are not + /// nullable any more, so an explicit null is refused before anything is sent. The reason names + /// the key, never the value. Shared by the upstream path and the browser router. + static func nullOverrideRefusal(_ name: String, _ arguments: JSONValue) -> String? { + guard name == "browser_emulate_media", let args = arguments.objectValue, + let key = emulateMediaOverrides.first(where: { args[$0]?.isNull == true }) + else { return nil } + return "browser_emulate_media: \(key) cannot be null; omit it or send one of its enum values" + } + func call(arguments: JSONValue) async throws -> ToolResult { let r = try await upstream.call(name, arguments: arguments) // Pass the upstream's result through verbatim: content blocks, isError, diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 9e75ef1..2942dc6 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -162,14 +162,15 @@ final class ToolSchemaShapeTests: XCTestCase { /// Checks the browser_emulate_media entry of a `tools/list` result as a client receives it: /// no anyOf anywhere, and each of the five overrides is a plain string enum with no null. - static func assertServedOptionB(_ result: JSONValue?, file: StaticString = #filePath, line: UInt = #line) { - guard let entry = result?["tools"]?.arrayValue?.first(where: { $0["name"]?.stringValue == "browser_emulate_media" }) else { - return XCTFail("browser_emulate_media is not in tools/list", file: file, line: line) + static func assertServedOptionB(_ result: JSONValue?, name: String = "browser_emulate_media", + file: StaticString = #filePath, line: UInt = #line) { + guard let entry = result?["tools"]?.arrayValue?.first(where: { $0["name"]?.stringValue == name }) else { + return XCTFail("\(name) is not in tools/list", file: file, line: line) } let schema = entry["inputSchema"] ?? .null let text = String(decoding: (try? JSONCoding.encoder.encode(schema)) ?? Data(), as: UTF8.self) - XCTAssertFalse(text.contains("anyOf"), "served browser_emulate_media schema still has anyOf", file: file, line: line) - XCTAssertEqual(problems(schema, root: "browser_emulate_media"), [], "served schema uses a banned construct", file: file, line: line) + XCTAssertFalse(text.contains("anyOf"), "served \(name) schema still has anyOf", file: file, line: line) + XCTAssertEqual(problems(schema, root: name), [], "served schema uses a banned construct", file: file, line: line) for (key, values) in emulateMediaEnums { let prop = schema["properties"]?[key] XCTAssertEqual(prop?["type"]?.stringValue, "string", "\(key) is not a plain string", file: file, line: line) @@ -187,6 +188,15 @@ final class ToolSchemaShapeTests: XCTestCase { Self.assertServedOptionB(try await serverRequest(server, "tools/list")?.result) } + // F1: the rewrite is decided on the upstream's own name, so a non-empty prefix still gets option B. + func testServedToolsListCarriesOptionBUnderAPrefix() async throws { + let up = try FakeUpstream(descriptors: try Self.recordedUpstreamTools()); defer { up.stop() } + let server = MCPServer(name: "t", version: "0", tools: [], + upstreams: [UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:\(up.port)/mcp")!, + prefix: "pw_")]) + Self.assertServedOptionB(try await serverRequest(server, "tools/list")?.result, name: "pw_browser_emulate_media") + } + // The real tools/list handler, on the browser router path (Playwright backend, recorded list). func testServedToolsListCarriesOptionBForBrowserRouterEmulateMedia() async throws { let backend = FakeBrowserBackend(.playwright) @@ -196,6 +206,20 @@ final class ToolSchemaShapeTests: XCTestCase { Self.assertServedOptionB(try await serverRequest(server, "tools/list")?.result) } + // F2: a null override is refused at the call on the browser router path, before the backend runs. + func testNullEmulateMediaOverrideIsRefusedOnTheBrowserRouter() async throws { + let backend = FakeBrowserBackend(.playwright) + backend.served = try Self.recordedUpstreamTools() + let server = MCPServer(name: "t", version: "0", tools: [], + browser: BrowserRouter(playwright: backend, store: MemoryPreferenceStore())) + let r = try await serverRequest(server, "tools/call", + params: ["name": "browser_emulate_media", "arguments": ["media": .null]]) + XCTAssertEqual(r?.result?["isError"], true) + let text = r?.result?["content"]?.arrayValue?.first?["text"]?.stringValue ?? "" + XCTAssertTrue(text.contains("media cannot be null"), text) + XCTAssertEqual(backend.calls, [], "a refused null reached the browser backend") + } + func testOtherRecordedPlaywrightToolsAreForwardedUnchanged() throws { let upstream = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!) for d in try Self.recordedUpstreamTools() where d["name"]?.stringValue != "browser_emulate_media" { diff --git a/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift b/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift index 4d0b0e2..20db3ec 100644 --- a/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift +++ b/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift @@ -153,6 +153,17 @@ final class UpstreamMCPTests: XCTestCase { XCTAssertEqual(content?[1]["mimeType"]?.stringValue, "image/png") } + func testNullEmulateMediaOverrideIsRefusedBeforeTheUpstreamSeesIt() async throws { + let up = UpstreamMCP(name: "browser", url: URL(string: "http://127.0.0.1:9/mcp")!, prefix: "pw_") + do { + _ = try await up.call("pw_browser_emulate_media", arguments: ["colorScheme": .null]) + XCTFail("a null override was forwarded upstream") + } catch let e as JSONRPCError { + XCTAssertEqual(e.code, JSONRPCError.invalidParams) + XCTAssertEqual(e.message, "Invalid params: browser_emulate_media: colorScheme cannot be null; omit it or send one of its enum values") + } + } + func testDeniedUpstreamToolIsUnknownUnderObserve() async throws { let up = try FakeUpstream(); defer { up.stop() } let s = makeServer(up, profile: .observe) diff --git a/poc/reverse-attach-linux/src/mcp.rs b/poc/reverse-attach-linux/src/mcp.rs index c91f09f..bfac358 100644 --- a/poc/reverse-attach-linux/src/mcp.rs +++ b/poc/reverse-attach-linux/src/mcp.rs @@ -265,6 +265,31 @@ pub(crate) fn forwarded_descriptor(mut t: Value) -> Value { t } +/// The five browser_emulate_media overrides, which take a string from their enum (option B). +const EMULATE_MEDIA_OVERRIDES: [&str; 5] = [ + "colorScheme", + "reducedMotion", + "forcedColors", + "contrast", + "media", +]; + +/// Why a `tools/call` must not be forwarded, or nil: an explicit null for one of +/// browser_emulate_media's overrides (option B: the served schema no longer offers null). +/// Names the key, never the value. Mirrors `UpstreamTool.nullOverrideRefusal` on the Swift side. +pub(crate) fn null_override_refusal(name: &str, arguments: &Value) -> Option { + if name != "browser_emulate_media" { + return None; + } + let key = EMULATE_MEDIA_OVERRIDES + .iter() + .copied() + .find(|key| arguments.get(*key).is_some_and(Value::is_null))?; + Some(format!( + "browser_emulate_media: {key} cannot be null; omit it or send one of its enum values" + )) +} + pub(crate) fn upstream_owning_with( name: &str, profile: &str, @@ -652,7 +677,10 @@ pub(crate) fn handle_tool_call_with( // Not tied to `cancel`: a job outlives the attach that started it. n if JOB_TOOL_NAMES.contains(&n) => crate::jobs::tools::call(n, &arguments), other => match upstream_owning_with(other, profile, ups) { - Some(up) => up.call(other, arguments).map_err(|e| (-32000, e)), + Some(up) => match null_override_refusal(other, &arguments) { + Some(why) => Err((INVALID_PARAMS, format!("Invalid params: {why}"))), + None => up.call(other, arguments).map_err(|e| (-32000, e)), + }, None => Err(( INVALID_PARAMS, format!("Invalid params: unknown tool: {other}"), diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index 55fbd7e..e37b933 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -5,12 +5,16 @@ //! array, at any schema position, and every schema position carries one plain `type` string. //! browser_emulate_media is also pinned to option B, as on the Swift side. +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use serde_json::{json, Value}; use crate::backend::{BackendStatus, Upstream}; -use crate::mcp::{tool_list_with, upstream_owning_with, upstream_tools_for_with}; +use crate::mcp::{ + handle_tool_call_with, tool_list_with, upstream_owning_with, upstream_tools_for_with, + INVALID_PARAMS, +}; use crate::schema_shape::{problems, BANNED}; /// A schema `{type: object, properties: {a: {type: string, : value}}}`. @@ -375,3 +379,62 @@ fn upstream_does_not_own_a_call_to_a_banned_schema_tool() { "a call to a refused tool is routed to the upstream" ); } + +/// An upstream that counts the calls it receives and answers each with an empty result. +struct CountingUpstream { + tools: Vec, + calls: AtomicUsize, +} + +impl Upstream for CountingUpstream { + fn tools(&self) -> Vec { + self.tools.clone() + } + fn call(&self, _name: &str, _arguments: Value) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + Ok(json!({ "content": [] })) + } + fn status(&self) -> BackendStatus { + BackendStatus { + backend: "managed", + reason: String::new(), + containment: String::new(), + display: "", + } + } +} + +/// F2: an explicit null for a browser_emulate_media override is refused at the call, and the +/// upstream never sees it. The reason names the key only. +#[test] +fn emulate_media_null_override_is_refused_before_the_upstream_call() { + let upstream = Arc::new(CountingUpstream { + tools: recorded_tools(), + calls: AtomicUsize::new(0), + }); + let ups: Vec> = vec![upstream.clone()]; + let params = json!({ "name": "browser_emulate_media", + "arguments": { "colorScheme": null, "media": "print" } }); + let refused = handle_tool_call_with(¶ms, "owner", None, &ups); + let err = refused.expect_err("a null override is refused"); + assert_eq!(err.0, INVALID_PARAMS); + assert_eq!( + err.1, + "Invalid params: browser_emulate_media: colorScheme cannot be null; omit it or send one of its enum values" + ); + assert_eq!(upstream.calls.load(Ordering::SeqCst), 0, "a refused call reached the upstream"); +} + +/// The enum values still reach the upstream, so the refusal is only for null. +#[test] +fn emulate_media_enum_value_still_reaches_the_upstream() { + let upstream = Arc::new(CountingUpstream { + tools: recorded_tools(), + calls: AtomicUsize::new(0), + }); + let ups: Vec> = vec![upstream.clone()]; + let params = json!({ "name": "browser_emulate_media", "arguments": { "colorScheme": "dark" } }); + let ok = handle_tool_call_with(¶ms, "owner", None, &ups); + assert!(ok.is_ok(), "{ok:?}"); + assert_eq!(upstream.calls.load(Ordering::SeqCst), 1); +} From a532aecab1732ff122b377ee22328353106b1759 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:02:23 -0500 Subject: [PATCH 18/26] fix(schema): F3 walk every sub-schema keyword, same root rule in Swift and Rust Both walkers recursed only through properties, items and additionalProperties. They now also enter patternProperties, dependentSchemas, prefixItems, propertyNames, contains, if, then and else, so a banned keyword or a missing single string type under any of them is reported. The non-object root rule was already "is not an object schema" on both sides; a Swift test now pins it too. The Playwright fixture still passes: its only propertyNames entry has a plain type. Tests added: - ToolSchemaShapeTests: testWalksPropertyNames, testWalksPatternProperties, testWalksDependentSchemas, testWalksPrefixItems, testWalksContains, testWalksIfThenElse, testNonObjectRootIsRefused - tool_schema_shape_tests.rs: walks_property_names_and_pattern_properties, walks_dependent_schemas_prefix_items_and_contains, walks_if_then_and_else No test was run on this laptop; Swift and Rust verification runs on the other hosts. --- Sources/InstanceMCPCore/ToolSchemaShape.swift | 21 ++++--- .../ToolSchemaShapeTests.swift | 41 +++++++++++++ poc/reverse-attach-linux/src/schema_shape.rs | 35 ++++++++--- .../src/tool_schema_shape_tests.rs | 59 +++++++++++++++++++ 4 files changed, 140 insertions(+), 16 deletions(-) diff --git a/Sources/InstanceMCPCore/ToolSchemaShape.swift b/Sources/InstanceMCPCore/ToolSchemaShape.swift index 458010e..fac84b8 100644 --- a/Sources/InstanceMCPCore/ToolSchemaShape.swift +++ b/Sources/InstanceMCPCore/ToolSchemaShape.swift @@ -25,14 +25,18 @@ enum ToolSchemaShape { return out } - /// Every schema node reachable from `schema` through a schema position: the node itself, - /// the values of `properties`, `items` (object or tuple form) and `additionalProperties`. - /// Data keywords (`default`, `enum`, `const`, `examples`) are never entered. + /// Every schema node reachable from `schema` through a schema position: the node itself, the + /// values of `properties`, `patternProperties` and `dependentSchemas`, `items` (object or tuple + /// form), `prefixItems`, and the single-schema keywords `additionalProperties`, `propertyNames`, + /// `contains`, `if`, `then` and `else`. Data keywords (`default`, `enum`, `const`, `examples`) are + /// never entered. A non-object sub-schema is not a node. static func nodes(_ schema: JSONValue, path: String) -> [(String, [String: JSONValue])] { guard case .object(let node) = schema else { return [] } var out: [(String, [String: JSONValue])] = [(path, node)] - for (name, sub) in (node["properties"]?.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) { - out += nodes(sub, path: "\(path).properties.\(name)") + for key in ["properties", "patternProperties", "dependentSchemas"] { + for (name, sub) in (node[key]?.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) { + out += nodes(sub, path: "\(path).\(key).\(name)") + } } if let items = node["items"] { if let tuple = items.arrayValue { @@ -41,8 +45,11 @@ enum ToolSchemaShape { out += nodes(items, path: "\(path).items") } } - if let extra = node["additionalProperties"] { - out += nodes(extra, path: "\(path).additionalProperties") + for (i, sub) in (node["prefixItems"]?.arrayValue ?? []).enumerated() { + out += nodes(sub, path: "\(path).prefixItems[\(i)]") + } + for key in ["additionalProperties", "propertyNames", "contains", "if", "then", "else"] { + if let sub = node[key] { out += nodes(sub, path: "\(path).\(key)") } } return out } diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 2942dc6..5e28481 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -303,6 +303,47 @@ final class ToolSchemaShapeTests: XCTestCase { XCTAssertEqual(Self.problems(schema, root: "t"), []) } + // F3: the keywords that hold a sub-schema are walked too, so a banned keyword or a missing type there is found. + + func testWalksPropertyNames() { + XCTAssertEqual(Self.problems(fixture("propertyNames", ["type": "string", "anyOf": [["type": "string"]]]), root: "t"), + ["t.properties.a.propertyNames.anyOf"]) + } + + func testWalksPatternProperties() { + XCTAssertEqual(Self.problems(fixture("patternProperties", ["p": ["description": "no type"]]), root: "t"), + ["t.properties.a.patternProperties.p has no single string type"]) + } + + func testWalksDependentSchemas() { + XCTAssertEqual(Self.problems(fixture("dependentSchemas", ["p": ["type": "string", "not": ["type": "string"]]]), root: "t"), + ["t.properties.a.dependentSchemas.p.not"]) + } + + func testWalksPrefixItems() { + XCTAssertEqual(Self.problems(fixture("prefixItems", [["type": "string", "oneOf": [["type": "string"]]]]), root: "t"), + ["t.properties.a.prefixItems[0].oneOf"]) + } + + func testWalksContains() { + XCTAssertEqual(Self.problems(fixture("contains", ["description": "no type"]), root: "t"), + ["t.properties.a.contains has no single string type"]) + } + + func testWalksIfThenElse() { + XCTAssertEqual(Self.problems(fixture("if", ["type": "string", "allOf": [["type": "string"]]]), root: "t"), + ["t.properties.a.if.allOf"]) + XCTAssertEqual(Self.problems(fixture("then", ["description": "no type"]), root: "t"), + ["t.properties.a.then has no single string type"]) + XCTAssertEqual(Self.problems(fixture("else", ["description": "no type"]), root: "t"), + ["t.properties.a.else has no single string type"]) + } + + /// The non-object root rule, the same as the Rust guard's `root_must_be_an_object_schema`. + func testNonObjectRootIsRefused() { + XCTAssertEqual(Self.problems(.bool(true), root: "t"), ["t is not an object schema"]) + } + // The runtime parsers keep the shapes the old schemas allowed, and the new integer field. func testSnapshotWindowAcceptsTitleAndIndex() throws { diff --git a/poc/reverse-attach-linux/src/schema_shape.rs b/poc/reverse-attach-linux/src/schema_shape.rs index aba4b06..c2a412b 100644 --- a/poc/reverse-attach-linux/src/schema_shape.rs +++ b/poc/reverse-attach-linux/src/schema_shape.rs @@ -17,18 +17,21 @@ pub(crate) const BANNED: &[&str] = &[ "definitions", ]; -/// Schema positions under `schema`, as (path, node): the node itself, the values of -/// `properties`, `items` (object or tuple form) and `additionalProperties`. Data keywords -/// (`default`, `enum`, `const`, `examples`) are never entered, and a property named like a -/// keyword is a name, not a keyword. +/// Schema positions under `schema`, as (path, node): the node itself, the values of `properties`, +/// `patternProperties` and `dependentSchemas`, `items` (object or tuple form), `prefixItems`, and +/// the single-schema keywords `additionalProperties`, `propertyNames`, `contains`, `if`, `then` and +/// `else`. Data keywords (`default`, `enum`, `const`, `examples`) are never entered, and a property +/// named like a keyword is a name, not a keyword. A non-object sub-schema is not a node. fn schema_nodes<'a>(schema: &'a Value, path: String, out: &mut Vec<(String, &'a Value)>) { if !schema.is_object() { return; } out.push((path.clone(), schema)); - if let Some(props) = schema.get("properties").and_then(Value::as_object) { - for (name, sub) in props { - schema_nodes(sub, format!("{path}.properties.{name}"), out); + for key in ["properties", "patternProperties", "dependentSchemas"] { + if let Some(map) = schema.get(key).and_then(Value::as_object) { + for (name, sub) in map { + schema_nodes(sub, format!("{path}.{key}.{name}"), out); + } } } match schema.get("items") { @@ -40,8 +43,22 @@ fn schema_nodes<'a>(schema: &'a Value, path: String, out: &mut Vec<(String, &'a Some(items) => schema_nodes(items, format!("{path}.items"), out), None => {} } - if let Some(extra) = schema.get("additionalProperties") { - schema_nodes(extra, format!("{path}.additionalProperties"), out); + if let Some(prefix) = schema.get("prefixItems").and_then(Value::as_array) { + for (i, sub) in prefix.iter().enumerate() { + schema_nodes(sub, format!("{path}.prefixItems[{i}]"), out); + } + } + for key in [ + "additionalProperties", + "propertyNames", + "contains", + "if", + "then", + "else", + ] { + if let Some(sub) = schema.get(key) { + schema_nodes(sub, format!("{path}.{key}"), out); + } } } diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index e37b933..5a2feb0 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -133,6 +133,65 @@ fn property_named_like_a_keyword_is_a_name() { assert_eq!(problems(&schema, "t"), Vec::::new()); } +/// F3: the keywords that hold a sub-schema are walked too. +#[test] +fn walks_property_names_and_pattern_properties() { + let value = json!({ "type": "string", "anyOf": [{ "type": "string" }] }); + let names = with_property_keyword("propertyNames", value); + assert_eq!( + problems(&names, "t"), + vec!["t.properties.a.propertyNames.anyOf".to_string()] + ); + + let value = json!({ "p": { "description": "no type" } }); + let pattern = with_property_keyword("patternProperties", value); + assert_eq!( + problems(&pattern, "t"), + vec!["t.properties.a.patternProperties.p has no single string type".to_string()] + ); +} + +#[test] +fn walks_dependent_schemas_prefix_items_and_contains() { + let value = json!({ "p": { "type": "string", "not": { "type": "string" } } }); + let dependent = with_property_keyword("dependentSchemas", value); + assert_eq!( + problems(&dependent, "t"), + vec!["t.properties.a.dependentSchemas.p.not".to_string()] + ); + + let value = json!([{ "type": "string", "oneOf": [{ "type": "string" }] }]); + let prefix = with_property_keyword("prefixItems", value); + assert_eq!( + problems(&prefix, "t"), + vec!["t.properties.a.prefixItems[0].oneOf".to_string()] + ); + + let contains = with_property_keyword("contains", json!({ "description": "no type" })); + assert_eq!( + problems(&contains, "t"), + vec!["t.properties.a.contains has no single string type".to_string()] + ); +} + +#[test] +fn walks_if_then_and_else() { + let value = json!({ "type": "string", "allOf": [{ "type": "string" }] }); + let branch = with_property_keyword("if", value); + assert_eq!( + problems(&branch, "t"), + vec!["t.properties.a.if.allOf".to_string()] + ); + + for keyword in ["then", "else"] { + let branch = with_property_keyword(keyword, json!({ "description": "no type" })); + assert_eq!( + problems(&branch, "t"), + vec![format!("t.properties.a.{keyword} has no single string type")] + ); + } +} + #[test] fn root_must_be_an_object_schema() { assert_eq!( From 98841dbf4f206c594370c427f84b96003dd24a97 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:03:06 -0500 Subject: [PATCH 19/26] fix(ui): F4 generic -25201 wording for native input, trim before the retry match The -25201 message stated a cause as fact. kAXErrorIllegalArgument is a generic error, so the text now names the likely cause ("The likely cause is a value type this control does not take"). A native JSON number or boolean gets the generic wording, because the input category alone does not say what the control accepts. Text keeps its "no number or boolean form" line, which is true for the strings it is checked against. nativeValue trims surrounding whitespace before matching, so " 3 " and "true\n" retry as native values. Exact-match documentation is not used. docs/ui-tools.md says so. Tests changed or added: - UIActionTests: testValueTypeRejectedForText exact text (hello case), testValueTypeRefusedForNativeNumberGivesTheGenericMessage (renamed), testValueTypeRefusedForNativeBoolGivesTheGenericMessage (renamed), testPaddedNumberStringIsRetriedAsNumber, testNativeFormIgnoresSurroundingWhitespaceOnly No test was run on this laptop; Swift verification runs on the other hosts. --- .../InstanceMCPCore/Tools/UIActionTool.swift | 27 +++++++------- .../InstanceMCPCore/UISnapshot/UIAction.swift | 6 ++-- .../InstanceMCPCoreTests/UIActionTests.swift | 35 +++++++++++++++---- docs/ui-tools.md | 2 +- 4 files changed, 48 insertions(+), 22 deletions(-) diff --git a/Sources/InstanceMCPCore/Tools/UIActionTool.swift b/Sources/InstanceMCPCore/Tools/UIActionTool.swift index 35cf109..56bbfde 100644 --- a/Sources/InstanceMCPCore/Tools/UIActionTool.swift +++ b/Sources/InstanceMCPCore/Tools/UIActionTool.swift @@ -72,22 +72,25 @@ public struct UIActionTool: Tool { (supported.isEmpty ? "No ui_action action is supported on it; use screenshot + mouse" : "Supported on it: \(supported.joined(separator: ", "))") } - /// AX refused the value's type (kAXErrorIllegalArgument) on `set_value`. Not an - /// unsupported action, so the supported list is not shown. `sent` is the value the caller - /// sent: the text names its type, and a native number or boolean is never described as - /// having no number or boolean form. + /// AX refused the value's type (kAXErrorIllegalArgument) on `set_value`. Not an unsupported action, + /// so the supported list is not shown. -25201 is a generic error, so the cause named here is the + /// likely one, not a confirmed one. `sent` selects the wording: text says whether it has a number + /// or boolean form, and a native number or boolean gets the generic wording. The value is never + /// echoed. public static func valueTypeRejected(ref: String, role: String, sent: UIAttrValue, retried: Bool) -> String { + let code = "AX error -25201, a generic illegal-argument error" + let likely = "The likely cause is a value type this control does not take." if retried { - return "\(ref) (\(role)) rejected the `value` property as text and as a number or boolean (AX error -25201). Take a new ui_snapshot to check the control's current value type" + return "\(ref) (\(role)) rejected the `value` property as text and as a number or boolean (\(code)). " + + "\(likely) Take a new ui_snapshot to check the control's current value type" } - switch sent { - case .number: - return "\(ref) (\(role)) rejected the `value` property's number type (AX error -25201). This control does not accept a number `value`. Take a new ui_snapshot to check the control's current value" - case .bool: - return "\(ref) (\(role)) rejected the `value` property's boolean type (AX error -25201). This control does not accept a boolean `value`. Take a new ui_snapshot to check the control's current value" - default: - return "\(ref) (\(role)) rejected the `value` property's type (AX error -25201). The `value` is text with no number or boolean form, and this control cannot take text. Take a new ui_snapshot to check the control's current value" + if case .string = sent { + return "\(ref) (\(role)) rejected the `value` property as text (\(code)). The text has no number " + + "or boolean form to retry as. The likely cause is that this control does not take a text value. " + + "Take a new ui_snapshot to check the control's current value type" } + return "\(ref) (\(role)) rejected the `value` property (\(code)). \(likely) " + + "Take a new ui_snapshot to check the control's current value type" } public static func unconfirmed(action: String, ref: String, app: String) -> String { "ui_action \(action) [\(ref)]: \(app) did not confirm in time. The action may have happened (a press that opens a dialog or menu often answers late); take a new ui_snapshot to check, and do not repeat it blindly" diff --git a/Sources/InstanceMCPCore/UISnapshot/UIAction.swift b/Sources/InstanceMCPCore/UISnapshot/UIAction.swift index b35e3e8..e4631ab 100644 --- a/Sources/InstanceMCPCore/UISnapshot/UIAction.swift +++ b/Sources/InstanceMCPCore/UISnapshot/UIAction.swift @@ -287,9 +287,11 @@ struct UIActionEngine { return ToolResult(content: [.text(text)], structured: .object(o)) } - /// The native number or boolean a string spells (`"3"`, `"true"`), or nil. + /// The native number or boolean a string spells (`"3"`, `"true"`), or nil. Surrounding + /// whitespace is ignored, so `" 3 "` retries as the number 3. static func nativeValue(_ v: UIAttrValue) -> UIAttrValue? { - guard case .string(let s) = v else { return nil } + guard case .string(let raw) = v else { return nil } + let s = raw.trimmingCharacters(in: .whitespacesAndNewlines) if s == "true" { return .bool(true) } if s == "false" { return .bool(false) } if let d = Double(s), d.isFinite { return .number(d) } diff --git a/Tests/InstanceMCPCoreTests/UIActionTests.swift b/Tests/InstanceMCPCoreTests/UIActionTests.swift index fce0744..091c59e 100644 --- a/Tests/InstanceMCPCoreTests/UIActionTests.swift +++ b/Tests/InstanceMCPCoreTests/UIActionTests.swift @@ -351,6 +351,26 @@ final class UIActionToolTests: XCTestCase { XCTAssertEqual(f.textArea.sets.map(\.1), [.bool(true)]) } + func testPaddedNumberStringIsRetriedAsNumber() async { + let f = Fixture() + let id = await f.snapshot() + f.textArea.settable = ["AXValue"] + f.textArea.refusesStrings = true + let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": " 3 "]) + XCTAssertFalse(r.isToolError, r.text) + XCTAssertEqual(f.textArea.sets.map(\.1), [.number(3)]) + } + + func testNativeFormIgnoresSurroundingWhitespaceOnly() { + XCTAssertEqual(UIActionEngine.nativeValue(.string(" 3 ")), .number(3)) + XCTAssertEqual(UIActionEngine.nativeValue(.string("\ttrue\n")), .bool(true)) + XCTAssertEqual(UIActionEngine.nativeValue(.string(" false")), .bool(false)) + XCTAssertNil(UIActionEngine.nativeValue(.string(" "))) + XCTAssertNil(UIActionEngine.nativeValue(.string("3 x"))) + XCTAssertNil(UIActionEngine.nativeValue(.string("nan"))) + XCTAssertNil(UIActionEngine.nativeValue(.number(3))) + } + func testValueTypeRefusalIsNotReportedAsUnsupported() async { let f = Fixture() let id = await f.snapshot() @@ -361,36 +381,37 @@ final class UIActionToolTests: XCTestCase { let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": "hello"]) XCTAssertTrue(r.isToolError) XCTAssertEqual(r.text, UIActionTool.Errors.valueTypeRejected(ref: "e2", role: "AXTextArea", sent: .string("hello"), retried: false)) - XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's type (AX error -25201). The `value` is text with no number or boolean form, and this control cannot take text. Take a new ui_snapshot to check the control's current value") + XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property as text (AX error -25201, a generic illegal-argument error). The text has no number or boolean form to retry as. The likely cause is that this control does not take a text value. Take a new ui_snapshot to check the control's current value type") XCTAssertFalse(r.text.contains("JSON"), r.text) XCTAssertFalse(r.text.contains("does not support"), r.text) XCTAssertFalse(r.text.contains("Supported on it"), r.text) assertNothingDone(f) } - func testValueTypeRefusedForNativeNumberSaysTheControlRefusesNumbers() async { + func testValueTypeRefusedForNativeNumberGivesTheGenericMessage() async { let f = Fixture() let id = await f.snapshot() f.textArea.settable = ["AXValue"] f.textArea.setError = .other(UIAXError.illegalArgumentCode) - // The caller sent a native number, so there is no string form to retry and the message must not - // say the value has no number form. + // The caller sent a native number, which has no string form to retry. -25201 is generic, so the + // message names the likely cause without claiming the control refuses numbers. let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": .number(3)]) XCTAssertTrue(r.isToolError) - XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's number type (AX error -25201). This control does not accept a number `value`. Take a new ui_snapshot to check the control's current value") + XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property (AX error -25201, a generic illegal-argument error). The likely cause is a value type this control does not take. Take a new ui_snapshot to check the control's current value type") XCTAssertFalse(r.text.contains("no number or boolean form"), r.text) + XCTAssertFalse(r.text.contains("does not accept"), r.text) XCTAssertFalse(r.text.contains("3"), "the value is never echoed: \(r.text)") assertNothingDone(f) } - func testValueTypeRefusedForNativeBoolSaysTheControlRefusesBooleans() async { + func testValueTypeRefusedForNativeBoolGivesTheGenericMessage() async { let f = Fixture() let id = await f.snapshot() f.textArea.settable = ["AXValue"] f.textArea.setError = .other(UIAXError.illegalArgumentCode) let r = await f.act(["snapshot_id": .string(id), "ref": "e2", "action": "set_value", "value": .bool(true)]) XCTAssertTrue(r.isToolError) - XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property's boolean type (AX error -25201). This control does not accept a boolean `value`. Take a new ui_snapshot to check the control's current value") + XCTAssertEqual(r.text, "e2 (AXTextArea) rejected the `value` property (AX error -25201, a generic illegal-argument error). The likely cause is a value type this control does not take. Take a new ui_snapshot to check the control's current value type") XCTAssertFalse(r.text.contains("no number or boolean form"), r.text) assertNothingDone(f) } diff --git a/docs/ui-tools.md b/docs/ui-tools.md index f6060bc..96c9364 100644 --- a/docs/ui-tools.md +++ b/docs/ui-tools.md @@ -30,7 +30,7 @@ Acts on a `ui_snapshot` node by ref through the Accessibility API, without movin - **Arguments.** `snapshot_id` + `ref` + `action`. - **Actions.** - `press` (AXPress). - - `set_value` (AXValue, with `value`, advertised and passed as a string, e.g. `"3"` or `"true"`; existing callers' native JSON number or bool are still accepted; replaces the whole value). A string the control refuses (AX error -25201) is retried once as the native number or boolean it spells, and only if that also refuses does the call fail with the value-type error. A refused write changes nothing. + - `set_value` (AXValue, with `value`, advertised and passed as a string, e.g. `"3"` or `"true"`; existing callers' native JSON number or bool are still accepted; replaces the whole value). A string the control refuses (AX error -25201) is retried once as the native number or boolean it spells (surrounding whitespace ignored, so `" 3 "` retries as 3), and only if that also refuses does the call fail with the value-type error. A refused write changes nothing. - `focus` (sets AXFocused; never raises a window; refused where AXFocused is not settable). - `show_menu`, `confirm`, `cancel`, `increment`, `decrement`. - **Unsupported actions.** An action the element does not support is refused before anything is From 8b96d42d98c35f635e0d108557a6704243227bc2 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:03:29 -0500 Subject: [PATCH 20/26] docs(fixtures): F5 README for re-recording the Playwright 0.0.82 tools/list fixture Documents the exact capture: the pinned package from release/playwright-pins, npm ci with the same flags as the pins smoke check, the stdio launch flags named in the fixture's source field, the three JSON-RPC messages, the output path and shape, and the 32-tool count the suites expect. A Node capture script is included. No test was run on this laptop, and the capture procedure was not run here either. --- Tests/Fixtures/README.md | 90 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Tests/Fixtures/README.md diff --git a/Tests/Fixtures/README.md b/Tests/Fixtures/README.md new file mode 100644 index 0000000..b6ddaf3 --- /dev/null +++ b/Tests/Fixtures/README.md @@ -0,0 +1,90 @@ +# Test fixtures + +## playwright-mcp-0.0.82-tools-list.json + +The recorded `tools/list` reply of `@playwright/mcp`, version **0.0.82**. It is the pinned +version in `release/playwright-pins/pins.json` (`mcp.version`). Two test suites read it: + +- `Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift` (Swift) +- `poc/reverse-attach-linux/src/tool_schema_shape_tests.rs` (Rust, via `include_str!`) + +Both expect **32 tools** and check that `browser_emulate_media` is served as option B. + +File shape: a JSON object with a `source` string (what the capture was) and a `result` object. +`result` is the `result` member of the JSON-RPC reply, so it has `tools`. There is no `jsonrpc` +or `id` member. + +### How to re-record + +Capture over stdio from a fresh process. Do not use the running service, and do not pass +`--port`, `--host` or `--allowed-hosts`: the capture needs no network port. + +1. Make a scratch directory and copy the pinned package files into it. Do not edit them. + + ```sh + mkdir -p /tmp/pw-mcp-capture && cd /tmp/pw-mcp-capture + cp /release/playwright-pins/package.json /release/playwright-pins/package-lock.json . + ``` + +2. Install exactly the locked tree. This is the install `scripts/playwright-pins.py` uses, without + install scripts: + + ```sh + npm ci --ignore-scripts --omit=dev --no-audit --no-fund --registry https://registry.npmjs.org/ + ``` + +3. Launch the server over stdio with the flags named in the fixture's `source` field: + `--browser chromium --shared-browser-context --caps vision,pdf --headless`. The entry point is + `node_modules/@playwright/mcp/cli.js`. + +4. Send three newline-delimited JSON-RPC messages on stdin, then read stdout until the reply with + `id` 2 arrives: + + ```json + {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"capture","version":"0"}}} + {"jsonrpc":"2.0","method":"notifications/initialized"} + {"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}} + ``` + +5. Write `{"source": "", "result": }` to + `Tests/Fixtures/playwright-mcp-0.0.82-tools-list.json`, pretty-printed with two-space indent and a + final newline. Set `source` to the same kind of note as the current file: the package version, + the flags, "stdio tools/list", and "a fresh process, not the running service". + + A minimal Node capture script that does steps 3 to 5 and checks the count: + + ```js + // Run from /tmp/pw-mcp-capture: node capture.mjs /Tests/Fixtures/playwright-mcp-0.0.82-tools-list.json + import { spawn } from "node:child_process"; + import { createInterface } from "node:readline"; + import { writeFileSync } from "node:fs"; + + const out = process.argv[2]; + const child = spawn("node", ["node_modules/@playwright/mcp/cli.js", "--browser", "chromium", + "--shared-browser-context", "--caps", "vision,pdf", "--headless"], + { stdio: ["pipe", "pipe", "inherit"] }); + const send = (m) => child.stdin.write(JSON.stringify(m) + "\n"); + createInterface({ input: child.stdout }).on("line", (line) => { + let m; + try { m = JSON.parse(line); } catch { return; } + if (m.id === 1) { + send({ jsonrpc: "2.0", method: "notifications/initialized" }); + send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }); + } + if (m.id === 2) { + const tools = m.result?.tools ?? []; + if (tools.length !== 32) { console.error(`expected 32 tools, got ${tools.length}`); process.exit(1); } + writeFileSync(out, JSON.stringify({ source: "@playwright/mcp@0.0.82 stdio tools/list, flags as ManagedPlaywright (--browser chromium --shared-browser-context --caps vision,pdf --headless); a fresh process, not the running service", result: m.result }, null, 2) + "\n"); + child.kill(); + } + }); + send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "capture", version: "0" } } }); + ``` + +6. Run the Swift and Rust suites on the test hosts. They must pass with the new file. + +### When to re-record + +- The pinned version in `release/playwright-pins/pins.json` changes. Re-record, then update the + tool count (`32`) in both suites if the number of tools changed. +- Do not edit the JSON by hand. Re-record from the pinned package. From 47ff10349b00736de47d87c36e8fc12a781124b7 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:06:43 -0500 Subject: [PATCH 21/26] docs(fixtures): F5 README install uses the pins smoke-check isolation Review B2 on the F5 README: step 2 claimed to be the install that scripts/playwright-pins.py uses, but the command omitted --userconfig, --globalconfig, --cache and HOME. A developer's ~/.npmrc could change the resolved tree, so a re-recorded fixture would not reproduce from the steps. The command now sets empty user and global npmrc files, a scratch cache, and HOME to the scratch directory, matching the smoke check. Tests: none added or changed (documentation only). No test was run on this laptop; Swift and Rust suites run on the test hosts for the pushed head. --- Tests/Fixtures/README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Tests/Fixtures/README.md b/Tests/Fixtures/README.md index b6ddaf3..6176a0e 100644 --- a/Tests/Fixtures/README.md +++ b/Tests/Fixtures/README.md @@ -26,11 +26,15 @@ Capture over stdio from a fresh process. Do not use the running service, and do cp /release/playwright-pins/package.json /release/playwright-pins/package-lock.json . ``` -2. Install exactly the locked tree. This is the install `scripts/playwright-pins.py` uses, without - install scripts: +2. Install exactly the locked tree, isolated from the developer's npm config. This matches the + smoke check in `scripts/playwright-pins.py`: empty user and global npmrc files, a scratch cache, + and `HOME` set to the scratch directory. Install scripts are skipped. ```sh - npm ci --ignore-scripts --omit=dev --no-audit --no-fund --registry https://registry.npmjs.org/ + cd /tmp/pw-mcp-capture && touch user.npmrc global.npmrc && mkdir -p cache + HOME=/tmp/pw-mcp-capture npm ci --ignore-scripts --omit=dev --no-audit --no-fund \ + --userconfig /tmp/pw-mcp-capture/user.npmrc --globalconfig /tmp/pw-mcp-capture/global.npmrc \ + --cache /tmp/pw-mcp-capture/cache --registry https://registry.npmjs.org/ ``` 3. Launch the server over stdio with the flags named in the fixture's `source` field: From c92f9055674b4dc56f1555bf06e40766eda66f7b Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:16:42 -0500 Subject: [PATCH 22/26] style: rustfmt tool_schema_shape_tests.rs (CI cargo fmt --check) CI run 44520868459 on 47ff103 failed both "Linux hands node" format jobs (amd64 and arm64) at `cargo fmt --check`. Two hunks in tool_schema_shape_tests.rs were not wrapped as rustfmt wants: the "has no single string type" format! call (around line 187) and the upstream.calls assert_eq! in the emulate_media null refusal test (around line 481). The change is line wrapping only; no assertion changed. Tests: no test added or changed. No cargo or rustfmt run on this laptop; the formatting was applied by hand from the CI diff. The Rust suite and cargo fmt --check run on the test host for the new head. --- .../src/tool_schema_shape_tests.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index 5a2feb0..b928b0c 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -187,7 +187,9 @@ fn walks_if_then_and_else() { let branch = with_property_keyword(keyword, json!({ "description": "no type" })); assert_eq!( problems(&branch, "t"), - vec![format!("t.properties.a.{keyword} has no single string type")] + vec![format!( + "t.properties.a.{keyword} has no single string type" + )] ); } } @@ -481,7 +483,11 @@ fn emulate_media_null_override_is_refused_before_the_upstream_call() { err.1, "Invalid params: browser_emulate_media: colorScheme cannot be null; omit it or send one of its enum values" ); - assert_eq!(upstream.calls.load(Ordering::SeqCst), 0, "a refused call reached the upstream"); + assert_eq!( + upstream.calls.load(Ordering::SeqCst), + 0, + "a refused call reached the upstream" + ); } /// The enum values still reach the upstream, so the refusal is only for null. From d25cdfba4abf0b827f5328d7409c1d4aaf574bc0 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:27:09 -0500 Subject: [PATCH 23/26] test(backend): down-backend call expects backoff, not start_failed On the F1/F2 branch, refused_upstream_tool() calls Managed::tools() on the call path (mcp.rs upstream_owning_with). With no cached list, tools() starts the child, so a call to a down browser backend makes that start attempt and then the real call hits the backoff window. Behavior change: a call to a down browser backend now returns class "backoff" on the first call, not "start_failed". Each routed call while the backend is down makes one start attempt for the listing. Chosen by the parent (option A): keep the banned- schema refusal on the call path and change this assertion. Tests: changed backend::tests::a_down_backend_answers_with_its_class_not_unknown_tool (expects backoff). main passes this test with start_failed, which is the behavior this commit changes. No cargo or test run on this laptop; the Linux suite runs on the test host for the pushed head. --- poc/reverse-attach-linux/src/backend_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/poc/reverse-attach-linux/src/backend_tests.rs b/poc/reverse-attach-linux/src/backend_tests.rs index 7a75b83..0d3815e 100644 --- a/poc/reverse-attach-linux/src/backend_tests.rs +++ b/poc/reverse-attach-linux/src/backend_tests.rs @@ -301,5 +301,5 @@ fn a_down_backend_answers_with_its_class_not_unknown_tool() { &ups, ) .unwrap_err(); - assert_eq!(err, (-32000, "start_failed".to_string())); + assert_eq!(err, (-32000, "backoff".to_string())); } From 1b90b8b3d0ea66ed4c8145c2e2e5626e0d8b2b07 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:34:32 +0000 Subject: [PATCH 24/26] fix(review): round-4 findings for schema guard and call path - Linux: decide call-path schema refusal from Upstream::cached_tools, never a new tools/list; a down backend answers with start_failed again - refuse an explicit null for any browser_emulate_media argument - collapse an anyOf only when every non-string branch is {type: null} - walk dependencies, additionalItems, unevaluated*, contentSchema, and fail closed on any keyword outside the known vocabulary (Swift + Rust) --- Sources/InstanceMCPCore/ToolSchemaShape.swift | 37 +++- Sources/InstanceMCPCore/UpstreamMCP.swift | 38 ++-- .../ToolSchemaShapeTests.swift | 57 ++++++ poc/reverse-attach-linux/src/backend.rs | 18 ++ poc/reverse-attach-linux/src/backend_tests.rs | 2 +- poc/reverse-attach-linux/src/external.rs | 9 + poc/reverse-attach-linux/src/mcp.rs | 73 ++++---- poc/reverse-attach-linux/src/schema_shape.rs | 112 ++++++++++-- .../src/tool_schema_shape_tests.rs | 173 +++++++++++++++++- 9 files changed, 441 insertions(+), 78 deletions(-) diff --git a/Sources/InstanceMCPCore/ToolSchemaShape.swift b/Sources/InstanceMCPCore/ToolSchemaShape.swift index fac84b8..abb1e10 100644 --- a/Sources/InstanceMCPCore/ToolSchemaShape.swift +++ b/Sources/InstanceMCPCore/ToolSchemaShape.swift @@ -9,13 +9,35 @@ enum ToolSchemaShape { /// Keywords no served schema may use at a schema position. static let banned: Set = ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"] - /// Findings for one schema, by path: a banned keyword, a `type` array, or a schema position - /// without one plain `type` string. Empty when the schema passes. + /// Keywords whose value is a map of name to sub-schema. + static let schemaMaps = ["properties", "patternProperties", "dependentSchemas", "dependencies"] + /// Keywords whose value is one sub-schema. + static let singleSchemas = ["additionalProperties", "additionalItems", "unevaluatedProperties", "unevaluatedItems", + "propertyNames", "contains", "contentSchema", "if", "then", "else"] + + /// Every keyword a schema node may carry: the JSON Schema 2020-12 vocabularies plus the draft-7 + /// keywords (`dependencies`, `additionalItems`, `definitions`, `id`). Anything else is reported, + /// so a keyword this walker does not know cannot hide a sub-schema from it (fail closed). + static let known: Set = banned + .union(schemaMaps).union(singleSchemas) + .union(["$schema", "$id", "id", "$anchor", "$dynamicAnchor", "$dynamicRef", "$recursiveRef", + "$recursiveAnchor", "$comment", "$vocabulary", + "items", "prefixItems", + "type", "enum", "const", "multipleOf", "maximum", "exclusiveMaximum", "minimum", + "exclusiveMinimum", "maxLength", "minLength", "pattern", "maxItems", "minItems", + "uniqueItems", "maxContains", "minContains", "maxProperties", "minProperties", + "required", "dependentRequired", + "title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples", + "format", "contentEncoding", "contentMediaType"]) + + /// Findings for one schema, by path: a banned keyword, an unknown keyword, a `type` array, or a + /// schema position without one plain `type` string. Empty when the schema passes. static func problems(_ schema: JSONValue, root: String) -> [String] { guard schema.objectValue != nil else { return ["\(root) is not an object schema"] } var out: [String] = [] for (path, node) in nodes(schema, path: root) { for k in node.keys.sorted() where banned.contains(k) { out.append("\(path).\(k)") } + for k in node.keys.sorted() where !known.contains(k) { out.append("\(path).\(k) is not a known schema keyword") } if node["type"]?.arrayValue != nil { out.append("\(path).type is an array") } else if node["type"]?.stringValue == nil { @@ -26,14 +48,13 @@ enum ToolSchemaShape { } /// Every schema node reachable from `schema` through a schema position: the node itself, the - /// values of `properties`, `patternProperties` and `dependentSchemas`, `items` (object or tuple - /// form), `prefixItems`, and the single-schema keywords `additionalProperties`, `propertyNames`, - /// `contains`, `if`, `then` and `else`. Data keywords (`default`, `enum`, `const`, `examples`) are - /// never entered. A non-object sub-schema is not a node. + /// values of `schemaMaps`, `items` (object or tuple form), `prefixItems`, and `singleSchemas`. + /// Data keywords (`default`, `enum`, `const`, `examples`) are never entered. A non-object + /// sub-schema is not a node (a boolean schema, or a draft-7 `dependencies` array of names). static func nodes(_ schema: JSONValue, path: String) -> [(String, [String: JSONValue])] { guard case .object(let node) = schema else { return [] } var out: [(String, [String: JSONValue])] = [(path, node)] - for key in ["properties", "patternProperties", "dependentSchemas"] { + for key in schemaMaps { for (name, sub) in (node[key]?.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) { out += nodes(sub, path: "\(path).\(key).\(name)") } @@ -48,7 +69,7 @@ enum ToolSchemaShape { for (i, sub) in (node["prefixItems"]?.arrayValue ?? []).enumerated() { out += nodes(sub, path: "\(path).prefixItems[\(i)]") } - for key in ["additionalProperties", "propertyNames", "contains", "if", "then", "else"] { + for key in singleSchemas { if let sub = node[key] { out += nodes(sub, path: "\(path).\(key)") } } return out diff --git a/Sources/InstanceMCPCore/UpstreamMCP.swift b/Sources/InstanceMCPCore/UpstreamMCP.swift index cca221f..5ba3545 100644 --- a/Sources/InstanceMCPCore/UpstreamMCP.swift +++ b/Sources/InstanceMCPCore/UpstreamMCP.swift @@ -196,16 +196,17 @@ struct UpstreamTool: Tool { } /// browser_emulate_media's five overrides are `anyOf: [enum string, null]`, a union that strict - /// MCP clients drop (#145). Only that branch is kept: each property becomes its plain enum - /// string. Owner decision on PR #146 (option B): the served schema no longer offers null, and - /// `nullOverrideRefusal` refuses a null at the call. Every other upstream schema is forwarded unchanged. + /// MCP clients drop (#145). Owner decision on PR #146 (option B): such a property becomes its + /// plain string branch, the served schema no longer offers null, and `nullOverrideRefusal` + /// refuses a null at the call. Only an `anyOf` of exactly one string branch plus `{type: null}` + /// branches is collapsed; any other union is left as is, so `refusal` hides the tool and logs why + /// instead of silently dropping a branch. Every other upstream schema is forwarded unchanged. static func forwardedSchema(name: String, _ schema: JSONValue) -> JSONValue { guard name == "browser_emulate_media", var root = schema.objectValue, var props = root["properties"]?.objectValue else { return schema } for (key, prop) in props { guard var p = prop.objectValue, let branches = p["anyOf"]?.arrayValue, - let string = branches.first(where: { $0["type"]?.stringValue == "string" })?.objectValue - else { continue } + let string = nullableStringBranch(branches) else { continue } p.removeValue(forKey: "anyOf") for (k, v) in string { p[k] = v } props[key] = .object(p) @@ -214,15 +215,30 @@ struct UpstreamTool: Tool { return .object(root) } - /// The five browser_emulate_media overrides, which take a string from their enum (option B). - static let emulateMediaOverrides = ["colorScheme", "reducedMotion", "forcedColors", "contrast", "media"] + /// The string branch of `[string, null...]`, or nil when any other branch is not exactly + /// `{type: null}` or there is not exactly one string branch. + static func nullableStringBranch(_ branches: [JSONValue]) -> [String: JSONValue]? { + var string: [String: JSONValue]? + for b in branches { + guard let o = b.objectValue else { return nil } + if o["type"]?.stringValue == "string" { + guard string == nil else { return nil } + string = o + } else if o.count != 1 || o["type"]?.stringValue != "null" { + return nil + } + } + return string + } - /// Why a `tools/call` must not be forwarded, or nil: browser_emulate_media's overrides are not - /// nullable any more, so an explicit null is refused before anything is sent. The reason names - /// the key, never the value. Shared by the upstream path and the browser router. + /// Why a `tools/call` must not be forwarded, or nil: the served browser_emulate_media schema + /// offers no nullable property (option B), so an explicit null for any argument is refused before + /// anything is sent. This covers an override a later upstream adds, not only today's five. The + /// reason names the first such key in sorted order, never the value. Shared by the upstream path + /// and the browser router. static func nullOverrideRefusal(_ name: String, _ arguments: JSONValue) -> String? { guard name == "browser_emulate_media", let args = arguments.objectValue, - let key = emulateMediaOverrides.first(where: { args[$0]?.isNull == true }) + let key = args.keys.sorted().first(where: { args[$0]?.isNull == true }) else { return nil } return "browser_emulate_media: \(key) cannot be null; omit it or send one of its enum values" } diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 5e28481..5a1696f 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -339,6 +339,63 @@ final class ToolSchemaShapeTests: XCTestCase { ["t.properties.a.else has no single string type"]) } + // Round-4 F4: the remaining draft-7 and 2020-12 sub-schema keywords are walked too. + + func testWalksDependenciesSchemaFormAndSkipsItsListForm() { + XCTAssertEqual(Self.problems(fixture("dependencies", ["p": ["type": "string", "anyOf": [["type": "string"]]], + "q": ["r", "s"]]), root: "t"), + ["t.properties.a.dependencies.p.anyOf"]) + } + + func testWalksAdditionalAndUnevaluatedItemsAndProperties() { + for key in ["additionalItems", "unevaluatedItems", "unevaluatedProperties", "contentSchema"] { + XCTAssertEqual(Self.problems(fixture(key, ["type": "string", "oneOf": [["type": "string"]]]), root: "t"), + ["t.properties.a.\(key).oneOf"], key) + } + } + + /// A keyword outside the known vocabulary fails closed: it may hold a sub-schema the walker + /// would not enter, so it is reported instead of passing silently. + func testUnknownKeywordFailsClosed() { + XCTAssertEqual(Self.problems(fixture("x-schema", ["anyOf": [["type": "string"]]]), root: "t"), + ["t.properties.a.x-schema is not a known schema keyword"]) + XCTAssertEqual(Self.problems(fixture("nullable", true), root: "t"), + ["t.properties.a.nullable is not a known schema keyword"]) + // Known annotation and validation keywords still pass. + XCTAssertEqual(Self.problems(fixture("format", "uri"), root: "t"), []) + XCTAssertEqual(Self.problems(fixture("$comment", "c"), root: "t"), []) + } + + // Round-4 F3: only a string-or-null union is collapsed; any other union keeps its anyOf and is refused. + + func testEmulateMediaUnionWithANonNullBranchIsRefusedNotCollapsed() { + let d = Self.descriptor("browser_emulate_media", [ + "zoom": ["anyOf": [["type": "string", "enum": ["in"]], ["type": "number"]]], + ], required: []) + let served = UpstreamTool.forwardedDescriptor(d) + XCTAssertNotNil(served["inputSchema"]?["properties"]?["zoom"]?["anyOf"], "a non-null branch was dropped") + XCTAssertEqual(UpstreamTool.refusal(d), "browser_emulate_media.properties.zoom.anyOf") + } + + func testEmulateMediaStringOrNullUnionIsStillCollapsed() { + let d = Self.descriptor("browser_emulate_media", [ + "zoom": ["anyOf": [["type": "string", "enum": ["in"]], ["type": "null"]], "description": "z"], + ], required: []) + XCTAssertNil(UpstreamTool.refusal(d)) + let zoom = UpstreamTool.forwardedDescriptor(d)["inputSchema"]?["properties"]?["zoom"] + XCTAssertEqual(zoom?["type"]?.stringValue, "string") + XCTAssertNil(zoom?["anyOf"]) + } + + // Round-4 F2: a null is refused for any browser_emulate_media argument, not a fixed key list. + + func testNullIsRefusedForAnEmulateMediaPropertyAddedLater() { + XCTAssertEqual(UpstreamTool.nullOverrideRefusal("browser_emulate_media", ["zoom": .null]), + "browser_emulate_media: zoom cannot be null; omit it or send one of its enum values") + XCTAssertNil(UpstreamTool.nullOverrideRefusal("browser_emulate_media", ["zoom": "in"])) + XCTAssertNil(UpstreamTool.nullOverrideRefusal("browser_click", ["zoom": .null])) + } + /// The non-object root rule, the same as the Rust guard's `root_must_be_an_object_schema`. func testNonObjectRootIsRefused() { XCTAssertEqual(Self.problems(.bool(true), root: "t"), ["t is not an object schema"]) diff --git a/poc/reverse-attach-linux/src/backend.rs b/poc/reverse-attach-linux/src/backend.rs index 23efaff..d267c0a 100644 --- a/poc/reverse-attach-linux/src/backend.rs +++ b/poc/reverse-attach-linux/src/backend.rs @@ -51,6 +51,12 @@ pub struct BackendStatus { pub trait Upstream: Send + Sync { /// The tools this upstream serves right now (empty when it is down). fn tools(&self) -> Vec; + /// The last list `tools` returned, without a request and without starting anything. Empty when + /// nothing is cached. The call path reads this, so a `tools/call` never costs a `tools/list`. + /// The default is `tools()`, for upstreams that hold their list in memory. + fn cached_tools(&self) -> Vec { + self.tools() + } /// Whether `name` is a tool this upstream serves. fn owns(&self, name: &str) -> bool { self.tools() @@ -66,6 +72,9 @@ impl Upstream for External { fn tools(&self) -> Vec { External::tools(self) } + fn cached_tools(&self) -> Vec { + External::cached_tools(self) + } fn call(&self, name: &str, arguments: Value) -> Result { self.rpc( "tools/call", @@ -159,6 +168,15 @@ impl Upstream for Managed { } } + /// The cached list at any age, so the call path neither lists nor starts the child. + fn cached_tools(&self) -> Vec { + self.cache + .lock() + .ok() + .and_then(|c| c.as_ref().map(|(_, t)| t.clone())) + .unwrap_or_default() + } + /// A catalog name is owned without asking the child, so a call while the child is down answers /// with the backend's class and not with "unknown tool". fn owns(&self, name: &str) -> bool { diff --git a/poc/reverse-attach-linux/src/backend_tests.rs b/poc/reverse-attach-linux/src/backend_tests.rs index 0d3815e..7a75b83 100644 --- a/poc/reverse-attach-linux/src/backend_tests.rs +++ b/poc/reverse-attach-linux/src/backend_tests.rs @@ -301,5 +301,5 @@ fn a_down_backend_answers_with_its_class_not_unknown_tool() { &ups, ) .unwrap_err(); - assert_eq!(err, (-32000, "backoff".to_string())); + assert_eq!(err, (-32000, "start_failed".to_string())); } diff --git a/poc/reverse-attach-linux/src/external.rs b/poc/reverse-attach-linux/src/external.rs index 6df98dd..aa97b4b 100644 --- a/poc/reverse-attach-linux/src/external.rs +++ b/poc/reverse-attach-linux/src/external.rs @@ -395,6 +395,15 @@ impl External { } list } + + /// The last list `tools` cached, at any age, without a request. Empty when nothing is cached. + pub fn cached_tools(&self) -> Vec { + self.cache + .lock() + .ok() + .and_then(|c| c.as_ref().map(|(_, t)| t.clone())) + .unwrap_or_default() + } } /// Why a paged listing failed: a request failed (already noted), or the pages were not acceptable. diff --git a/poc/reverse-attach-linux/src/mcp.rs b/poc/reverse-attach-linux/src/mcp.rs index bfac358..06dc678 100644 --- a/poc/reverse-attach-linux/src/mcp.rs +++ b/poc/reverse-attach-linux/src/mcp.rs @@ -219,9 +219,11 @@ pub(crate) fn schema_refusal(descriptor: &Value) -> Option { const NULL_CLAUSE: &str = "; null clears an override"; /// browser_emulate_media's five overrides are `anyOf: [enum string, null]` upstream (#145). Option B -/// (owner decision, PR #146): only the string branch is kept, so each property becomes its plain enum, -/// and the description drops the sentence about null. Mirrors `UpstreamTool.forwardedDescriptor` on -/// the Swift side. Every other descriptor passes unchanged. +/// (owner decision, PR #146): such a property becomes its plain string branch, so each override is +/// its plain enum, and the description drops the sentence about null. Only an `anyOf` of exactly one +/// string branch plus `{type: null}` branches is collapsed; any other union is left as is, so +/// `schema_refusal` hides the tool and logs why instead of silently dropping a branch. Mirrors +/// `UpstreamTool.forwardedDescriptor` on the Swift side. Every other descriptor passes unchanged. pub(crate) fn forwarded_descriptor(mut t: Value) -> Value { if t.get("name").and_then(Value::as_str) != Some("browser_emulate_media") { return t; @@ -244,17 +246,7 @@ pub(crate) fn forwarded_descriptor(mut t: Value) -> Value { let Some(obj) = prop.as_object_mut() else { continue; }; - let string = obj - .get("anyOf") - .and_then(Value::as_array) - .and_then(|branches| { - branches - .iter() - .find(|b| b.get("type").and_then(Value::as_str) == Some("string")) - }) - .and_then(Value::as_object) - .cloned(); - let Some(string) = string else { + let Some(string) = obj.get("anyOf").and_then(nullable_string_branch) else { continue; }; obj.remove("anyOf"); @@ -265,26 +257,40 @@ pub(crate) fn forwarded_descriptor(mut t: Value) -> Value { t } -/// The five browser_emulate_media overrides, which take a string from their enum (option B). -const EMULATE_MEDIA_OVERRIDES: [&str; 5] = [ - "colorScheme", - "reducedMotion", - "forcedColors", - "contrast", - "media", -]; +/// The string branch of an `anyOf` of `[string, null...]`, or `None` when any other branch is not +/// exactly `{type: null}` or there is not exactly one string branch. Mirrors +/// `UpstreamTool.nullableStringBranch` on the Swift side. +fn nullable_string_branch(any_of: &Value) -> Option> { + let mut string = None; + for branch in any_of.as_array()? { + let obj = branch.as_object()?; + let kind = obj.get("type").and_then(Value::as_str); + if kind == Some("string") { + if string.is_some() { + return None; + } + string = Some(obj.clone()); + } else if obj.len() != 1 || kind != Some("null") { + return None; + } + } + string +} -/// Why a `tools/call` must not be forwarded, or nil: an explicit null for one of -/// browser_emulate_media's overrides (option B: the served schema no longer offers null). -/// Names the key, never the value. Mirrors `UpstreamTool.nullOverrideRefusal` on the Swift side. +/// Why a `tools/call` must not be forwarded, or nil: the served browser_emulate_media schema offers +/// no nullable property (option B), so an explicit null for any argument is refused. This covers an +/// override a later upstream adds, not only today's five. Names the first such key in sorted order, +/// never the value. Mirrors `UpstreamTool.nullOverrideRefusal` on the Swift side. pub(crate) fn null_override_refusal(name: &str, arguments: &Value) -> Option { if name != "browser_emulate_media" { return None; } - let key = EMULATE_MEDIA_OVERRIDES + let key = arguments + .as_object()? .iter() - .copied() - .find(|key| arguments.get(*key).is_some_and(Value::is_null))?; + .filter(|(_, v)| v.is_null()) + .map(|(k, _)| k) + .min()?; Some(format!( "browser_emulate_media: {key} cannot be null; omit it or send one of its enum values" )) @@ -303,12 +309,15 @@ pub(crate) fn upstream_owning_with( .cloned() } -/// True when `up` lists `name` and its forwarded schema is refused. Such a tool is neither served nor -/// routed, so a call to it is not sent upstream. +/// True when the last list `up` served has `name` and its forwarded schema is refused. Such a tool +/// is neither served nor routed, so a call to it is not sent upstream. Decided from +/// `Upstream::cached_tools`, never a new `tools/list`: a call does not pay for a listing, and a down +/// backend answers the call with its own class. With nothing cached the tool is not refused here; +/// a client cannot have been offered it, and the call fails or is answered upstream on its own. fn refused_upstream_tool(up: &Arc, name: &str) -> bool { - up.tools().iter().any(|t| { + up.cached_tools().into_iter().any(|t| { t.get("name").and_then(Value::as_str) == Some(name) - && schema_refusal(&forwarded_descriptor(t.clone())).is_some() + && schema_refusal(&forwarded_descriptor(t)).is_some() }) } diff --git a/poc/reverse-attach-linux/src/schema_shape.rs b/poc/reverse-attach-linux/src/schema_shape.rs index c2a412b..05a4386 100644 --- a/poc/reverse-attach-linux/src/schema_shape.rs +++ b/poc/reverse-attach-linux/src/schema_shape.rs @@ -17,18 +17,95 @@ pub(crate) const BANNED: &[&str] = &[ "definitions", ]; -/// Schema positions under `schema`, as (path, node): the node itself, the values of `properties`, -/// `patternProperties` and `dependentSchemas`, `items` (object or tuple form), `prefixItems`, and -/// the single-schema keywords `additionalProperties`, `propertyNames`, `contains`, `if`, `then` and -/// `else`. Data keywords (`default`, `enum`, `const`, `examples`) are never entered, and a property -/// named like a keyword is a name, not a keyword. A non-object sub-schema is not a node. +/// Keywords whose value is a map of name to sub-schema. +const SCHEMA_MAPS: &[&str] = &[ + "properties", + "patternProperties", + "dependentSchemas", + "dependencies", +]; + +/// Keywords whose value is one sub-schema. +const SINGLE_SCHEMAS: &[&str] = &[ + "additionalProperties", + "additionalItems", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "contains", + "contentSchema", + "if", + "then", + "else", +]; + +/// Every other keyword a schema node may carry: the rest of the JSON Schema 2020-12 vocabularies +/// plus the draft-7 `id`. With `BANNED`, `SCHEMA_MAPS` and `SINGLE_SCHEMAS` this is the known set; +/// anything else is reported, so a keyword this walker does not know cannot hide a sub-schema from +/// it (fail closed). Same set as `ToolSchemaShape.known` on the Swift side. +const OTHER_KNOWN: &[&str] = &[ + "$schema", + "$id", + "id", + "$anchor", + "$dynamicAnchor", + "$dynamicRef", + "$recursiveRef", + "$recursiveAnchor", + "$comment", + "$vocabulary", + "items", + "prefixItems", + "type", + "enum", + "const", + "multipleOf", + "maximum", + "exclusiveMaximum", + "minimum", + "exclusiveMinimum", + "maxLength", + "minLength", + "pattern", + "maxItems", + "minItems", + "uniqueItems", + "maxContains", + "minContains", + "maxProperties", + "minProperties", + "required", + "dependentRequired", + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples", + "format", + "contentEncoding", + "contentMediaType", +]; + +fn is_known(keyword: &str) -> bool { + [BANNED, SCHEMA_MAPS, SINGLE_SCHEMAS, OTHER_KNOWN] + .iter() + .any(|set| set.contains(&keyword)) +} + +/// Schema positions under `schema`, as (path, node): the node itself, the values of `SCHEMA_MAPS`, +/// `items` (object or tuple form), `prefixItems`, and `SINGLE_SCHEMAS`. Data keywords (`default`, +/// `enum`, `const`, `examples`) are never entered, and a property named like a keyword is a name, +/// not a keyword. A non-object sub-schema is not a node (a boolean schema, or a draft-7 +/// `dependencies` array of names). fn schema_nodes<'a>(schema: &'a Value, path: String, out: &mut Vec<(String, &'a Value)>) { if !schema.is_object() { return; } out.push((path.clone(), schema)); - for key in ["properties", "patternProperties", "dependentSchemas"] { - if let Some(map) = schema.get(key).and_then(Value::as_object) { + for key in SCHEMA_MAPS { + if let Some(map) = schema.get(*key).and_then(Value::as_object) { for (name, sub) in map { schema_nodes(sub, format!("{path}.{key}.{name}"), out); } @@ -48,21 +125,15 @@ fn schema_nodes<'a>(schema: &'a Value, path: String, out: &mut Vec<(String, &'a schema_nodes(sub, format!("{path}.prefixItems[{i}]"), out); } } - for key in [ - "additionalProperties", - "propertyNames", - "contains", - "if", - "then", - "else", - ] { - if let Some(sub) = schema.get(key) { + for key in SINGLE_SCHEMAS { + if let Some(sub) = schema.get(*key) { schema_nodes(sub, format!("{path}.{key}"), out); } } } -/// Findings for one schema, by path. An empty result means the schema passes. +/// Findings for one schema, by path: a banned keyword, an unknown keyword, a `type` array, or a +/// schema position without one plain `type` string. An empty result means the schema passes. pub(crate) fn problems(schema: &Value, root: &str) -> Vec { if !schema.is_object() { return vec![format!("{root} is not an object schema")]; @@ -76,6 +147,13 @@ pub(crate) fn problems(schema: &Value, root: &str) -> Vec { out.push(format!("{path}.{keyword}")); } } + if let Some(map) = node.as_object() { + let mut unknown: Vec<&String> = map.keys().filter(|k| !is_known(k)).collect(); + unknown.sort(); + for keyword in unknown { + out.push(format!("{path}.{keyword} is not a known schema keyword")); + } + } match node.get("type") { Some(Value::String(_)) => {} Some(Value::Array(_)) => out.push(format!("{path}.type is an array")), diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index b928b0c..6528625 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -441,16 +441,38 @@ fn upstream_does_not_own_a_call_to_a_banned_schema_tool() { ); } -/// An upstream that counts the calls it receives and answers each with an empty result. +/// An upstream that counts the calls and the listings it receives and answers each call with an +/// empty result. Like the managed backend, it owns a name without listing, and its cached list is +/// read without a listing. struct CountingUpstream { tools: Vec, calls: AtomicUsize, + lists: AtomicUsize, +} + +impl CountingUpstream { + fn new(tools: Vec) -> Arc { + Arc::new(CountingUpstream { + tools, + calls: AtomicUsize::new(0), + lists: AtomicUsize::new(0), + }) + } } impl Upstream for CountingUpstream { fn tools(&self) -> Vec { + self.lists.fetch_add(1, Ordering::SeqCst); + self.tools.clone() + } + fn cached_tools(&self) -> Vec { self.tools.clone() } + fn owns(&self, name: &str) -> bool { + self.tools + .iter() + .any(|t| t.get("name").and_then(Value::as_str) == Some(name)) + } fn call(&self, _name: &str, _arguments: Value) -> Result { self.calls.fetch_add(1, Ordering::SeqCst); Ok(json!({ "content": [] })) @@ -469,10 +491,7 @@ impl Upstream for CountingUpstream { /// upstream never sees it. The reason names the key only. #[test] fn emulate_media_null_override_is_refused_before_the_upstream_call() { - let upstream = Arc::new(CountingUpstream { - tools: recorded_tools(), - calls: AtomicUsize::new(0), - }); + let upstream = CountingUpstream::new(recorded_tools()); let ups: Vec> = vec![upstream.clone()]; let params = json!({ "name": "browser_emulate_media", "arguments": { "colorScheme": null, "media": "print" } }); @@ -493,13 +512,149 @@ fn emulate_media_null_override_is_refused_before_the_upstream_call() { /// The enum values still reach the upstream, so the refusal is only for null. #[test] fn emulate_media_enum_value_still_reaches_the_upstream() { - let upstream = Arc::new(CountingUpstream { - tools: recorded_tools(), - calls: AtomicUsize::new(0), - }); + let upstream = CountingUpstream::new(recorded_tools()); let ups: Vec> = vec![upstream.clone()]; let params = json!({ "name": "browser_emulate_media", "arguments": { "colorScheme": "dark" } }); let ok = handle_tool_call_with(¶ms, "owner", None, &ups); assert!(ok.is_ok(), "{ok:?}"); assert_eq!(upstream.calls.load(Ordering::SeqCst), 1); } + +/// Round-4 F1: a routed call decides refusal from the cached list, so it never sends a tools/list. +#[test] +fn a_routed_call_does_not_list_the_upstream() { + let upstream = CountingUpstream::new(recorded_tools()); + let ups: Vec> = vec![upstream.clone()]; + let params = json!({ "name": "browser_navigate", "arguments": { "url": "https://a.test" } }); + let ok = handle_tool_call_with(¶ms, "owner", None, &ups); + assert!(ok.is_ok(), "{ok:?}"); + assert_eq!(upstream.calls.load(Ordering::SeqCst), 1); + assert_eq!( + upstream.lists.load(Ordering::SeqCst), + 0, + "a tools/call sent a tools/list" + ); +} + +/// Round-4 F1: a refused tool in the cached list is still not routed, without a listing. +#[test] +fn a_cached_refused_tool_is_not_routed_and_not_listed() { + let upstream = CountingUpstream::new(banned_upstream_tools()); + let ups: Vec> = vec![upstream.clone()]; + for name in BANNED_NAMES { + assert!( + upstream_owning_with(name, "owner", &ups).is_none(), + "{name} is routed" + ); + } + assert_eq!(upstream.lists.load(Ordering::SeqCst), 0); +} + +/// Round-4 F2: a null is refused for any browser_emulate_media argument, including one a later +/// upstream adds, not only the five overrides of 0.0.82. +#[test] +fn emulate_media_null_for_a_sixth_property_is_refused() { + let mut tools = recorded_tools(); + let media = tools + .iter_mut() + .find(|t| t["name"].as_str() == Some("browser_emulate_media")) + .expect("fixture has browser_emulate_media"); + media["inputSchema"]["properties"]["zoom"] = json!({ + "anyOf": [{ "type": "string", "enum": ["in", "out"] }, { "type": "null" }] + }); + let upstream = CountingUpstream::new(tools); + let ups: Vec> = vec![upstream.clone()]; + let params = json!({ "name": "browser_emulate_media", "arguments": { "zoom": null } }); + let refused = handle_tool_call_with(¶ms, "owner", None, &ups); + let err = refused.expect_err("null is refused"); + assert_eq!(err.0, INVALID_PARAMS); + assert_eq!( + err.1, + "Invalid params: browser_emulate_media: zoom cannot be null; omit it or send one of its enum values" + ); + assert_eq!(upstream.calls.load(Ordering::SeqCst), 0); +} + +/// Round-4 F3: a union with a branch other than null keeps its anyOf, so the tool is refused +/// instead of losing that branch. +#[test] +fn emulate_media_union_with_a_non_null_branch_is_refused_not_collapsed() { + let tool = json!({ "name": "browser_emulate_media", "description": "fixture", "inputSchema": { + "type": "object", + "properties": { "zoom": { "anyOf": [{ "type": "string", "enum": ["in"] }, { "type": "number" }] } } + } }); + let served = crate::mcp::forwarded_descriptor(tool); + assert!( + served["inputSchema"]["properties"]["zoom"]["anyOf"].is_array(), + "a non-null branch was dropped: {served}" + ); + assert_eq!( + crate::mcp::schema_refusal(&served).as_deref(), + Some("browser_emulate_media.properties.zoom.anyOf") + ); +} + +/// Round-4 F3: a string-or-null union is still collapsed to its string branch. +#[test] +fn emulate_media_string_or_null_union_is_collapsed() { + let tool = json!({ "name": "browser_emulate_media", "description": "fixture", "inputSchema": { + "type": "object", + "properties": { "zoom": { "anyOf": [{ "type": "string", "enum": ["in"] }, { "type": "null" }] } } + } }); + let served = crate::mcp::forwarded_descriptor(tool); + let zoom = &served["inputSchema"]["properties"]["zoom"]; + assert_eq!(zoom["type"], json!("string")); + assert!(zoom.get("anyOf").is_none(), "{served}"); + assert_eq!(crate::mcp::schema_refusal(&served), None); +} + +/// Round-4 F4: the draft-7 `dependencies` schema form is walked; its list form is not a schema. +#[test] +fn walks_dependencies_schema_form_and_skips_its_list_form() { + let union = json!({ "type": "string", "anyOf": [{ "type": "string" }] }); + let value = json!({ "p": union, "q": ["r", "s"] }); + let schema = with_property_keyword("dependencies", value); + assert_eq!( + problems(&schema, "t"), + vec!["t.properties.a.dependencies.p.anyOf".to_string()] + ); +} + +/// Round-4 F4: the remaining single sub-schema keywords are walked. +#[test] +fn walks_additional_and_unevaluated_items_and_properties() { + for keyword in [ + "additionalItems", + "unevaluatedItems", + "unevaluatedProperties", + "contentSchema", + ] { + let value = json!({ "type": "string", "oneOf": [{ "type": "string" }] }); + let schema = with_property_keyword(keyword, value); + assert_eq!( + problems(&schema, "t"), + vec![format!("t.properties.a.{keyword}.oneOf")], + "{keyword}" + ); + } +} + +/// Round-4 F4: a keyword outside the known vocabulary fails closed, because it may hold a +/// sub-schema the walker would not enter. +#[test] +fn unknown_keyword_fails_closed() { + let hidden = with_property_keyword("x-schema", json!({ "anyOf": [{ "type": "string" }] })); + assert_eq!( + problems(&hidden, "t"), + vec!["t.properties.a.x-schema is not a known schema keyword".to_string()] + ); + let nullable = with_property_keyword("nullable", json!(true)); + assert_eq!( + problems(&nullable, "t"), + vec!["t.properties.a.nullable is not a known schema keyword".to_string()] + ); + for (keyword, value) in [("format", json!("uri")), ("$comment", json!("c"))] { + let known = with_property_keyword(keyword, value); + assert_eq!(problems(&known, "t"), Vec::::new(), "{keyword}"); + } +} From 23a9db15c11cf5e48f8f20c32d3a0e42be38d680 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:32:12 +0000 Subject: [PATCH 25/26] fix(review): ban $dynamicRef and $recursiveRef in schema guards Round-5 F1. Both guards say they reject reference keywords but listed $dynamicRef and $recursiveRef as known (allowed). Move them to the banned set on the Swift and Rust sides and add one test per side. The anchor keywords stay allowed. --- Sources/InstanceMCPCore/ToolSchemaShape.swift | 7 ++++--- .../ToolSchemaShapeTests.swift | 12 ++++++++++++ poc/reverse-attach-linux/src/schema_shape.rs | 4 ++-- .../src/tool_schema_shape_tests.rs | 18 ++++++++++++++++++ 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/Sources/InstanceMCPCore/ToolSchemaShape.swift b/Sources/InstanceMCPCore/ToolSchemaShape.swift index abb1e10..407c7a1 100644 --- a/Sources/InstanceMCPCore/ToolSchemaShape.swift +++ b/Sources/InstanceMCPCore/ToolSchemaShape.swift @@ -7,7 +7,8 @@ import Foundation /// `UpstreamTool.refusal`), and the tests use them over the local catalog. enum ToolSchemaShape { /// Keywords no served schema may use at a schema position. - static let banned: Set = ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"] + static let banned: Set = ["anyOf", "oneOf", "allOf", "not", "$ref", "$dynamicRef", "$recursiveRef", + "$defs", "definitions"] /// Keywords whose value is a map of name to sub-schema. static let schemaMaps = ["properties", "patternProperties", "dependentSchemas", "dependencies"] @@ -20,8 +21,8 @@ enum ToolSchemaShape { /// so a keyword this walker does not know cannot hide a sub-schema from it (fail closed). static let known: Set = banned .union(schemaMaps).union(singleSchemas) - .union(["$schema", "$id", "id", "$anchor", "$dynamicAnchor", "$dynamicRef", "$recursiveRef", - "$recursiveAnchor", "$comment", "$vocabulary", + .union(["$schema", "$id", "id", "$anchor", "$dynamicAnchor", "$recursiveAnchor", + "$comment", "$vocabulary", "items", "prefixItems", "type", "enum", "const", "multipleOf", "maximum", "exclusiveMaximum", "minimum", "exclusiveMinimum", "maxLength", "minLength", "pattern", "maxItems", "minItems", diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 5a1696f..07f048e 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -366,6 +366,18 @@ final class ToolSchemaShapeTests: XCTestCase { XCTAssertEqual(Self.problems(fixture("$comment", "c"), root: "t"), []) } + // Round-5 F1: the dynamic and recursive reference keywords are refused like `$ref`; their + // anchors stay allowed, since an anchor does nothing without a reference. + + func testDynamicAndRecursiveRefsAreBanned() { + for key in ["$dynamicRef", "$recursiveRef"] { + XCTAssertEqual(Self.problems(fixture(key, "#meta"), root: "t"), ["t.properties.a.\(key)"], key) + } + for key in ["$dynamicAnchor", "$recursiveAnchor"] { + XCTAssertEqual(Self.problems(fixture(key, "meta"), root: "t"), [], key) + } + } + // Round-4 F3: only a string-or-null union is collapsed; any other union keeps its anyOf and is refused. func testEmulateMediaUnionWithANonNullBranchIsRefusedNotCollapsed() { diff --git a/poc/reverse-attach-linux/src/schema_shape.rs b/poc/reverse-attach-linux/src/schema_shape.rs index 05a4386..a3139bc 100644 --- a/poc/reverse-attach-linux/src/schema_shape.rs +++ b/poc/reverse-attach-linux/src/schema_shape.rs @@ -13,6 +13,8 @@ pub(crate) const BANNED: &[&str] = &[ "allOf", "not", "$ref", + "$dynamicRef", + "$recursiveRef", "$defs", "definitions", ]; @@ -49,8 +51,6 @@ const OTHER_KNOWN: &[&str] = &[ "id", "$anchor", "$dynamicAnchor", - "$dynamicRef", - "$recursiveRef", "$recursiveAnchor", "$comment", "$vocabulary", diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index 6528625..ed53474 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -658,3 +658,21 @@ fn unknown_keyword_fails_closed() { assert_eq!(problems(&known, "t"), Vec::::new(), "{keyword}"); } } + +/// Round-5 F1: the dynamic and recursive reference keywords are refused like `$ref`; their anchors +/// stay allowed, since an anchor does nothing without a reference. +#[test] +fn dynamic_and_recursive_refs_are_banned() { + for keyword in ["$dynamicRef", "$recursiveRef"] { + let schema = with_property_keyword(keyword, json!("#meta")); + assert_eq!( + problems(&schema, "t"), + vec![format!("t.properties.a.{keyword}")], + "{keyword}" + ); + } + for keyword in ["$dynamicAnchor", "$recursiveAnchor"] { + let schema = with_property_keyword(keyword, json!("meta")); + assert_eq!(problems(&schema, "t"), Vec::::new(), "{keyword}"); + } +} From 22ee32b1f6ec86dd9855cba46e8530bb87449305 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:43:53 +0000 Subject: [PATCH 26/26] test(review): update banned-set tests for $dynamicRef and $recursiveRef The exact-set tests on both sides still listed seven keywords, which failed Linux hands node on 23a9db1. List nine, add per-keyword ban tests in the existing style, and keep a separate test that the anchors pass. --- .../ToolSchemaShapeTests.swift | 22 ++++++++++++------- .../src/tool_schema_shape_tests.rs | 20 +++++++---------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift index 07f048e..cf78183 100644 --- a/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -230,8 +230,9 @@ final class ToolSchemaShapeTests: XCTestCase { // One test per banned keyword, so deleting an entry from `banned` fails its own test. - func testBannedSetIsExactlyTheSevenKeywords() { - XCTAssertEqual(Self.banned, ["anyOf", "oneOf", "allOf", "not", "$ref", "$defs", "definitions"]) + func testBannedSetIsExactlyTheNineKeywords() { + XCTAssertEqual(Self.banned, ["anyOf", "oneOf", "allOf", "not", "$ref", "$dynamicRef", "$recursiveRef", + "$defs", "definitions"]) } func testBansAnyOf() { @@ -254,6 +255,14 @@ final class ToolSchemaShapeTests: XCTestCase { XCTAssertEqual(Self.problems(fixture("$ref", "#/$defs/x"), root: "t"), ["t.properties.a.$ref"]) } + func testBansDynamicRef() { + XCTAssertEqual(Self.problems(fixture("$dynamicRef", "#meta"), root: "t"), ["t.properties.a.$dynamicRef"]) + } + + func testBansRecursiveRef() { + XCTAssertEqual(Self.problems(fixture("$recursiveRef", "#"), root: "t"), ["t.properties.a.$recursiveRef"]) + } + func testBansDefs() { XCTAssertEqual(Self.problems(fixture("$defs", ["x": ["type": "string"]]), root: "t"), ["t.properties.a.$defs"]) } @@ -366,13 +375,10 @@ final class ToolSchemaShapeTests: XCTestCase { XCTAssertEqual(Self.problems(fixture("$comment", "c"), root: "t"), []) } - // Round-5 F1: the dynamic and recursive reference keywords are refused like `$ref`; their - // anchors stay allowed, since an anchor does nothing without a reference. + // Round-5 F1: `$dynamicRef` and `$recursiveRef` are banned (see testBansDynamicRef and + // testBansRecursiveRef); their anchors stay allowed, since an anchor does nothing without a reference. - func testDynamicAndRecursiveRefsAreBanned() { - for key in ["$dynamicRef", "$recursiveRef"] { - XCTAssertEqual(Self.problems(fixture(key, "#meta"), root: "t"), ["t.properties.a.\(key)"], key) - } + func testAnchorsWithoutAReferenceAreAllowed() { for key in ["$dynamicAnchor", "$recursiveAnchor"] { XCTAssertEqual(Self.problems(fixture(key, "meta"), root: "t"), [], key) } diff --git a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs index ed53474..724d251 100644 --- a/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -40,7 +40,7 @@ fn assert_tool_passes(tool: &Value, context: &str) { } #[test] -fn banned_set_is_exactly_the_seven_keywords() { +fn banned_set_is_exactly_the_nine_keywords() { assert_eq!( BANNED, [ @@ -49,6 +49,8 @@ fn banned_set_is_exactly_the_seven_keywords() { "allOf", "not", "$ref", + "$dynamicRef", + "$recursiveRef", "$defs", "definitions" ] @@ -74,6 +76,8 @@ bans! { bans_all_of => "allOf", bans_schema_not => "not", bans_ref => "$ref", + bans_dynamic_ref => "$dynamicRef", + bans_recursive_ref => "$recursiveRef", bans_defs => "$defs", bans_definitions => "definitions", } @@ -659,18 +663,10 @@ fn unknown_keyword_fails_closed() { } } -/// Round-5 F1: the dynamic and recursive reference keywords are refused like `$ref`; their anchors -/// stay allowed, since an anchor does nothing without a reference. +/// Round-5 F1: `$dynamicRef` and `$recursiveRef` are banned (see `bans!`); their anchors stay +/// allowed, since an anchor does nothing without a reference. #[test] -fn dynamic_and_recursive_refs_are_banned() { - for keyword in ["$dynamicRef", "$recursiveRef"] { - let schema = with_property_keyword(keyword, json!("#meta")); - assert_eq!( - problems(&schema, "t"), - vec![format!("t.properties.a.{keyword}")], - "{keyword}" - ); - } +fn anchors_without_a_reference_are_allowed() { for keyword in ["$dynamicAnchor", "$recursiveAnchor"] { let schema = with_property_keyword(keyword, json!("meta")); assert_eq!(problems(&schema, "t"), Vec::::new(), "{keyword}");