diff --git a/Sources/InstanceMCPCore/Browser/BrowserRouter.swift b/Sources/InstanceMCPCore/Browser/BrowserRouter.swift index 72a8a2e..bc9d58a 100644 --- a/Sources/InstanceMCPCore/Browser/BrowserRouter.swift +++ b/Sources/InstanceMCPCore/Browser/BrowserRouter.swift @@ -74,9 +74,13 @@ 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 } + 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,11 +101,14 @@ 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) } + 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/ToolSchemaShape.swift b/Sources/InstanceMCPCore/ToolSchemaShape.swift new file mode 100644 index 0000000..407c7a1 --- /dev/null +++ b/Sources/InstanceMCPCore/ToolSchemaShape.swift @@ -0,0 +1,78 @@ +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", "$dynamicRef", "$recursiveRef", + "$defs", "definitions"] + + /// 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", "$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 { + 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 `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 schemaMaps { + 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 { + for (i, sub) in tuple.enumerated() { out += nodes(sub, path: "\(path).items[\(i)]") } + } else { + out += nodes(items, path: "\(path).items") + } + } + for (i, sub) in (node["prefixItems"]?.arrayValue ?? []).enumerated() { + out += nodes(sub, path: "\(path).prefixItems[\(i)]") + } + for key in singleSchemas { + if let sub = node[key] { out += nodes(sub, path: "\(path).\(key)") } + } + return out + } +} diff --git a/Sources/InstanceMCPCore/Tools/UIActionTool.swift b/Sources/InstanceMCPCore/Tools/UIActionTool.swift index 95dd886..56bbfde 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 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.", @@ -73,6 +72,26 @@ 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. -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 (\(code)). " + + "\(likely) Take a new ui_snapshot to check the control's current value type" + } + 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" } @@ -151,6 +170,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 29cea07..40f1911 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 `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 \ @@ -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: exact match, else case-insensitive substring. A string is always read as a title, even when it looks like a number. 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.", @@ -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" @@ -122,12 +123,16 @@ 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") } } if let v = a["all_windows"], !v.isNull { diff --git a/Sources/InstanceMCPCore/UISnapshot/UIAction.swift b/Sources/InstanceMCPCore/UISnapshot/UIAction.swift index 233e104..e4631ab 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,10 @@ 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: + // 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)) } @@ -275,6 +287,17 @@ struct UIActionEngine { return ToolResult(content: [.text(text)], structured: .object(o)) } + /// 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 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) } + 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/Sources/InstanceMCPCore/UpstreamMCP.swift b/Sources/InstanceMCPCore/UpstreamMCP.swift index 1bc70f9..5ba3545 100644 --- a/Sources/InstanceMCPCore/UpstreamMCP.swift +++ b/Sources/InstanceMCPCore/UpstreamMCP.swift @@ -41,13 +41,23 @@ 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) } - 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)") @@ -59,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 @@ -155,8 +166,82 @@ struct UpstreamTool: Tool { var name: String { descriptorValue["name"]?.stringValue ?? "?" } var description: String { descriptorValue["description"]?.stringValue ?? "" } - var inputSchema: JSONValue { descriptorValue["inputSchema"] ?? ["type": "object"] } - var descriptor: JSONValue { descriptorValue } + var inputSchema: JSONValue { Self.forwardedSchema(name: name, descriptorValue["inputSchema"] ?? ["type": "object"]) } + /// 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, 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 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). 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 = nullableStringBranch(branches) 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) + } + + /// 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: 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 = 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" + } func call(arguments: JSONValue) async throws -> ToolResult { let r = try await upstream.call(name, arguments: arguments) diff --git a/Tests/Fixtures/README.md b/Tests/Fixtures/README.md new file mode 100644 index 0000000..6176a0e --- /dev/null +++ b/Tests/Fixtures/README.md @@ -0,0 +1,94 @@ +# 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, 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 + 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: + `--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. 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/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 new file mode 100644 index 0000000..cf78183 --- /dev/null +++ b/Tests/InstanceMCPCoreTests/ToolSchemaShapeTests.swift @@ -0,0 +1,449 @@ +import Foundation +import XCTest +@testable import InstanceMCPCore + +/// 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. 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 { + /// Keywords no guarded schema may use at a schema position. + static let banned: Set = ToolSchemaShape.banned + + /// 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] { + ToolSchemaShape.problems(schema, root: root) + } + + /// 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") + XCTAssertEqual(Self.problems(t.inputSchema, root: t.name), [], "\(t.name) uses a construct some MCP clients reject") + } + } + + // 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)] } + + 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 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 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") + } + } + + 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?, 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 \(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) + 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) + } + + // 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) + 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) + } + + // 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" { + 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 testBannedSetIsExactlyTheNineKeywords() { + XCTAssertEqual(Self.banned, ["anyOf", "oneOf", "allOf", "not", "$ref", "$dynamicRef", "$recursiveRef", + "$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 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"]) + } + + 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"), []) + } + + // 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"]) + } + + // 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-5 F1: `$dynamicRef` and `$recursiveRef` are banned (see testBansDynamicRef and + // testBansRecursiveRef); their anchors stay allowed, since an anchor does nothing without a reference. + + func testAnchorsWithoutAReferenceAreAllowed() { + 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() { + 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"]) + } + + // 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 testSnapshotWindowSchemaIsTitleOnly() throws { + let props = UISnapshotTool().inputSchema["properties"] + XCTAssertEqual(props?["window"]?["type"]?.stringValue, "string") + 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 { + 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/Tests/InstanceMCPCoreTests/UIActionTests.swift b/Tests/InstanceMCPCoreTests/UIActionTests.swift index 90ff0ac..091c59e 100644 --- a/Tests/InstanceMCPCoreTests/UIActionTests.swift +++ b/Tests/InstanceMCPCoreTests/UIActionTests.swift @@ -330,6 +330,121 @@ 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 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() + 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", sent: .string("hello"), retried: false)) + 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 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, 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 (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 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 (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) + } + + 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", 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", sent: .string("3"), retried: retried) + XCTAssertTrue(text.contains("the `value` property"), text) + } + } + + func testValueParseErrorNamesTheAcceptedTypes() async { + let f = Fixture() + let id = await f.snapshot() + // 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, number or boolean") + 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..bc17833 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?() @@ -677,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) @@ -690,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 @@ -879,7 +888,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"), (["app": ""], "app must be a non-empty string")] for (args, why) in cases { let r = await call(args) diff --git a/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift b/Tests/InstanceMCPCoreTests/UpstreamMCPTests.swift index 189918c..20db3ec 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"]] @@ -148,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/docs/ui-tools.md b/docs/ui-tools.md index 46477e7..96c9364 100644 --- a/docs/ui-tools.md +++ b/docs/ui-tools.md @@ -9,7 +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` (title or index) or `all_windows` selects windows. + 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 @@ -28,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`: 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). 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 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/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/main.rs b/poc/reverse-attach-linux/src/main.rs index 1199371..0c7b179 100644 --- a/poc/reverse-attach-linux/src/main.rs +++ b/poc/reverse-attach-linux/src/main.rs @@ -49,6 +49,7 @@ mod procnet; #[cfg(test)] mod profile_conformance; mod run_record; +mod schema_shape; mod signin; mod sigstop; mod state; @@ -56,6 +57,8 @@ mod stdio_client; mod sweep; #[cfg(test)] mod test_exec; +#[cfg(test)] +mod tool_schema_shape_tests; mod tools; mod unit; #[cfg(test)] diff --git a/poc/reverse-attach-linux/src/mcp.rs b/poc/reverse-attach-linux/src/mcp.rs index 5863f9f..06dc678 100644 --- a/poc/reverse-attach-linux/src/mcp.rs +++ b/poc/reverse-attach-linux/src/mcp.rs @@ -181,18 +181,121 @@ 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(), 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): 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; + } + 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")) + .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 Some(string) = obj.get("anyOf").and_then(nullable_string_branch) else { + continue; + }; + obj.remove("anyOf"); + for (k, v) in string { + obj.insert(k, v); + } + } + t +} + +/// 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: 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 = arguments + .as_object()? + .iter() + .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" + )) +} + pub(crate) fn upstream_owning_with( name: &str, profile: &str, @@ -201,7 +304,21 @@ 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 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.cached_tools().into_iter().any(|t| { + t.get("name").and_then(Value::as_str) == Some(name) + && schema_refusal(&forwarded_descriptor(t)).is_some() + }) } // --------------------------------------------------------------------------- @@ -569,7 +686,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/schema_shape.rs b/poc/reverse-attach-linux/src/schema_shape.rs new file mode 100644 index 0000000..a3139bc --- /dev/null +++ b/poc/reverse-attach-linux/src/schema_shape.rs @@ -0,0 +1,164 @@ +//! 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", + "$dynamicRef", + "$recursiveRef", + "$defs", + "definitions", +]; + +/// 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", + "$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 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); + } + } + } + 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(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 SINGLE_SCHEMAS { + if let Some(sub) = schema.get(*key) { + schema_nodes(sub, format!("{path}.{key}"), out); + } + } +} + +/// 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")]; + } + 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}")); + } + } + 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")), + _ => 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 new file mode 100644 index 0000000..724d251 --- /dev/null +++ b/poc/reverse-attach-linux/src/tool_schema_shape_tests.rs @@ -0,0 +1,674 @@ +//! 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), `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::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use serde_json::{json, Value}; + +use crate::backend::{BackendStatus, Upstream}; +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}}}`. +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_nine_keywords() { + assert_eq!( + BANNED, + [ + "anyOf", + "oneOf", + "allOf", + "not", + "$ref", + "$dynamicRef", + "$recursiveRef", + "$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_dynamic_ref => "$dynamicRef", + bans_recursive_ref => "$recursiveRef", + 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()); +} + +/// 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!( + 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"); + } +} + +/// 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, 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"), + "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 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"])), + ("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); +} + +/// 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"); + } +} + +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" + ); +} + +/// 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": [] })) + } + 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 = CountingUpstream::new(recorded_tools()); + 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 = 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}"); + } +} + +/// Round-5 F1: `$dynamicRef` and `$recursiveRef` are banned (see `bans!`); their anchors stay +/// allowed, since an anchor does nothing without a reference. +#[test] +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}"); + } +}