Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
a95874b
fix: plain input schemas for ui_snapshot and ui_action (#145)
chaodu-agent Nov 17, 2026
08c525a
fix: ui_action set_value type fallback and ui_snapshot window_index
chaodu-agent Nov 18, 2026
a655beb
test: schema guard covers forwarded upstream schemas, every banned ke…
chaodu-agent Nov 18, 2026
54d6db1
test(rust): schema guard over the Linux daemon's tool lists
chaodu-agent Nov 18, 2026
97f7a9e
fix: make ui_snapshot window title-only in the schema, drop window_index
chaodu-agent Nov 18, 2026
e1a0fa0
fix: value-type refusal names the mismatch, no native-number advice
chaodu-agent Nov 18, 2026
07647ad
fix: forward browser_emulate_media overrides as plain enums; pin upst…
chaodu-agent Nov 18, 2026
dc7786e
fix(schema): serve option B for browser_emulate_media on every tools/…
chaodu-agent Nov 19, 2026
3326036
test(schema): shape guard covers forwarded upstream tools
chaodu-agent Nov 19, 2026
9fce1bb
fix(ui): title-only window error text in ui_snapshot
chaodu-agent Nov 19, 2026
e5c2e53
fix(ui): name the field in valueTypeRejected and match value parse er…
chaodu-agent Nov 19, 2026
faa323b
style(linux): cargo fmt
chaodu-agent Nov 19, 2026
d4297ef
test(schema): cover runtime refusal, native value wording and emulate…
chaodu-agent Nov 19, 2026
507e2f9
fix(schema): refuse forwarded tools whose schema breaks the shape rul…
chaodu-agent Nov 19, 2026
79ea45a
Revert "test(schema): cover runtime refusal, native value wording and…
chaodu-agent Nov 19, 2026
06f7eba
Merge main into fix/tool-schema-no-anyof
chaodu-agent Nov 19, 2026
175278c
style: rustfmt tool_schema_shape_tests.rs
chaodu-agent Nov 19, 2026
b308f14
fix(schema): F1 prefix-aware emulate rewrite, F2 refuse null override…
chaodu-agent Nov 19, 2026
a532aec
fix(schema): F3 walk every sub-schema keyword, same root rule in Swif…
chaodu-agent Nov 19, 2026
98841db
fix(ui): F4 generic -25201 wording for native input, trim before the …
chaodu-agent Nov 19, 2026
8b96d42
docs(fixtures): F5 README for re-recording the Playwright 0.0.82 tool…
chaodu-agent Nov 19, 2026
47ff103
docs(fixtures): F5 README install uses the pins smoke-check isolation
chaodu-agent Nov 19, 2026
c92f905
style: rustfmt tool_schema_shape_tests.rs (CI cargo fmt --check)
chaodu-agent Nov 19, 2026
d25cdfb
test(backend): down-backend call expects backoff, not start_failed
chaodu-agent Nov 19, 2026
1b90b8b
fix(review): round-4 findings for schema guard and call path
chaodu-agent Nov 19, 2026
23a9db1
fix(review): ban $dynamicRef and $recursiveRef in schema guards
chaodu-agent Nov 19, 2026
22ee32b
test(review): update banned-set tests for $dynamicRef and $recursiveRef
chaodu-agent Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions Sources/InstanceMCPCore/Browser/BrowserRouter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand All @@ -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)
Expand Down
78 changes: 78 additions & 0 deletions Sources/InstanceMCPCore/ToolSchemaShape.swift
Original file line number Diff line number Diff line change
@@ -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<String> = ["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<String> = 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
}
}
29 changes: 26 additions & 3 deletions Sources/InstanceMCPCore/Tools/UIActionTool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down Expand Up @@ -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"
}
Expand Down Expand Up @@ -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 {
Expand Down
17 changes: 11 additions & 6 deletions Sources/InstanceMCPCore/Tools/UISnapshotTool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand All @@ -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.",
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down
25 changes: 24 additions & 1 deletion Sources/InstanceMCPCore/UISnapshot/UIAction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void, UIAXError>
var done: Result<Void, UIAXError>
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:
Expand All @@ -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))
}
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions Sources/InstanceMCPCore/UISnapshot/UIElementProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading