Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver): support modern stdio MCP and skills resources

Francesco Bonacci9dd3013fbdbc
diff --git a/.github/scripts/cua-driver-mcp-compat/expected-tools.json b/.github/scripts/cua-driver-mcp-compat/expected-tools.json
index 6297759235..7d80cc8db8 100644
--- a/.github/scripts/cua-driver-mcp-compat/expected-tools.json
+++ b/.github/scripts/cua-driver-mcp-compat/expected-tools.json
@@ -69,6 +69,9 @@
"mouse_button_up",
"mouse_drag",
"parallel_mouse_drag"
+ ],
+ "win32": [
+ "debug_window_info"
]
}
}
diff --git a/.github/scripts/cua-driver-mcp-compat/modern-client/.gitignore b/.github/scripts/cua-driver-mcp-compat/modern-client/.gitignore
new file mode 100644
index 0000000000..c2658d7d1b
--- /dev/null
+++ b/.github/scripts/cua-driver-mcp-compat/modern-client/.gitignore
@@ -0,0 +1 @@
+node_modules/
diff --git a/.github/scripts/cua-driver-mcp-compat/modern-client/SCHEMA-SOURCE.md b/.github/scripts/cua-driver-mcp-compat/modern-client/SCHEMA-SOURCE.md
new file mode 100644
index 0000000000..837007686f
--- /dev/null
+++ b/.github/scripts/cua-driver-mcp-compat/modern-client/SCHEMA-SOURCE.md
@@ -0,0 +1,16 @@
+# Pinned upstream schema
+
+`schema-2026-07-28.json` copies the JSON schema from
+<https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/e76e9c572c6f2bfcb730357101acc90f2f802e02/schema/2026-07-28/schema.json>.
+
+Upstream SHA-256: `ef70b61f99b6d2e5e3b46863822eab08dff6a45bedc7a08914e0e5b133f40203`.
+
+`schema-LICENSE` reproduces the upstream license notice at that commit. This
+fixture retains the upstream licensing terms, including its transition notice.
+
+The schema covers the base MCP protocol. SEP-2640 Skills remains an extension:
+the probe checks its list/get structure, metadata, manifest, content integrity,
+and frontmatter explicitly rather than claiming base-schema validation of it.
+
+The local fixture normalizes trailing blank lines to one final newline; its JSON
+content is unchanged. Local SHA-256: `e8c8ae56f7dd8eab465fb2740db54042761c4f9e0e19b23b98504cec27f4c91d`.
diff --git a/.github/scripts/cua-driver-mcp-compat/modern-client/package-lock.json b/.github/scripts/cua-driver-mcp-compat/modern-client/package-lock.json
new file mode 100644
index 0000000000..babc1e096f
--- /dev/null
+++ b/.github/scripts/cua-driver-mcp-compat/modern-client/package-lock.json
@@ -0,0 +1,226 @@
+{
+ "name": "cua-driver-modern-mcp-compat",
+ "version": "0.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "cua-driver-modern-mcp-compat",
+ "version": "0.0.0",
+ "dependencies": {
+ "@modelcontextprotocol/client": "2.0.0",
+ "@modelcontextprotocol/core": "2.0.0",
+ "ajv": "8.17.1",
+ "yaml": "2.8.1"
+ }
+ },
+ "node_modules/@modelcontextprotocol/client": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.0.0.tgz",
+ "integrity": "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==",
+ "license": "MIT",
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.0.0",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.0",
+ "jose": "^6.1.3",
+ "pkce-challenge": "^5.0.0",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz",
+ "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==",
+ "license": "MIT",
+ "dependencies": {
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/ajv": {
+ "version": "8.17.1",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
+ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/eventsource": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+ "license": "MIT",
+ "dependencies": {
+ "eventsource-parser": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/eventsource-parser": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "license": "MIT"
+ },
+ "node_modules/fast-uri": {
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz",
+ "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "license": "ISC"
+ },
+ "node_modules/jose": {
+ "version": "6.2.12",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz",
+ "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
+ "node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/pkce-challenge": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/yaml": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz",
+ "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==",
+ "license": "ISC",
+ "bin": {
+ "yaml": "bin.mjs"
+ },
+ "engines": {
+ "node": ">= 14.6"
+ }
+ },
+ "node_modules/zod": {
+ "version": "4.5.4",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.5.4.tgz",
+ "integrity": "sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/.github/scripts/cua-driver-mcp-compat/modern-client/package.json b/.github/scripts/cua-driver-mcp-compat/modern-client/package.json
new file mode 100644
index 0000000000..05200fd5c3
--- /dev/null
+++ b/.github/scripts/cua-driver-mcp-compat/modern-client/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "cua-driver-modern-mcp-compat",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "dependencies": {
+ "@modelcontextprotocol/client": "2.0.0",
+ "@modelcontextprotocol/core": "2.0.0",
+ "ajv": "8.17.1",
+ "yaml": "2.8.1"
+ }
+}
diff --git a/.github/scripts/cua-driver-mcp-compat/modern-client/schema-2026-07-28.json b/.github/scripts/cua-driver-mcp-compat/modern-client/schema-2026-07-28.json
new file mode 100644
index 0000000000..b8ac603c82
--- /dev/null
+++ b/.github/scripts/cua-driver-mcp-compat/modern-client/schema-2026-07-28.json
@@ -0,0 +1,3962 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$defs": {
+ "Annotations": {
+ "description": "Optional annotations for the client. The client can use annotations to inform how objects are used or displayed",
+ "properties": {
+ "audience": {
+ "description": "Describes who the intended audience of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).",
+ "items": {
+ "$ref": "#/$defs/Role"
+ },
+ "type": "array"
+ },
+ "lastModified": {
+ "description": "The moment the resource was last modified, as an ISO 8601 formatted string.\n\nShould be an ISO 8601 formatted string (e.g., \"2025-01-12T15:00:58Z\").\n\nExamples: last activity timestamp in an open file, timestamp when the resource\nwas attached, etc.",
+ "type": "string"
+ },
+ "priority": {
+ "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.",
+ "maximum": 1,
+ "minimum": 0,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "AudioContent": {
+ "description": "Audio provided to or from an LLM.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "annotations": {
+ "$ref": "#/$defs/Annotations",
+ "description": "Optional annotations for the client."
+ },
+ "data": {
+ "description": "The base64-encoded audio data.",
+ "format": "byte",
+ "type": "string"
+ },
+ "mimeType": {
+ "description": "The MIME type of the audio. Different providers may support different audio types.",
+ "type": "string"
+ },
+ "type": {
+ "const": "audio",
+ "type": "string"
+ }
+ },
+ "required": [
+ "data",
+ "mimeType",
+ "type"
+ ],
+ "type": "object"
+ },
+ "BaseMetadata": {
+ "description": "Base interface for metadata with name (identifier) and title (display name) properties.",
+ "properties": {
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "type": "object"
+ },
+ "BlobResourceContents": {
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "blob": {
+ "description": "A base64-encoded string representing the binary data of the item.",
+ "format": "byte",
+ "type": "string"
+ },
+ "mimeType": {
+ "description": "The MIME type of this resource, if known.",
+ "type": "string"
+ },
+ "uri": {
+ "description": "The URI of this resource.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "blob",
+ "uri"
+ ],
+ "type": "object"
+ },
+ "BooleanSchema": {
+ "properties": {
+ "default": {
+ "type": "boolean"
+ },
+ "description": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ },
+ "type": {
+ "const": "boolean",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ "CacheableResult": {
+ "description": "A result that supports a time-to-live (TTL) hint for client-side caching.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "cacheScope": {
+ "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).",
+ "enum": [
+ "private",
+ "public"
+ ],
+ "type": "string"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ },
+ "ttlMs": {
+ "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "cacheScope",
+ "resultType",
+ "ttlMs"
+ ],
+ "type": "object"
+ },
+ "CallToolRequest": {
+ "description": "Used by the client to invoke a tool provided by the server.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "tools/call",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/CallToolRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "CallToolRequestParams": {
+ "description": "Parameters for a `tools/call` request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ },
+ "arguments": {
+ "additionalProperties": {},
+ "description": "Arguments to use for the tool call.",
+ "type": "object"
+ },
+ "inputResponses": {
+ "$ref": "#/$defs/InputResponses"
+ },
+ "name": {
+ "description": "The name of the tool.",
+ "type": "string"
+ },
+ "requestState": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "_meta",
+ "name"
+ ],
+ "type": "object"
+ },
+ "CallToolResult": {
+ "description": "The result returned by the server for a {@link CallToolRequesttools/call} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "content": {
+ "description": "A list of content objects that represent the unstructured result of the tool call.",
+ "items": {
+ "$ref": "#/$defs/ContentBlock"
+ },
+ "type": "array"
+ },
+ "isError": {
+ "description": "Whether the tool call ended in an error.\n\nIf not set, this is assumed to be false (the call was successful).\n\nAny errors that originate from the tool SHOULD be reported inside the result\nobject, with `isError` set to true, _not_ as an MCP protocol-level error\nresponse. Otherwise, the LLM would not be able to see that an error occurred\nand self-correct.\n\nHowever, any errors in _finding_ the tool, an error indicating that the\nserver does not support tool calls, or any other exceptional conditions,\nshould be reported as an MCP error response.",
+ "type": "boolean"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ },
+ "structuredContent": {
+ "description": "An optional JSON value that represents the structured result of the tool call.\n\nThis can be any JSON value (object, array, string, number, boolean, or null)\nthat conforms to the tool's outputSchema if one is defined."
+ }
+ },
+ "required": [
+ "content",
+ "resultType"
+ ],
+ "type": "object"
+ },
+ "CallToolResultResponse": {
+ "description": "A successful response from the server for a {@link CallToolRequesttools/call} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/InputRequiredResult"
+ },
+ {
+ "$ref": "#/$defs/CallToolResult"
+ }
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "CancelledNotification": {
+ "description": "This notification is sent by the client to indicate that it is cancelling a request it previously issued.\n\nOn stdio, the server also sends this notification, solely to terminate a {@link SubscriptionsListenRequestsubscriptions/listen} stream: it references the ID of the `subscriptions/listen` request that opened the stream. Servers MUST NOT use this notification to cancel any other request.\n\nThe request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n\nThis notification indicates that the result will be unused, so any associated processing SHOULD cease.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/cancelled",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/CancelledNotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "CancelledNotificationParams": {
+ "description": "Parameters for a `notifications/cancelled` notification.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/NotificationMetaObject"
+ },
+ "reason": {
+ "description": "An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.",
+ "type": "string"
+ },
+ "requestId": {
+ "$ref": "#/$defs/RequestId",
+ "description": "The ID of the request to cancel.\n\nThis MUST correspond to the ID of a request the client previously issued."
+ }
+ },
+ "required": [
+ "requestId"
+ ],
+ "type": "object"
+ },
+ "ClientCapabilities": {
+ "description": "Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.",
+ "properties": {
+ "elicitation": {
+ "description": "Present if the client supports elicitation from the server.",
+ "properties": {
+ "form": {
+ "$ref": "#/$defs/JSONObject"
+ },
+ "url": {
+ "$ref": "#/$defs/JSONObject"
+ }
+ },
+ "type": "object"
+ },
+ "experimental": {
+ "additionalProperties": {
+ "$ref": "#/$defs/JSONObject"
+ },
+ "description": "Experimental, non-standard capabilities that the client supports.",
+ "type": "object"
+ },
+ "extensions": {
+ "additionalProperties": {
+ "$ref": "#/$defs/JSONObject"
+ },
+ "description": "Optional MCP extensions that the client supports. Keys are extension identifiers\n(e.g., \"io.modelcontextprotocol/oauth-client-credentials\"), and values are\nper-extension settings objects. An empty object indicates support with no settings.\n\nKeys MUST follow the {@link MetaObject`_meta` key naming rules}, with a\nmandatory prefix.",
+ "type": "object"
+ },
+ "roots": {
+ "description": "Present if the client supports listing roots.",
+ "properties": {},
+ "type": "object"
+ },
+ "sampling": {
+ "description": "Present if the client supports sampling from an LLM.",
+ "properties": {
+ "context": {
+ "$ref": "#/$defs/JSONObject",
+ "description": "Whether the client supports context inclusion via `includeContext` parameter.\nIf not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it)."
+ },
+ "tools": {
+ "$ref": "#/$defs/JSONObject",
+ "description": "Whether the client supports tool use via `tools` and `toolChoice` parameters."
+ }
+ },
+ "type": "object"
+ }
+ },
+ "type": "object"
+ },
+ "ClientNotification": {
+ "description": "This notification is sent by the client to indicate that it is cancelling a request it previously issued.\n\nOn stdio, the server also sends this notification, solely to terminate a {@link SubscriptionsListenRequestsubscriptions/listen} stream: it references the ID of the `subscriptions/listen` request that opened the stream. Servers MUST NOT use this notification to cancel any other request.\n\nThe request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n\nThis notification indicates that the result will be unused, so any associated processing SHOULD cease.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/cancelled",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/CancelledNotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ClientRequest": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/DiscoverRequest"
+ },
+ {
+ "$ref": "#/$defs/ListResourcesRequest"
+ },
+ {
+ "$ref": "#/$defs/ListResourceTemplatesRequest"
+ },
+ {
+ "$ref": "#/$defs/ReadResourceRequest"
+ },
+ {
+ "$ref": "#/$defs/SubscriptionsListenRequest"
+ },
+ {
+ "$ref": "#/$defs/ListPromptsRequest"
+ },
+ {
+ "$ref": "#/$defs/GetPromptRequest"
+ },
+ {
+ "$ref": "#/$defs/ListToolsRequest"
+ },
+ {
+ "$ref": "#/$defs/CallToolRequest"
+ },
+ {
+ "$ref": "#/$defs/CompleteRequest"
+ }
+ ]
+ },
+ "ClientResult": {
+ "$ref": "#/$defs/Result",
+ "description": "Common result fields."
+ },
+ "CompleteRequest": {
+ "description": "A request from the client to the server, to ask for completion options.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "completion/complete",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/CompleteRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "CompleteRequestParams": {
+ "description": "Parameters for a `completion/complete` request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ },
+ "argument": {
+ "description": "The argument's information",
+ "properties": {
+ "name": {
+ "description": "The name of the argument",
+ "type": "string"
+ },
+ "value": {
+ "description": "The value of the argument to use for completion matching.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "value"
+ ],
+ "type": "object"
+ },
+ "context": {
+ "description": "Additional, optional context for completions",
+ "properties": {
+ "arguments": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "Previously-resolved variables in a URI template or prompt.",
+ "type": "object"
+ }
+ },
+ "type": "object"
+ },
+ "ref": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/PromptReference"
+ },
+ {
+ "$ref": "#/$defs/ResourceTemplateReference"
+ }
+ ]
+ }
+ },
+ "required": [
+ "_meta",
+ "argument",
+ "ref"
+ ],
+ "type": "object"
+ },
+ "CompleteResult": {
+ "description": "The result returned by the server for a {@link CompleteRequestcompletion/complete} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "completion": {
+ "properties": {
+ "hasMore": {
+ "description": "Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.",
+ "type": "boolean"
+ },
+ "total": {
+ "description": "The total number of completion options available. This can exceed the number of values actually sent in the response.",
+ "type": "integer"
+ },
+ "values": {
+ "description": "An array of completion values. Must not exceed 100 items.",
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 100,
+ "type": "array"
+ }
+ },
+ "required": [
+ "values"
+ ],
+ "type": "object"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "completion",
+ "resultType"
+ ],
+ "type": "object"
+ },
+ "CompleteResultResponse": {
+ "description": "A successful response from the server for a {@link CompleteRequestcompletion/complete} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "$ref": "#/$defs/CompleteResult"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "ContentBlock": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/TextContent"
+ },
+ {
+ "$ref": "#/$defs/ImageContent"
+ },
+ {
+ "$ref": "#/$defs/AudioContent"
+ },
+ {
+ "$ref": "#/$defs/ResourceLink"
+ },
+ {
+ "$ref": "#/$defs/EmbeddedResource"
+ }
+ ]
+ },
+ "CreateMessageRequest": {
+ "description": "A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.",
+ "properties": {
+ "method": {
+ "const": "sampling/createMessage",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/CreateMessageRequestParams"
+ }
+ },
+ "required": [
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "CreateMessageRequestParams": {
+ "description": "Parameters for a `sampling/createMessage` request.",
+ "properties": {
+ "includeContext": {
+ "description": "A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\nThe client MAY ignore this request.\n\nDefault is `\"none\"`. The values `\"thisServer\"` and `\"allServers\"` are deprecated (SEP-2596): servers SHOULD\nomit this field or use `\"none\"`, and SHOULD only use the deprecated values if the client declares\n{@link ClientCapabilities.sampling.context}.",
+ "enum": [
+ "allServers",
+ "none",
+ "thisServer"
+ ],
+ "type": "string"
+ },
+ "maxTokens": {
+ "description": "The requested maximum number of tokens to sample (to prevent runaway completions).\n\nThe client MAY choose to sample fewer tokens than the requested maximum.",
+ "type": "integer"
+ },
+ "messages": {
+ "items": {
+ "$ref": "#/$defs/SamplingMessage"
+ },
+ "type": "array"
+ },
+ "metadata": {
+ "$ref": "#/$defs/JSONObject",
+ "description": "Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific."
+ },
+ "modelPreferences": {
+ "$ref": "#/$defs/ModelPreferences",
+ "description": "The server's preferences for which model to select. The client MAY ignore these preferences."
+ },
+ "stopSequences": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "systemPrompt": {
+ "description": "An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.",
+ "type": "string"
+ },
+ "temperature": {
+ "type": "number"
+ },
+ "toolChoice": {
+ "$ref": "#/$defs/ToolChoice",
+ "description": "Controls how the model uses tools.\nThe client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared.\nDefault is `{ mode: \"auto\" }`."
+ },
+ "tools": {
+ "description": "Tools that the model may use during generation.\nThe client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared.",
+ "items": {
+ "$ref": "#/$defs/Tool"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "maxTokens",
+ "messages"
+ ],
+ "type": "object"
+ },
+ "CreateMessageResult": {
+ "description": "The result returned by the client for a {@link CreateMessageRequestsampling/createMessage} request.\nThe client should inform the user before returning the sampled message, to allow them\nto inspect the response (human in the loop) and decide whether to allow the server to see it.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "content": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/TextContent"
+ },
+ {
+ "$ref": "#/$defs/ImageContent"
+ },
+ {
+ "$ref": "#/$defs/AudioContent"
+ },
+ {
+ "$ref": "#/$defs/ToolUseContent"
+ },
+ {
+ "$ref": "#/$defs/ToolResultContent"
+ },
+ {
+ "items": {
+ "$ref": "#/$defs/SamplingMessageContentBlock"
+ },
+ "type": "array"
+ }
+ ]
+ },
+ "model": {
+ "description": "The name of the model that generated the message.",
+ "type": "string"
+ },
+ "role": {
+ "$ref": "#/$defs/Role"
+ },
+ "stopReason": {
+ "description": "The reason why sampling stopped, if known.\n\nStandard values:\n- `\"endTurn\"`: Natural end of the assistant's turn\n- `\"stopSequence\"`: A stop sequence was encountered\n- `\"maxTokens\"`: Maximum token limit was reached\n- `\"toolUse\"`: The model wants to use one or more tools\n\nThis field is an open string to allow for provider-specific stop reasons.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "content",
+ "model",
+ "role"
+ ],
+ "type": "object"
+ },
+ "Cursor": {
+ "description": "An opaque token used to represent a cursor for pagination.",
+ "type": "string"
+ },
+ "DiscoverRequest": {
+ "description": "A request from the client asking the server to advertise its supported\nprotocol versions, capabilities, and other metadata. Servers **MUST**\nimplement `server/discover`. Clients **MAY** call it but are not required\nto — version negotiation can also happen inline via per-request `_meta`.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "server/discover",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/RequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "DiscoverResult": {
+ "description": "The result returned by the server for a {@link DiscoverRequestserver/discover} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "cacheScope": {
+ "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).",
+ "enum": [
+ "private",
+ "public"
+ ],
+ "type": "string"
+ },
+ "capabilities": {
+ "$ref": "#/$defs/ServerCapabilities",
+ "description": "The capabilities of the server."
+ },
+ "instructions": {
+ "description": "Natural-language guidance describing the server and its features.\n\nThis can be used by clients to improve an LLM's understanding of\navailable tools (e.g., by including it in a system prompt). It should\nfocus on information that helps the model use the server effectively\nand should not duplicate information already in tool descriptions.",
+ "type": "string"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ },
+ "supportedVersions": {
+ "description": "MCP Protocol Versions this server supports. The client should choose a\nversion from this list for use in subsequent requests.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "ttlMs": {
+ "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "cacheScope",
+ "capabilities",
+ "resultType",
+ "supportedVersions",
+ "ttlMs"
+ ],
+ "type": "object"
+ },
+ "DiscoverResultResponse": {
+ "description": "A successful response from the server for a {@link DiscoverRequestserver/discover} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "$ref": "#/$defs/DiscoverResult"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "ElicitRequest": {
+ "description": "A request from the server to elicit additional information from the user via the client.",
+ "properties": {
+ "method": {
+ "const": "elicitation/create",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/ElicitRequestParams"
+ }
+ },
+ "required": [
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ElicitRequestFormParams": {
+ "description": "The parameters for a request to elicit non-sensitive information from the user via a form in the client.",
+ "properties": {
+ "message": {
+ "description": "The message to present to the user describing what information is being requested.",
+ "type": "string"
+ },
+ "mode": {
+ "const": "form",
+ "description": "The elicitation mode.",
+ "type": "string"
+ },
+ "requestedSchema": {
+ "description": "A restricted subset of JSON Schema.\nOnly top-level properties are allowed, without nesting.",
+ "properties": {
+ "$schema": {
+ "type": "string"
+ },
+ "properties": {
+ "additionalProperties": {
+ "$ref": "#/$defs/PrimitiveSchemaDefinition"
+ },
+ "type": "object"
+ },
+ "required": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "object",
+ "type": "string"
+ }
+ },
+ "required": [
+ "properties",
+ "type"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "message",
+ "requestedSchema"
+ ],
+ "type": "object"
+ },
+ "ElicitRequestParams": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/ElicitRequestFormParams"
+ },
+ {
+ "$ref": "#/$defs/ElicitRequestURLParams"
+ }
+ ],
+ "description": "The parameters for a request to elicit additional information from the user via the client."
+ },
+ "ElicitRequestURLParams": {
+ "description": "The parameters for a request to elicit information from the user via a URL in the client.",
+ "properties": {
+ "message": {
+ "description": "The message to present to the user explaining why the interaction is needed.",
+ "type": "string"
+ },
+ "mode": {
+ "const": "url",
+ "description": "The elicitation mode.",
+ "type": "string"
+ },
+ "url": {
+ "description": "The URL that the user should navigate to.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "message",
+ "mode",
+ "url"
+ ],
+ "type": "object"
+ },
+ "ElicitResult": {
+ "description": "The result returned by the client for an {@link ElicitRequestelicitation/create} request.",
+ "properties": {
+ "action": {
+ "description": "The user action in response to the elicitation.\n- `\"accept\"`: User submitted the form/confirmed the action\n- `\"decline\"`: User explicitly declined the action\n- `\"cancel\"`: User dismissed without making an explicit choice",
+ "enum": [
+ "accept",
+ "cancel",
+ "decline"
+ ],
+ "type": "string"
+ },
+ "content": {
+ "additionalProperties": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": [
+ "string",
+ "integer",
+ "boolean"
+ ]
+ }
+ ]
+ },
+ "description": "The submitted form data, only present when action is `\"accept\"` and mode was `\"form\"`.\nContains values matching the requested schema.\nOmitted for out-of-band mode responses.",
+ "type": "object"
+ }
+ },
+ "required": [
+ "action"
+ ],
+ "type": "object"
+ },
+ "EmbeddedResource": {
+ "description": "The contents of a resource, embedded into a prompt or tool call result.\n\nIt is up to the client how best to render embedded resources for the benefit\nof the LLM and/or the user.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "annotations": {
+ "$ref": "#/$defs/Annotations",
+ "description": "Optional annotations for the client."
+ },
+ "resource": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/TextResourceContents"
+ },
+ {
+ "$ref": "#/$defs/BlobResourceContents"
+ }
+ ]
+ },
+ "type": {
+ "const": "resource",
+ "type": "string"
+ }
+ },
+ "required": [
+ "resource",
+ "type"
+ ],
+ "type": "object"
+ },
+ "EmptyResult": {
+ "$ref": "#/$defs/Result",
+ "description": "Common result fields."
+ },
+ "EnumSchema": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/UntitledSingleSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/TitledSingleSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/UntitledMultiSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/TitledMultiSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/LegacyTitledEnumSchema"
+ }
+ ]
+ },
+ "Error": {
+ "properties": {
+ "code": {
+ "description": "The error type that occurred.",
+ "type": "integer"
+ },
+ "data": {
+ "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)."
+ },
+ "message": {
+ "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "message"
+ ],
+ "type": "object"
+ },
+ "GetPromptRequest": {
+ "description": "Used by the client to get a prompt provided by the server.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "prompts/get",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/GetPromptRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "GetPromptRequestParams": {
+ "description": "Parameters for a `prompts/get` request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ },
+ "arguments": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "description": "Arguments to use for templating the prompt.",
+ "type": "object"
+ },
+ "inputResponses": {
+ "$ref": "#/$defs/InputResponses"
+ },
+ "name": {
+ "description": "The name of the prompt or prompt template.",
+ "type": "string"
+ },
+ "requestState": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "_meta",
+ "name"
+ ],
+ "type": "object"
+ },
+ "GetPromptResult": {
+ "description": "The result returned by the server for a {@link GetPromptRequestprompts/get} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "description": {
+ "description": "An optional description for the prompt.",
+ "type": "string"
+ },
+ "messages": {
+ "items": {
+ "$ref": "#/$defs/PromptMessage"
+ },
+ "type": "array"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "messages",
+ "resultType"
+ ],
+ "type": "object"
+ },
+ "GetPromptResultResponse": {
+ "description": "A successful response from the server for a {@link GetPromptRequestprompts/get} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/InputRequiredResult"
+ },
+ {
+ "$ref": "#/$defs/GetPromptResult"
+ }
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "HeaderMismatchError": {
+ "description": "Returned when a server rejects a request because the values in the HTTP\nheaders do not match the corresponding values in the request body, or\nbecause required headers are missing or malformed. For HTTP, the response\nstatus code MUST be `400 Bad Request`.",
+ "properties": {
+ "error": {
+ "allOf": [
+ {
+ "$ref": "#/$defs/Error"
+ },
+ {
+ "properties": {
+ "code": {
+ "const": -32020,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "code"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ }
+ },
+ "required": [
+ "error",
+ "jsonrpc"
+ ],
+ "type": "object"
+ },
+ "Icon": {
+ "description": "An optionally-sized icon that can be displayed in a user interface.",
+ "properties": {
+ "mimeType": {
+ "description": "Optional MIME type override if the source MIME type is missing or generic.\nFor example: `\"image/png\"`, `\"image/jpeg\"`, or `\"image/svg+xml\"`.",
+ "type": "string"
+ },
+ "sizes": {
+ "description": "Optional array of strings that specify sizes at which the icon can be used.\nEach string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n\nIf not provided, the client should assume that the icon can be used at any size.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "src": {
+ "description": "A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a\n`data:` URI with Base64-encoded image data.\n\nConsumers SHOULD take steps to ensure URLs serving icons are from the\nsame domain as the client/server or a trusted domain.\n\nConsumers SHOULD take appropriate precautions when consuming SVGs as they can contain\nexecutable JavaScript.",
+ "format": "uri",
+ "type": "string"
+ },
+ "theme": {
+ "description": "Optional specifier for the theme this icon is designed for. `\"light\"` indicates\nthe icon is designed to be used with a light background, and `\"dark\"` indicates\nthe icon is designed to be used with a dark background.\n\nIf not provided, the client should assume the icon can be used with any theme.",
+ "enum": [
+ "dark",
+ "light"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "src"
+ ],
+ "type": "object"
+ },
+ "Icons": {
+ "description": "Base interface to add `icons` property.",
+ "properties": {
+ "icons": {
+ "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)",
+ "items": {
+ "$ref": "#/$defs/Icon"
+ },
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "ImageContent": {
+ "description": "An image provided to or from an LLM.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "annotations": {
+ "$ref": "#/$defs/Annotations",
+ "description": "Optional annotations for the client."
+ },
+ "data": {
+ "description": "The base64-encoded image data.",
+ "format": "byte",
+ "type": "string"
+ },
+ "mimeType": {
+ "description": "The MIME type of the image. Different providers may support different image types.",
+ "type": "string"
+ },
+ "type": {
+ "const": "image",
+ "type": "string"
+ }
+ },
+ "required": [
+ "data",
+ "mimeType",
+ "type"
+ ],
+ "type": "object"
+ },
+ "Implementation": {
+ "description": "Describes the MCP implementation.",
+ "properties": {
+ "description": {
+ "description": "An optional human-readable description of what this implementation does.\n\nThis can be used by clients or servers to provide context about their purpose\nand capabilities. For example, a server might describe the types of resources\nor tools it provides, while a client might describe its intended use case.",
+ "type": "string"
+ },
+ "icons": {
+ "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)",
+ "items": {
+ "$ref": "#/$defs/Icon"
+ },
+ "type": "array"
+ },
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ },
+ "version": {
+ "description": "The version of this implementation.",
+ "type": "string"
+ },
+ "websiteUrl": {
+ "description": "An optional URL of the website for this implementation.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "version"
+ ],
+ "type": "object"
+ },
+ "InputRequest": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/CreateMessageRequest"
+ },
+ {
+ "$ref": "#/$defs/ListRootsRequest"
+ },
+ {
+ "$ref": "#/$defs/ElicitRequest"
+ }
+ ]
+ },
+ "InputRequests": {
+ "additionalProperties": {
+ "$ref": "#/$defs/InputRequest"
+ },
+ "description": "A map of server-initiated requests that the client must fulfill.\nKeys are server-assigned identifiers; values are the request objects.",
+ "type": "object"
+ },
+ "InputRequiredResult": {
+ "description": "An InputRequiredResult sent by the server to indicate that additional input is needed\nbefore the request can be completed.\n\nAt least one of `inputRequests` or `requestState` MUST be present.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "inputRequests": {
+ "$ref": "#/$defs/InputRequests"
+ },
+ "requestState": {
+ "type": "string"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "resultType"
+ ],
+ "type": "object"
+ },
+ "InputResponse": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/CreateMessageResult"
+ },
+ {
+ "$ref": "#/$defs/ListRootsResult"
+ },
+ {
+ "$ref": "#/$defs/ElicitResult"
+ }
+ ]
+ },
+ "InputResponseRequestParams": {
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ },
+ "inputResponses": {
+ "$ref": "#/$defs/InputResponses"
+ },
+ "requestState": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "_meta"
+ ],
+ "type": "object"
+ },
+ "InputResponses": {
+ "additionalProperties": {
+ "$ref": "#/$defs/InputResponse"
+ },
+ "description": "A map of client responses to server-initiated requests.\nKeys correspond to the keys in the {@link InputRequests} map;\nvalues are the client's result for each request.",
+ "type": "object"
+ },
+ "InternalError": {
+ "description": "A JSON-RPC error indicating that an internal error occurred on the receiver. This error is returned when the receiver encounters an unexpected condition that prevents it from fulfilling the request.",
+ "properties": {
+ "code": {
+ "const": -32603,
+ "description": "The error type that occurred.",
+ "type": "integer"
+ },
+ "data": {
+ "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)."
+ },
+ "message": {
+ "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "message"
+ ],
+ "type": "object"
+ },
+ "InvalidParamsError": {
+ "description": "A JSON-RPC error indicating that the method parameters are invalid or malformed.\n\nIn MCP, this error is returned in various contexts when request parameters fail validation:\n\n- **Tools**: Unknown tool name or invalid tool arguments\n- **Prompts**: Unknown prompt name or missing required arguments\n- **Pagination**: Invalid or expired cursor values\n- **Logging**: Invalid log level\n- **Elicitation**: Server requests an elicitation mode not declared in client capabilities\n- **Sampling**: Missing tool result or tool results mixed with other content",
+ "properties": {
+ "code": {
+ "const": -32602,
+ "description": "The error type that occurred.",
+ "type": "integer"
+ },
+ "data": {
+ "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)."
+ },
+ "message": {
+ "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "message"
+ ],
+ "type": "object"
+ },
+ "InvalidRequestError": {
+ "description": "A JSON-RPC error indicating that the request is not a valid request object. This error is returned when the message structure does not conform to the JSON-RPC 2.0 specification requirements for a request (e.g., missing required fields like `jsonrpc` or `method`, or using invalid types for these fields).",
+ "properties": {
+ "code": {
+ "const": -32600,
+ "description": "The error type that occurred.",
+ "type": "integer"
+ },
+ "data": {
+ "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)."
+ },
+ "message": {
+ "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "message"
+ ],
+ "type": "object"
+ },
+ "JSONArray": {
+ "items": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "type": "array"
+ },
+ "JSONObject": {
+ "additionalProperties": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "type": "object"
+ },
+ "JSONRPCErrorResponse": {
+ "description": "A response to a request that indicates an error occurred.",
+ "properties": {
+ "error": {
+ "$ref": "#/$defs/Error"
+ },
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ }
+ },
+ "required": [
+ "error",
+ "jsonrpc"
+ ],
+ "type": "object"
+ },
+ "JSONRPCMessage": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/JSONRPCRequest"
+ },
+ {
+ "$ref": "#/$defs/JSONRPCNotification"
+ },
+ {
+ "$ref": "#/$defs/JSONRPCResultResponse"
+ },
+ {
+ "$ref": "#/$defs/JSONRPCErrorResponse"
+ }
+ ],
+ "description": "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent."
+ },
+ "JSONRPCNotification": {
+ "description": "A notification which does not expect a response.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "type": "string"
+ },
+ "params": {
+ "additionalProperties": {},
+ "type": "object"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method"
+ ],
+ "type": "object"
+ },
+ "JSONRPCRequest": {
+ "description": "A request that expects a response.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "type": "string"
+ },
+ "params": {
+ "additionalProperties": {},
+ "type": "object"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method"
+ ],
+ "type": "object"
+ },
+ "JSONRPCResponse": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/JSONRPCResultResponse"
+ },
+ {
+ "$ref": "#/$defs/JSONRPCErrorResponse"
+ }
+ ],
+ "description": "A response to a request, containing either the result or error."
+ },
+ "JSONRPCResultResponse": {
+ "description": "A successful (non-error) response to a request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "$ref": "#/$defs/Result"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "JSONValue": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/JSONObject"
+ },
+ {
+ "items": {
+ "$ref": "#/$defs/JSONValue"
+ },
+ "type": "array"
+ },
+ {
+ "type": [
+ "string",
+ "integer",
+ "boolean"
+ ]
+ }
+ ]
+ },
+ "LegacyTitledEnumSchema": {
+ "description": "Use {@link TitledSingleSelectEnumSchema} instead.\nThis interface will be removed in a future version.",
+ "properties": {
+ "default": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "enum": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "enumNames": {
+ "description": "(Legacy) Display names for enum values.\nNon-standard according to JSON schema 2020-12.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "title": {
+ "type": "string"
+ },
+ "type": {
+ "const": "string",
+ "type": "string"
+ }
+ },
+ "required": [
+ "enum",
+ "type"
+ ],
+ "type": "object"
+ },
+ "ListPromptsRequest": {
+ "description": "Sent from the client to request a list of prompts and prompt templates the server has.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "prompts/list",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/PaginatedRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ListPromptsResult": {
+ "description": "The result returned by the server for a {@link ListPromptsRequestprompts/list} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "cacheScope": {
+ "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).",
+ "enum": [
+ "private",
+ "public"
+ ],
+ "type": "string"
+ },
+ "nextCursor": {
+ "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
+ "type": "string"
+ },
+ "prompts": {
+ "items": {
+ "$ref": "#/$defs/Prompt"
+ },
+ "type": "array"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ },
+ "ttlMs": {
+ "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "cacheScope",
+ "prompts",
+ "resultType",
+ "ttlMs"
+ ],
+ "type": "object"
+ },
+ "ListPromptsResultResponse": {
+ "description": "A successful response from the server for a {@link ListPromptsRequestprompts/list} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "$ref": "#/$defs/ListPromptsResult"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "ListResourceTemplatesRequest": {
+ "description": "Sent from the client to request a list of resource templates the server has.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "resources/templates/list",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/PaginatedRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ListResourceTemplatesResult": {
+ "description": "The result returned by the server for a {@link ListResourceTemplatesRequestresources/templates/list} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "cacheScope": {
+ "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).",
+ "enum": [
+ "private",
+ "public"
+ ],
+ "type": "string"
+ },
+ "nextCursor": {
+ "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
+ "type": "string"
+ },
+ "resourceTemplates": {
+ "items": {
+ "$ref": "#/$defs/ResourceTemplate"
+ },
+ "type": "array"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ },
+ "ttlMs": {
+ "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "cacheScope",
+ "resourceTemplates",
+ "resultType",
+ "ttlMs"
+ ],
+ "type": "object"
+ },
+ "ListResourceTemplatesResultResponse": {
+ "description": "A successful response from the server for a {@link ListResourceTemplatesRequestresources/templates/list} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "$ref": "#/$defs/ListResourceTemplatesResult"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "ListResourcesRequest": {
+ "description": "Sent from the client to request a list of resources the server has.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "resources/list",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/PaginatedRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ListResourcesResult": {
+ "description": "The result returned by the server for a {@link ListResourcesRequestresources/list} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "cacheScope": {
+ "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).",
+ "enum": [
+ "private",
+ "public"
+ ],
+ "type": "string"
+ },
+ "nextCursor": {
+ "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
+ "type": "string"
+ },
+ "resources": {
+ "items": {
+ "$ref": "#/$defs/Resource"
+ },
+ "type": "array"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ },
+ "ttlMs": {
+ "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "cacheScope",
+ "resources",
+ "resultType",
+ "ttlMs"
+ ],
+ "type": "object"
+ },
+ "ListResourcesResultResponse": {
+ "description": "A successful response from the server for a {@link ListResourcesRequestresources/list} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "$ref": "#/$defs/ListResourcesResult"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "ListRootsRequest": {
+ "description": "Sent from the server to request a list of root URIs from the client. Roots allow\nservers to ask for specific directories or files to operate on. A common example\nfor roots is providing a set of repositories or directories a server should operate\non.\n\nThis request is typically used when the server needs to understand the file system\nstructure or access specific locations that the client has permission to read from.",
+ "properties": {
+ "method": {
+ "const": "roots/list",
+ "type": "string"
+ },
+ "params": {
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ }
+ },
+ "type": "object"
+ }
+ },
+ "required": [
+ "method"
+ ],
+ "type": "object"
+ },
+ "ListRootsResult": {
+ "description": "The result returned by the client for a {@link ListRootsRequestroots/list} request.\nThis result contains an array of {@link Root} objects, each representing a root directory\nor file that the server can operate on.",
+ "properties": {
+ "roots": {
+ "items": {
+ "$ref": "#/$defs/Root"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "roots"
+ ],
+ "type": "object"
+ },
+ "ListToolsRequest": {
+ "description": "Sent from the client to request a list of tools the server has.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "tools/list",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/PaginatedRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ListToolsResult": {
+ "description": "The result returned by the server for a {@link ListToolsRequesttools/list} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "cacheScope": {
+ "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).",
+ "enum": [
+ "private",
+ "public"
+ ],
+ "type": "string"
+ },
+ "nextCursor": {
+ "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
+ "type": "string"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ },
+ "tools": {
+ "items": {
+ "$ref": "#/$defs/Tool"
+ },
+ "type": "array"
+ },
+ "ttlMs": {
+ "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "cacheScope",
+ "resultType",
+ "tools",
+ "ttlMs"
+ ],
+ "type": "object"
+ },
+ "ListToolsResultResponse": {
+ "description": "A successful response from the server for a {@link ListToolsRequesttools/list} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "$ref": "#/$defs/ListToolsResult"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "LoggingLevel": {
+ "description": "The severity of a log message.\n\nThese map to syslog message severities, as specified in RFC-5424:\nhttps://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1",
+ "enum": [
+ "alert",
+ "critical",
+ "debug",
+ "emergency",
+ "error",
+ "info",
+ "notice",
+ "warning"
+ ],
+ "type": "string"
+ },
+ "LoggingMessageNotification": {
+ "description": "JSONRPCNotification of a log message passed from server to client. The client opts in by setting `\"io.modelcontextprotocol/logLevel\"` in a request's `_meta`.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/message",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/LoggingMessageNotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "LoggingMessageNotificationParams": {
+ "description": "Parameters for a `notifications/message` notification.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/NotificationMetaObject"
+ },
+ "data": {
+ "description": "The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here."
+ },
+ "level": {
+ "$ref": "#/$defs/LoggingLevel",
+ "description": "The severity of this log message."
+ },
+ "logger": {
+ "description": "An optional name of the logger issuing this message.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "data",
+ "level"
+ ],
+ "type": "object"
+ },
+ "MetaObject": {
+ "description": "Represents the contents of a `_meta` field, which clients and servers use to attach additional metadata to their interactions.\n\nCertain key names are reserved by MCP for protocol-level metadata; implementations MUST NOT make assumptions about values at these keys. Additionally, specific schema definitions may reserve particular names for purpose-specific metadata, as declared in those definitions.\n\nValid keys have two segments:\n\n**Prefix:**\n- Optional — if specified, MUST be a series of _labels_ separated by dots (`.`), followed by a slash (`/`).\n- Labels MUST start with a letter and end with a letter or digit. Interior characters may be letters, digits, or hyphens (`-`).\n- Implementations SHOULD use reverse DNS notation (e.g., `com.example/` rather than `example.com/`).\n- Any prefix where the second label is `modelcontextprotocol` or `mcp` is **reserved** for MCP use. For example: `io.modelcontextprotocol/`, `dev.mcp/`, `org.modelcontextprotocol.api/`, and `com.mcp.tools/` are all reserved. However, `com.example.mcp/` is NOT reserved, as the second label is `example`.\n\n**Name:**\n- Unless empty, MUST start and end with an alphanumeric character (`[a-z0-9A-Z]`).\n- Interior characters may be alphanumeric, hyphens (`-`), underscores (`_`), or dots (`.`).",
+ "type": "object"
+ },
+ "MethodNotFoundError": {
+ "description": "A JSON-RPC error indicating that the requested method does not exist or is not available.\n\nIn MCP, a server returns this error when a client invokes a method the server does not implement — either a genuinely unknown method, or one gated behind a server capability the server did not advertise (e.g., calling `prompts/list` when the `prompts` capability was not advertised).\n\nA request that requires a client capability the client did not declare is signalled instead by {@link MissingRequiredClientCapabilityError} (`-32021`).",
+ "properties": {
+ "code": {
+ "const": -32601,
+ "description": "The error type that occurred.",
+ "type": "integer"
+ },
+ "data": {
+ "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)."
+ },
+ "message": {
+ "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "message"
+ ],
+ "type": "object"
+ },
+ "MissingRequiredClientCapabilityError": {
+ "description": "Returned when processing a request requires a capability the client did not\ndeclare in `clientCapabilities`. For HTTP, the response status code MUST be\n`400 Bad Request`.",
+ "properties": {
+ "error": {
+ "allOf": [
+ {
+ "$ref": "#/$defs/Error"
+ },
+ {
+ "properties": {
+ "code": {
+ "const": -32021,
+ "type": "integer"
+ },
+ "data": {
+ "properties": {
+ "requiredCapabilities": {
+ "$ref": "#/$defs/ClientCapabilities",
+ "description": "The capabilities the server requires from the client to process this request."
+ }
+ },
+ "required": [
+ "requiredCapabilities"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "code",
+ "data"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ }
+ },
+ "required": [
+ "error",
+ "jsonrpc"
+ ],
+ "type": "object"
+ },
+ "ModelHint": {
+ "description": "Hints to use for model selection.\n\nKeys not declared here are currently left unspecified by the spec and are up\nto the client to interpret.",
+ "properties": {
+ "name": {
+ "description": "A hint for a model name.\n\nThe client SHOULD treat this as a substring of a model name; for example:\n - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n - `claude` should match any Claude model\n\nThe client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example:\n - `gemini-1.5-flash` could match `claude-3-haiku-20240307`",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "ModelPreferences": {
+ "description": "The server's preferences for model selection, requested of the client during sampling.\n\nBecause LLMs can vary along multiple dimensions, choosing the \"best\" model is\nrarely straightforward. Different models excel in different areas—some are\nfaster but less capable, others are more capable but more expensive, and so\non. This interface allows servers to express their priorities across multiple\ndimensions to help clients make an appropriate selection for their use case.\n\nThese preferences are always advisory. The client MAY ignore them. It is also\nup to the client to decide how to interpret these preferences and how to\nbalance them against other considerations.",
+ "properties": {
+ "costPriority": {
+ "description": "How much to prioritize cost when selecting a model. A value of 0 means cost\nis not important, while a value of 1 means cost is the most important\nfactor.",
+ "maximum": 1,
+ "minimum": 0,
+ "type": "number"
+ },
+ "hints": {
+ "description": "Optional hints to use for model selection.\n\nIf multiple hints are specified, the client MUST evaluate them in order\n(such that the first match is taken).\n\nThe client SHOULD prioritize these hints over the numeric priorities, but\nMAY still use the priorities to select from ambiguous matches.",
+ "items": {
+ "$ref": "#/$defs/ModelHint"
+ },
+ "type": "array"
+ },
+ "intelligencePriority": {
+ "description": "How much to prioritize intelligence and capabilities when selecting a\nmodel. A value of 0 means intelligence is not important, while a value of 1\nmeans intelligence is the most important factor.",
+ "maximum": 1,
+ "minimum": 0,
+ "type": "number"
+ },
+ "speedPriority": {
+ "description": "How much to prioritize sampling speed (latency) when selecting a model. A\nvalue of 0 means speed is not important, while a value of 1 means speed is\nthe most important factor.",
+ "maximum": 1,
+ "minimum": 0,
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "MultiSelectEnumSchema": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/UntitledMultiSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/TitledMultiSelectEnumSchema"
+ }
+ ]
+ },
+ "Notification": {
+ "properties": {
+ "method": {
+ "type": "string"
+ },
+ "params": {
+ "additionalProperties": {},
+ "type": "object"
+ }
+ },
+ "required": [
+ "method"
+ ],
+ "type": "object"
+ },
+ "NotificationMetaObject": {
+ "description": "Extends {@link MetaObject} with additional notification-specific fields. All key naming rules from `MetaObject` apply.",
+ "properties": {
+ "io.modelcontextprotocol/subscriptionId": {
+ "$ref": "#/$defs/RequestId",
+ "description": "Identifies the subscription stream a notification was delivered on. The\nserver MUST include this key on every notification delivered via a\n{@link SubscriptionsListenRequestsubscriptions/listen} stream, so the\nclient can correlate the notification with the originating subscription.\nThe key is absent on notifications not delivered via a subscription\nstream (e.g. progress notifications for an in-flight request), which is\nwhy it is optional here.\n\nThe value is the JSON-RPC ID of the `subscriptions/listen` request that\nopened the stream."
+ }
+ },
+ "type": "object"
+ },
+ "NotificationParams": {
+ "description": "Common params for any notification.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/NotificationMetaObject"
+ }
+ },
+ "type": "object"
+ },
+ "NumberSchema": {
+ "properties": {
+ "default": {
+ "type": "number"
+ },
+ "description": {
+ "type": "string"
+ },
+ "maximum": {
+ "type": "number"
+ },
+ "minimum": {
+ "type": "number"
+ },
+ "title": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "integer",
+ "number"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ "PaginatedRequest": {
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/PaginatedRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "PaginatedRequestParams": {
+ "description": "Common params for paginated requests.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ },
+ "cursor": {
+ "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "_meta"
+ ],
+ "type": "object"
+ },
+ "PaginatedResult": {
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "nextCursor": {
+ "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.",
+ "type": "string"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "resultType"
+ ],
+ "type": "object"
+ },
+ "ParseError": {
+ "description": "A JSON-RPC error indicating that invalid JSON was received by the server. This error is returned when the server cannot parse the JSON text of a message.",
+ "properties": {
+ "code": {
+ "const": -32700,
+ "description": "The error type that occurred.",
+ "type": "integer"
+ },
+ "data": {
+ "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)."
+ },
+ "message": {
+ "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "message"
+ ],
+ "type": "object"
+ },
+ "PrimitiveSchemaDefinition": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/StringSchema"
+ },
+ {
+ "$ref": "#/$defs/NumberSchema"
+ },
+ {
+ "$ref": "#/$defs/BooleanSchema"
+ },
+ {
+ "$ref": "#/$defs/UntitledSingleSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/TitledSingleSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/UntitledMultiSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/TitledMultiSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/LegacyTitledEnumSchema"
+ }
+ ],
+ "description": "Restricted schema definitions that only allow primitive types\nwithout nested objects or arrays."
+ },
+ "ProgressNotification": {
+ "description": "An out-of-band notification used to inform the receiver of a progress update for a long-running request.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/progress",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/ProgressNotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ProgressNotificationParams": {
+ "description": "Parameters for a {@link ProgressNotificationnotifications/progress} notification.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/NotificationMetaObject"
+ },
+ "message": {
+ "description": "An optional message describing the current progress.",
+ "type": "string"
+ },
+ "progress": {
+ "description": "The progress thus far. This should increase every time progress is made, even if the total is unknown.",
+ "type": "number"
+ },
+ "progressToken": {
+ "$ref": "#/$defs/ProgressToken",
+ "description": "The progress token which was given in the initial request, used to associate this notification with the request that is proceeding."
+ },
+ "total": {
+ "description": "Total number of items to process (or total progress required), if known.",
+ "type": "number"
+ }
+ },
+ "required": [
+ "progress",
+ "progressToken"
+ ],
+ "type": "object"
+ },
+ "ProgressToken": {
+ "description": "A progress token, used to associate progress notifications with the original request.",
+ "type": [
+ "string",
+ "integer"
+ ]
+ },
+ "Prompt": {
+ "description": "A prompt or prompt template that the server offers.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "arguments": {
+ "description": "A list of arguments to use for templating the prompt.",
+ "items": {
+ "$ref": "#/$defs/PromptArgument"
+ },
+ "type": "array"
+ },
+ "description": {
+ "description": "An optional description of what this prompt provides",
+ "type": "string"
+ },
+ "icons": {
+ "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)",
+ "items": {
+ "$ref": "#/$defs/Icon"
+ },
+ "type": "array"
+ },
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "type": "object"
+ },
+ "PromptArgument": {
+ "description": "Describes an argument that a prompt can accept.",
+ "properties": {
+ "description": {
+ "description": "A human-readable description of the argument.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "required": {
+ "description": "Whether this argument must be provided.",
+ "type": "boolean"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "type": "object"
+ },
+ "PromptListChangedNotification": {
+ "description": "An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This is only delivered on a {@link SubscriptionsListenRequestsubscriptions/listen} stream when the client requested it via the `promptsListChanged` filter field.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/prompts/list_changed",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/NotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method"
+ ],
+ "type": "object"
+ },
+ "PromptMessage": {
+ "description": "Describes a message returned as part of a prompt.\n\nThis is similar to {@link SamplingMessage}, but also supports the embedding of\nresources from the MCP server.",
+ "properties": {
+ "content": {
+ "$ref": "#/$defs/ContentBlock"
+ },
+ "role": {
+ "$ref": "#/$defs/Role"
+ }
+ },
+ "required": [
+ "content",
+ "role"
+ ],
+ "type": "object"
+ },
+ "PromptReference": {
+ "description": "Identifies a prompt.",
+ "properties": {
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ },
+ "type": {
+ "const": "ref/prompt",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "type"
+ ],
+ "type": "object"
+ },
+ "ReadResourceRequest": {
+ "description": "Sent from the client to the server, to read a specific resource URI.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "resources/read",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/ReadResourceRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ReadResourceRequestParams": {
+ "description": "Parameters for a `resources/read` request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ },
+ "inputResponses": {
+ "$ref": "#/$defs/InputResponses"
+ },
+ "requestState": {
+ "type": "string"
+ },
+ "uri": {
+ "description": "The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "_meta",
+ "uri"
+ ],
+ "type": "object"
+ },
+ "ReadResourceResult": {
+ "description": "The result returned by the server for a {@link ReadResourceRequestresources/read} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "cacheScope": {
+ "description": "Indicates the intended scope of the cached response, analogous to HTTP\n`Cache-Control: public` vs `Cache-Control: private`.\n\n- `\"public\"`: The response does not contain user-specific data. Any\n client or intermediary (e.g., shared gateway, caching proxy) MAY cache\n the response and serve it across authorization contexts.\n- `\"private\"`: The response MAY be cached and reused only within the\n same authorization context. Caches MUST NOT be shared across\n authorization contexts (e.g., a different access token requires a\n different cache).",
+ "enum": [
+ "private",
+ "public"
+ ],
+ "type": "string"
+ },
+ "contents": {
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/TextResourceContents"
+ },
+ {
+ "$ref": "#/$defs/BlobResourceContents"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ },
+ "ttlMs": {
+ "description": "A hint from the server indicating how long (in milliseconds) the\nclient MAY cache this response before re-fetching. Semantics are\nanalogous to HTTP Cache-Control max-age.\n\n- If 0, The response SHOULD be considered immediately stale,\n The client MAY re-fetch every time the result is needed.\n- If positive, the client SHOULD consider the result fresh for this many\n milliseconds after receiving the response.",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "cacheScope",
+ "contents",
+ "resultType",
+ "ttlMs"
+ ],
+ "type": "object"
+ },
+ "ReadResourceResultResponse": {
+ "description": "A successful response from the server for a {@link ReadResourceRequestresources/read} request.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/InputRequiredResult"
+ },
+ {
+ "$ref": "#/$defs/ReadResourceResult"
+ }
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "Request": {
+ "properties": {
+ "method": {
+ "type": "string"
+ },
+ "params": {
+ "additionalProperties": {},
+ "type": "object"
+ }
+ },
+ "required": [
+ "method"
+ ],
+ "type": "object"
+ },
+ "RequestId": {
+ "description": "A uniquely identifying ID for a request in JSON-RPC.",
+ "type": [
+ "string",
+ "integer"
+ ]
+ },
+ "RequestMetaObject": {
+ "description": "Extends {@link MetaObject} with additional request-specific fields. All key naming rules from `MetaObject` apply.",
+ "properties": {
+ "io.modelcontextprotocol/clientCapabilities": {
+ "$ref": "#/$defs/ClientCapabilities",
+ "description": "The client's capabilities for this specific request. Required.\n\nCapabilities are declared per-request rather than once at initialization;\nan empty object means the client supports no optional capabilities.\nServers MUST NOT infer capabilities from prior requests."
+ },
+ "io.modelcontextprotocol/clientInfo": {
+ "$ref": "#/$defs/Implementation",
+ "description": "Identifies the client software making the request. Clients SHOULD\ninclude this field on every request unless specifically configured not\nto do so.\n\nThe {@link Implementation} schema requires `name` and `version`; other\nfields are optional.\n\nThe value is self-reported by the client and is not verified by the\nprotocol. It is intended for display, logging, and debugging. Servers\nSHOULD NOT use it to change their behavior, and SHOULD NOT rely on it for\nsecurity decisions."
+ },
+ "io.modelcontextprotocol/logLevel": {
+ "$ref": "#/$defs/LoggingLevel",
+ "description": "The desired log level for this request. Optional.\n\nIf absent, the server MUST NOT send any {@link LoggingMessageNotificationnotifications/message}\nnotifications for this request. The client opts in to log messages by\nexplicitly setting a level. Replaces the former `logging/setLevel` RPC."
+ },
+ "io.modelcontextprotocol/protocolVersion": {
+ "description": "The MCP Protocol Version being used for this request. Required.\n\nFor the HTTP transport, this value MUST match the `MCP-Protocol-Version`\nheader; otherwise the server MUST return a `400 Bad Request`. If the\nserver does not support the requested version, it MUST return an\n{@link UnsupportedProtocolVersionError}.",
+ "type": "string"
+ },
+ "progressToken": {
+ "$ref": "#/$defs/ProgressToken",
+ "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by {@link ProgressNotificationnotifications/progress}). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications."
+ }
+ },
+ "required": [
+ "io.modelcontextprotocol/clientCapabilities",
+ "io.modelcontextprotocol/protocolVersion"
+ ],
+ "type": "object"
+ },
+ "RequestParams": {
+ "description": "Common params for any request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ }
+ },
+ "required": [
+ "_meta"
+ ],
+ "type": "object"
+ },
+ "Resource": {
+ "description": "A known resource that the server is capable of reading.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "annotations": {
+ "$ref": "#/$defs/Annotations",
+ "description": "Optional annotations for the client."
+ },
+ "description": {
+ "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.",
+ "type": "string"
+ },
+ "icons": {
+ "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)",
+ "items": {
+ "$ref": "#/$defs/Icon"
+ },
+ "type": "array"
+ },
+ "mimeType": {
+ "description": "The MIME type of this resource, if known.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "size": {
+ "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.",
+ "type": "integer"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ },
+ "uri": {
+ "description": "The URI of this resource.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "uri"
+ ],
+ "type": "object"
+ },
+ "ResourceContents": {
+ "description": "The contents of a specific resource or sub-resource.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "mimeType": {
+ "description": "The MIME type of this resource, if known.",
+ "type": "string"
+ },
+ "uri": {
+ "description": "The URI of this resource.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "uri"
+ ],
+ "type": "object"
+ },
+ "ResourceLink": {
+ "description": "A resource that the server is capable of reading, included in a prompt or tool call result.\n\nNote: resource links returned by tools are not guaranteed to appear in the results of {@link ListResourcesRequestresources/list} requests.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "annotations": {
+ "$ref": "#/$defs/Annotations",
+ "description": "Optional annotations for the client."
+ },
+ "description": {
+ "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.",
+ "type": "string"
+ },
+ "icons": {
+ "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)",
+ "items": {
+ "$ref": "#/$defs/Icon"
+ },
+ "type": "array"
+ },
+ "mimeType": {
+ "description": "The MIME type of this resource, if known.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "size": {
+ "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.",
+ "type": "integer"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ },
+ "type": {
+ "const": "resource_link",
+ "type": "string"
+ },
+ "uri": {
+ "description": "The URI of this resource.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "type",
+ "uri"
+ ],
+ "type": "object"
+ },
+ "ResourceListChangedNotification": {
+ "description": "An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This is only delivered on a {@link SubscriptionsListenRequestsubscriptions/listen} stream when the client requested it via the `resourcesListChanged` filter field.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/resources/list_changed",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/NotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method"
+ ],
+ "type": "object"
+ },
+ "ResourceRequestParams": {
+ "description": "Common params for resource-related requests.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ },
+ "uri": {
+ "description": "The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "_meta",
+ "uri"
+ ],
+ "type": "object"
+ },
+ "ResourceTemplate": {
+ "description": "A template description for resources available on the server.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "annotations": {
+ "$ref": "#/$defs/Annotations",
+ "description": "Optional annotations for the client."
+ },
+ "description": {
+ "description": "A description of what this template is for.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.",
+ "type": "string"
+ },
+ "icons": {
+ "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)",
+ "items": {
+ "$ref": "#/$defs/Icon"
+ },
+ "type": "array"
+ },
+ "mimeType": {
+ "description": "The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.",
+ "type": "string"
+ },
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ },
+ "uriTemplate": {
+ "description": "A URI template (according to RFC 6570) that can be used to construct resource URIs.",
+ "format": "uri-template",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "uriTemplate"
+ ],
+ "type": "object"
+ },
+ "ResourceTemplateReference": {
+ "description": "A reference to a resource or resource template definition.",
+ "properties": {
+ "type": {
+ "const": "ref/resource",
+ "type": "string"
+ },
+ "uri": {
+ "description": "The URI or URI template of the resource.",
+ "format": "uri-template",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "uri"
+ ],
+ "type": "object"
+ },
+ "ResourceUpdatedNotification": {
+ "description": "A notification from the server to the client, informing it that a resource has changed and may need to be read again. This is only sent for resources the client opted in to via the `resourceSubscriptions` field of a {@link SubscriptionsListenRequestsubscriptions/listen} request.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/resources/updated",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/ResourceUpdatedNotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "ResourceUpdatedNotificationParams": {
+ "description": "Parameters for a `notifications/resources/updated` notification.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/NotificationMetaObject"
+ },
+ "uri": {
+ "description": "The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "uri"
+ ],
+ "type": "object"
+ },
+ "Result": {
+ "additionalProperties": {},
+ "description": "Common result fields.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/ResultMetaObject"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "resultType"
+ ],
+ "type": "object"
+ },
+ "ResultMetaObject": {
+ "description": "Extends {@link MetaObject} with additional result-specific fields. All key naming rules from `MetaObject` apply.",
+ "properties": {
+ "io.modelcontextprotocol/serverInfo": {
+ "$ref": "#/$defs/Implementation",
+ "description": "Identifies the server software producing the response. Servers SHOULD\ninclude this field on every response unless specifically configured not\nto do so.\n\nThe {@link Implementation} schema requires `name` and `version`; other\nfields are optional.\n\nThe value is self-reported by the server and is not verified by the\nprotocol. It is intended for display, logging, and debugging. Clients\nSHOULD NOT use it to change their behavior, and SHOULD NOT rely on it for\nsecurity decisions."
+ }
+ },
+ "type": "object"
+ },
+ "ResultType": {
+ "description": "Indicates the type of a {@link Result} object, allowing the client to\ndetermine how to parse the response.\n\ncomplete - the request completed successfully and the result contains the final content.\ninput_required - the request requires additional input and the result contains an {@link InputRequiredResult} object with instructions for the client to provide additional input before retrying the original request.",
+ "type": "string"
+ },
+ "Role": {
+ "description": "The sender or recipient of messages and data in a conversation.",
+ "enum": [
+ "assistant",
+ "user"
+ ],
+ "type": "string"
+ },
+ "Root": {
+ "description": "Represents a root directory or file that the server can operate on.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "name": {
+ "description": "An optional name for the root. This can be used to provide a human-readable\nidentifier for the root, which may be useful for display purposes or for\nreferencing the root in other parts of the application.",
+ "type": "string"
+ },
+ "uri": {
+ "description": "The URI identifying the root. This *must* start with `file://` for now.\nThis restriction may be relaxed in future versions of the protocol to allow\nother URI schemes.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "uri"
+ ],
+ "type": "object"
+ },
+ "SamplingMessage": {
+ "description": "Describes a message issued to or received from an LLM API.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "content": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/TextContent"
+ },
+ {
+ "$ref": "#/$defs/ImageContent"
+ },
+ {
+ "$ref": "#/$defs/AudioContent"
+ },
+ {
+ "$ref": "#/$defs/ToolUseContent"
+ },
+ {
+ "$ref": "#/$defs/ToolResultContent"
+ },
+ {
+ "items": {
+ "$ref": "#/$defs/SamplingMessageContentBlock"
+ },
+ "type": "array"
+ }
+ ]
+ },
+ "role": {
+ "$ref": "#/$defs/Role"
+ }
+ },
+ "required": [
+ "content",
+ "role"
+ ],
+ "type": "object"
+ },
+ "SamplingMessageContentBlock": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/TextContent"
+ },
+ {
+ "$ref": "#/$defs/ImageContent"
+ },
+ {
+ "$ref": "#/$defs/AudioContent"
+ },
+ {
+ "$ref": "#/$defs/ToolUseContent"
+ },
+ {
+ "$ref": "#/$defs/ToolResultContent"
+ }
+ ]
+ },
+ "ServerCapabilities": {
+ "description": "Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.",
+ "properties": {
+ "completions": {
+ "$ref": "#/$defs/JSONObject",
+ "description": "Present if the server supports argument autocompletion suggestions."
+ },
+ "experimental": {
+ "additionalProperties": {
+ "$ref": "#/$defs/JSONObject"
+ },
+ "description": "Experimental, non-standard capabilities that the server supports.",
+ "type": "object"
+ },
+ "extensions": {
+ "additionalProperties": {
+ "$ref": "#/$defs/JSONObject"
+ },
+ "description": "Optional MCP extensions that the server supports. Keys are extension identifiers\n(e.g., \"io.modelcontextprotocol/tasks\"), and values are per-extension settings\nobjects. An empty object indicates support with no settings.\n\nKeys MUST follow the {@link MetaObject`_meta` key naming rules}, with a\nmandatory prefix.",
+ "type": "object"
+ },
+ "logging": {
+ "$ref": "#/$defs/JSONObject",
+ "description": "Present if the server supports sending log messages to the client."
+ },
+ "prompts": {
+ "description": "Present if the server offers any prompt templates.",
+ "properties": {
+ "listChanged": {
+ "description": "Whether this server supports notifications for changes to the prompt list.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "resources": {
+ "description": "Present if the server offers any resources to read.",
+ "properties": {
+ "listChanged": {
+ "description": "Whether this server supports notifications for changes to the resource list.",
+ "type": "boolean"
+ },
+ "subscribe": {
+ "description": "Whether this server supports subscribing to resource updates.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "tools": {
+ "description": "Present if the server offers any tools to call.",
+ "properties": {
+ "listChanged": {
+ "description": "Whether this server supports notifications for changes to the tool list.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ }
+ },
+ "type": "object"
+ },
+ "ServerNotification": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/CancelledNotification"
+ },
+ {
+ "$ref": "#/$defs/ProgressNotification"
+ },
+ {
+ "$ref": "#/$defs/ResourceListChangedNotification"
+ },
+ {
+ "$ref": "#/$defs/SubscriptionsAcknowledgedNotification"
+ },
+ {
+ "$ref": "#/$defs/ResourceUpdatedNotification"
+ },
+ {
+ "$ref": "#/$defs/PromptListChangedNotification"
+ },
+ {
+ "$ref": "#/$defs/ToolListChangedNotification"
+ },
+ {
+ "$ref": "#/$defs/LoggingMessageNotification"
+ }
+ ]
+ },
+ "ServerResult": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/Result"
+ },
+ {
+ "$ref": "#/$defs/InputRequiredResult"
+ },
+ {
+ "$ref": "#/$defs/DiscoverResult"
+ },
+ {
+ "$ref": "#/$defs/ListResourcesResult"
+ },
+ {
+ "$ref": "#/$defs/ListResourceTemplatesResult"
+ },
+ {
+ "$ref": "#/$defs/ReadResourceResult"
+ },
+ {
+ "$ref": "#/$defs/SubscriptionsListenResult"
+ },
+ {
+ "$ref": "#/$defs/ListPromptsResult"
+ },
+ {
+ "$ref": "#/$defs/GetPromptResult"
+ },
+ {
+ "$ref": "#/$defs/ListToolsResult"
+ },
+ {
+ "$ref": "#/$defs/CallToolResult"
+ },
+ {
+ "$ref": "#/$defs/CompleteResult"
+ }
+ ]
+ },
+ "SingleSelectEnumSchema": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/UntitledSingleSelectEnumSchema"
+ },
+ {
+ "$ref": "#/$defs/TitledSingleSelectEnumSchema"
+ }
+ ]
+ },
+ "StringSchema": {
+ "properties": {
+ "default": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "format": {
+ "enum": [
+ "date",
+ "date-time",
+ "email",
+ "uri"
+ ],
+ "type": "string"
+ },
+ "maxLength": {
+ "type": "integer"
+ },
+ "minLength": {
+ "type": "integer"
+ },
+ "title": {
+ "type": "string"
+ },
+ "type": {
+ "const": "string",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ "SubscriptionFilter": {
+ "description": "The set of notification types a client may opt in to on a\n{@link SubscriptionsListenRequestsubscriptions/listen} request.\n\nEach notification type is **opt-in**; the server **MUST NOT** send\nnotification types the client has not explicitly requested here.",
+ "properties": {
+ "promptsListChanged": {
+ "description": "If true, receive {@link PromptListChangedNotificationnotifications/prompts/list_changed}.",
+ "type": "boolean"
+ },
+ "resourceSubscriptions": {
+ "description": "Subscribe to {@link ResourceUpdatedNotificationnotifications/resources/updated} for these resource URIs.\nReplaces the former `resources/subscribe` RPC.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "resourcesListChanged": {
+ "description": "If true, receive {@link ResourceListChangedNotificationnotifications/resources/list_changed}.",
+ "type": "boolean"
+ },
+ "toolsListChanged": {
+ "description": "If true, receive {@link ToolListChangedNotificationnotifications/tools/list_changed}.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "SubscriptionsAcknowledgedNotification": {
+ "description": "Sent by the server to acknowledge that a\n{@link SubscriptionsListenRequestsubscriptions/listen} subscription has been\nestablished and to report which notification types it agreed to honor.\n\nThis notification MUST be the first message the server sends carrying the\nsubscription's ID in `io.modelcontextprotocol/subscriptionId`. The server MUST\nNOT send any notification on the subscription before acknowledging it. On\nstdio, where every subscription shares one channel, this ordering is defined\nper subscription ID and not per channel: messages belonging to other\nsubscriptions MAY be interleaved before it.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/subscriptions/acknowledged",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/SubscriptionsAcknowledgedNotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "SubscriptionsAcknowledgedNotificationParams": {
+ "description": "Parameters for a {@link SubscriptionsAcknowledgedNotificationnotifications/subscriptions/acknowledged} notification.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/NotificationMetaObject"
+ },
+ "notifications": {
+ "$ref": "#/$defs/SubscriptionFilter",
+ "description": "The subset of requested notification types the server agreed to honor.\nOnly includes notification types the server actually supports; if the\nclient requested an unsupported type (e.g., `promptsListChanged` when\nthe server has no prompts), it is omitted from this set."
+ }
+ },
+ "required": [
+ "notifications"
+ ],
+ "type": "object"
+ },
+ "SubscriptionsListenRequest": {
+ "description": "Sent from the client to open a long-lived channel for receiving notifications\noutside the context of a specific request. Replaces the previous HTTP GET\nendpoint and ensures consistent behavior between HTTP and STDIO.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "subscriptions/listen",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/SubscriptionsListenRequestParams"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "method",
+ "params"
+ ],
+ "type": "object"
+ },
+ "SubscriptionsListenRequestParams": {
+ "description": "Parameters for a {@link SubscriptionsListenRequestsubscriptions/listen} request.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/RequestMetaObject"
+ },
+ "notifications": {
+ "$ref": "#/$defs/SubscriptionFilter",
+ "description": "The notifications the client opts in to on this stream. The server\n**MUST NOT** send notification types the client has not explicitly\nrequested."
+ }
+ },
+ "required": [
+ "_meta",
+ "notifications"
+ ],
+ "type": "object"
+ },
+ "SubscriptionsListenResult": {
+ "description": "The response to a {@link SubscriptionsListenRequestsubscriptions/listen}\nrequest, signalling that the subscription has ended gracefully (for example,\nduring server shutdown). Because the listen stream is long-lived, this result\nis sent only when the server tears the subscription down; an abrupt transport\nclose carries no response. The result body is otherwise empty.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/SubscriptionsListenResultMetaObject"
+ },
+ "resultType": {
+ "description": "Indicates the type of the result, which allows the client to determine\nhow to parse the result object.\n\nServers implementing this protocol version MUST include this field.\nFor backward compatibility, when a client receives a result from a\nserver implementing an earlier protocol version (which does not include\n`resultType`), the client MUST treat the absent field as `\"complete\"`.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "_meta",
+ "resultType"
+ ],
+ "type": "object"
+ },
+ "SubscriptionsListenResultMetaObject": {
+ "description": "Extends {@link ResultMetaObject} with the subscription-stream identifier carried by a\n{@link SubscriptionsListenResult}. All key naming rules from `MetaObject` apply.",
+ "properties": {
+ "io.modelcontextprotocol/serverInfo": {
+ "$ref": "#/$defs/Implementation",
+ "description": "Identifies the server software producing the response. Servers SHOULD\ninclude this field on every response unless specifically configured not\nto do so.\n\nThe {@link Implementation} schema requires `name` and `version`; other\nfields are optional.\n\nThe value is self-reported by the server and is not verified by the\nprotocol. It is intended for display, logging, and debugging. Clients\nSHOULD NOT use it to change their behavior, and SHOULD NOT rely on it for\nsecurity decisions."
+ },
+ "io.modelcontextprotocol/subscriptionId": {
+ "$ref": "#/$defs/RequestId",
+ "description": "Identifies the subscription stream this response closes, so the client can\ncorrelate it with the originating subscription — mirroring the same key on\nthe stream's notifications. The value is the JSON-RPC ID of the\n`subscriptions/listen` request that opened the stream (and equals this\nresponse's `id`)."
+ }
+ },
+ "required": [
+ "io.modelcontextprotocol/subscriptionId"
+ ],
+ "type": "object"
+ },
+ "SubscriptionsListenResultResponse": {
+ "description": "A successful response from the server for a {@link SubscriptionsListenRequestsubscriptions/listen}\nrequest, sent when the server tears the subscription down gracefully.",
+ "properties": {
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "result": {
+ "$ref": "#/$defs/SubscriptionsListenResult"
+ }
+ },
+ "required": [
+ "id",
+ "jsonrpc",
+ "result"
+ ],
+ "type": "object"
+ },
+ "TextContent": {
+ "description": "Text provided to or from an LLM.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "annotations": {
+ "$ref": "#/$defs/Annotations",
+ "description": "Optional annotations for the client."
+ },
+ "text": {
+ "description": "The text content of the message.",
+ "type": "string"
+ },
+ "type": {
+ "const": "text",
+ "type": "string"
+ }
+ },
+ "required": [
+ "text",
+ "type"
+ ],
+ "type": "object"
+ },
+ "TextResourceContents": {
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "mimeType": {
+ "description": "The MIME type of this resource, if known.",
+ "type": "string"
+ },
+ "text": {
+ "description": "The text of the item. This must only be set if the item can actually be represented as text (not binary data).",
+ "type": "string"
+ },
+ "uri": {
+ "description": "The URI of this resource.",
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "text",
+ "uri"
+ ],
+ "type": "object"
+ },
+ "TitledMultiSelectEnumSchema": {
+ "description": "Schema for multiple-selection enumeration with display titles for each option.",
+ "properties": {
+ "default": {
+ "description": "Optional default value.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "description": {
+ "description": "Optional description for the enum field.",
+ "type": "string"
+ },
+ "items": {
+ "description": "Schema for array items with enum options and display labels.",
+ "properties": {
+ "anyOf": {
+ "description": "Array of enum options with values and display labels.",
+ "items": {
+ "properties": {
+ "const": {
+ "description": "The constant enum value.",
+ "type": "string"
+ },
+ "title": {
+ "description": "Display title for this option.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "const",
+ "title"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "anyOf"
+ ],
+ "type": "object"
+ },
+ "maxItems": {
+ "description": "Maximum number of items to select.",
+ "type": "integer"
+ },
+ "minItems": {
+ "description": "Minimum number of items to select.",
+ "type": "integer"
+ },
+ "title": {
+ "description": "Optional title for the enum field.",
+ "type": "string"
+ },
+ "type": {
+ "const": "array",
+ "type": "string"
+ }
+ },
+ "required": [
+ "items",
+ "type"
+ ],
+ "type": "object"
+ },
+ "TitledSingleSelectEnumSchema": {
+ "description": "Schema for single-selection enumeration with display titles for each option.",
+ "properties": {
+ "default": {
+ "description": "Optional default value.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Optional description for the enum field.",
+ "type": "string"
+ },
+ "oneOf": {
+ "description": "Array of enum options with values and display labels.",
+ "items": {
+ "properties": {
+ "const": {
+ "description": "The enum value.",
+ "type": "string"
+ },
+ "title": {
+ "description": "Display label for this option.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "const",
+ "title"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "title": {
+ "description": "Optional title for the enum field.",
+ "type": "string"
+ },
+ "type": {
+ "const": "string",
+ "type": "string"
+ }
+ },
+ "required": [
+ "oneOf",
+ "type"
+ ],
+ "type": "object"
+ },
+ "Tool": {
+ "description": "Definition for a tool the client can call.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject"
+ },
+ "annotations": {
+ "$ref": "#/$defs/ToolAnnotations",
+ "description": "Optional additional tool information.\n\nDisplay name precedence order is: `title`, `annotations.title`, then `name`."
+ },
+ "description": {
+ "description": "A human-readable description of the tool.\n\nThis can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a \"hint\" to the model.",
+ "type": "string"
+ },
+ "icons": {
+ "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)",
+ "items": {
+ "$ref": "#/$defs/Icon"
+ },
+ "type": "array"
+ },
+ "inputSchema": {
+ "additionalProperties": {},
+ "description": "A JSON Schema object defining the expected parameters for the tool.\n\nTool arguments are always JSON objects, so `type: \"object\"` is required at the root.\nBeyond that, any JSON Schema 2020-12 keyword may appear alongside `type` — including\ncomposition keywords (`oneOf`, `anyOf`, `allOf`, `not`), conditional keywords\n(`if`/`then`/`else`), reference keywords (`$ref`, `$defs`, `$anchor`), and any other\nstandard validation or annotation keywords.\n\nProperty schemas may carry an `x-mcp-header` annotation to mirror the\nargument value into an HTTP header on the Streamable HTTP transport. See\nthe Streamable HTTP transport specification for the validity and\nextraction rules.\n\nDefaults to JSON Schema 2020-12 when no explicit `$schema` is provided.",
+ "properties": {
+ "$schema": {
+ "type": "string"
+ },
+ "type": {
+ "const": "object",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ "name": {
+ "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).",
+ "type": "string"
+ },
+ "outputSchema": {
+ "additionalProperties": {},
+ "description": "An optional JSON Schema object defining the structure of the tool's output returned in\nthe structuredContent field of a {@link CallToolResult}. This can be any valid JSON Schema 2020-12.\n\nDefaults to JSON Schema 2020-12 when no explicit `$schema` is provided.",
+ "properties": {
+ "$schema": {
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "title": {
+ "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for {@link Tool},\nwhere `annotations.title` should be given precedence over using `name`,\nif present).",
+ "type": "string"
+ }
+ },
+ "required": [
+ "inputSchema",
+ "name"
+ ],
+ "type": "object"
+ },
+ "ToolAnnotations": {
+ "description": "Additional properties describing a {@link Tool} to clients.\n\nNOTE: all properties in `ToolAnnotations` are **hints**.\nThey are not guaranteed to provide a faithful description of\ntool behavior (including descriptive properties like `title`).\n\nClients should never make tool use decisions based on `ToolAnnotations`\nreceived from untrusted servers.",
+ "properties": {
+ "destructiveHint": {
+ "description": "If true, the tool may perform destructive updates to its environment.\nIf false, the tool performs only additive updates.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: true",
+ "type": "boolean"
+ },
+ "idempotentHint": {
+ "description": "If true, calling the tool repeatedly with the same arguments\nwill have no additional effect on its environment.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: false",
+ "type": "boolean"
+ },
+ "openWorldHint": {
+ "description": "If true, this tool may interact with an \"open world\" of external\nentities. If false, the tool's domain of interaction is closed.\nFor example, the world of a web search tool is open, whereas that\nof a memory tool is not.\n\nDefault: true",
+ "type": "boolean"
+ },
+ "readOnlyHint": {
+ "description": "If true, the tool does not modify its environment.\n\nDefault: false",
+ "type": "boolean"
+ },
+ "title": {
+ "description": "A human-readable title for the tool.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "ToolChoice": {
+ "description": "Controls tool selection behavior for sampling requests.",
+ "properties": {
+ "mode": {
+ "description": "Controls the tool use ability of the model:\n- `\"auto\"`: Model decides whether to use tools (default)\n- `\"required\"`: Model MUST use at least one tool before completing\n- `\"none\"`: Model MUST NOT use any tools",
+ "enum": [
+ "auto",
+ "none",
+ "required"
+ ],
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "ToolListChangedNotification": {
+ "description": "An optional notification from the server to the client, informing it that the list of tools it offers has changed. This is only delivered on a {@link SubscriptionsListenRequestsubscriptions/listen} stream when the client requested it via the `toolsListChanged` filter field.",
+ "properties": {
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ },
+ "method": {
+ "const": "notifications/tools/list_changed",
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/$defs/NotificationParams"
+ }
+ },
+ "required": [
+ "jsonrpc",
+ "method"
+ ],
+ "type": "object"
+ },
+ "ToolResultContent": {
+ "description": "The result of a tool use, provided by the user back to the assistant.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject",
+ "description": "Optional metadata about the tool result. Clients SHOULD preserve this field when\nincluding tool results in subsequent sampling requests to enable caching optimizations."
+ },
+ "content": {
+ "description": "The unstructured result content of the tool use.\n\nThis has the same format as {@link CallToolResult.content} and can include text, images,\naudio, resource links, and embedded resources.",
+ "items": {
+ "$ref": "#/$defs/ContentBlock"
+ },
+ "type": "array"
+ },
+ "isError": {
+ "description": "Whether the tool use resulted in an error.\n\nIf true, the content typically describes the error that occurred.\nDefault: false",
+ "type": "boolean"
+ },
+ "structuredContent": {
+ "description": "An optional structured result value.\n\nThis can be any JSON value (object, array, string, number, boolean, or null).\nIf the tool defined an {@link Tool.outputSchema}, this SHOULD conform to that schema."
+ },
+ "toolUseId": {
+ "description": "The ID of the tool use this result corresponds to.\n\nThis MUST match the ID from a previous {@link ToolUseContent}.",
+ "type": "string"
+ },
+ "type": {
+ "const": "tool_result",
+ "type": "string"
+ }
+ },
+ "required": [
+ "content",
+ "toolUseId",
+ "type"
+ ],
+ "type": "object"
+ },
+ "ToolUseContent": {
+ "description": "A request from the assistant to call a tool.",
+ "properties": {
+ "_meta": {
+ "$ref": "#/$defs/MetaObject",
+ "description": "Optional metadata about the tool use. Clients SHOULD preserve this field when\nincluding tool uses in subsequent sampling requests to enable caching optimizations."
+ },
+ "id": {
+ "description": "A unique identifier for this tool use.\n\nThis ID is used to match tool results to their corresponding tool uses.",
+ "type": "string"
+ },
+ "input": {
+ "additionalProperties": {},
+ "description": "The arguments to pass to the tool, conforming to the tool's input schema.",
+ "type": "object"
+ },
+ "name": {
+ "description": "The name of the tool to call.",
+ "type": "string"
+ },
+ "type": {
+ "const": "tool_use",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "input",
+ "name",
+ "type"
+ ],
+ "type": "object"
+ },
+ "UnsupportedProtocolVersionError": {
+ "description": "Returned when the request's protocol version is unknown to the server or\nunsupported (e.g., a known experimental or draft version the server has\nchosen not to implement). For HTTP, the response status code MUST be\n`400 Bad Request`.",
+ "properties": {
+ "error": {
+ "allOf": [
+ {
+ "$ref": "#/$defs/Error"
+ },
+ {
+ "properties": {
+ "code": {
+ "const": -32022,
+ "type": "integer"
+ },
+ "data": {
+ "properties": {
+ "requested": {
+ "description": "The protocol version that was requested by the client.",
+ "type": "string"
+ },
+ "supported": {
+ "description": "Protocol versions the server supports. The client should choose a\nmutually supported version from this list and retry.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "requested",
+ "supported"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "code",
+ "data"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "id": {
+ "$ref": "#/$defs/RequestId"
+ },
+ "jsonrpc": {
+ "const": "2.0",
+ "type": "string"
+ }
+ },
+ "required": [
+ "error",
+ "jsonrpc"
+ ],
+ "type": "object"
+ },
+ "UntitledMultiSelectEnumSchema": {
+ "description": "Schema for multiple-selection enumeration without display titles for options.",
+ "properties": {
+ "default": {
+ "description": "Optional default value.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "description": {
+ "description": "Optional description for the enum field.",
+ "type": "string"
+ },
+ "items": {
+ "description": "Schema for the array items.",
+ "properties": {
+ "enum": {
+ "description": "Array of enum values to choose from.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": {
+ "const": "string",
+ "type": "string"
+ }
+ },
+ "required": [
+ "enum",
+ "type"
+ ],
+ "type": "object"
+ },
+ "maxItems": {
+ "description": "Maximum number of items to select.",
+ "type": "integer"
+ },
+ "minItems": {
+ "description": "Minimum number of items to select.",
+ "type": "integer"
+ },
+ "title": {
+ "description": "Optional title for the enum field.",
+ "type": "string"
+ },
+ "type": {
+ "const": "array",
+ "type": "string"
+ }
+ },
+ "required": [
+ "items",
+ "type"
+ ],
+ "type": "object"
+ },
+ "UntitledSingleSelectEnumSchema": {
+ "description": "Schema for single-selection enumeration without display titles for options.",
+ "properties": {
+ "default": {
+ "description": "Optional default value.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Optional description for the enum field.",
+ "type": "string"
+ },
+ "enum": {
+ "description": "Array of enum values to choose from.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "title": {
+ "description": "Optional title for the enum field.",
+ "type": "string"
+ },
+ "type": {
+ "const": "string",
+ "type": "string"
+ }
+ },
+ "required": [
+ "enum",
+ "type"
+ ],
+ "type": "object"
+ }
+ }
+}
diff --git a/.github/scripts/cua-driver-mcp-compat/modern-client/schema-LICENSE b/.github/scripts/cua-driver-mcp-compat/modern-client/schema-LICENSE
new file mode 100644
index 0000000000..4a93985763
--- /dev/null
+++ b/.github/scripts/cua-driver-mcp-compat/modern-client/schema-LICENSE
@@ -0,0 +1,216 @@
+The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0.
+
+Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.
+
+No rights beyond those granted by the applicable original license are conveyed for such contributions.
+
+---
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to the Licensor for inclusion in the Work by the copyright
+ owner or by an individual or Legal Entity authorized to submit on behalf
+ of the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+---
+
+MIT License
+
+Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+---
+
+Creative Commons Attribution 4.0 International (CC-BY-4.0)
+
+Documentation in this project (excluding specifications) is licensed under
+CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for
+the full license text.
diff --git a/.github/scripts/cua-driver-mcp-compat/verify-modern.mjs b/.github/scripts/cua-driver-mcp-compat/verify-modern.mjs
new file mode 100644
index 0000000000..5a7bd2f2c0
--- /dev/null
+++ b/.github/scripts/cua-driver-mcp-compat/verify-modern.mjs
@@ -0,0 +1,289 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { mkdtemp, mkdir } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+// Keep the real v2 SDK isolated from the existing pinned legacy-client suite.
+const HERE = dirname(fileURLToPath(import.meta.url));
+const require = createRequire(join(HERE, 'modern-client', 'package.json'));
+const { Client } = require('@modelcontextprotocol/client');
+const { StdioClientTransport } = require('@modelcontextprotocol/client/stdio');
+const { ResultSchema } = require('@modelcontextprotocol/core');
+const Ajv2020 = require('ajv/dist/2020.js');
+const { parse: parseYaml } = require('yaml');
+const VERSION = '2026-07-28';
+const VERSION_KEY = 'io.modelcontextprotocol/protocolVersion';
+const CAPABILITIES_KEY = 'io.modelcontextprotocol/clientCapabilities';
+const SCHEMA = JSON.parse(readFileSync(join(HERE, 'modern-client/schema-2026-07-28.json')));
+const ajv = new Ajv2020({ strict: false, allErrors: true, validateFormats: false });
+ajv.addSchema(SCHEMA, 'mcp');
+const DEFINITIONS = {
+ 'server/discover': 'DiscoverResult',
+ 'tools/list': 'ListToolsResult',
+ 'tools/call': 'CallToolResult',
+ 'resources/list': 'ListResourcesResult',
+ 'resources/read': 'ReadResourceResult',
+ 'skills/list': 'Result',
+ 'skills/get': 'Result',
+};
+const validators = Object.fromEntries(
+ Object.entries(DEFINITIONS).map(([method, name]) => [
+ method,
+ ajv.compile({ $ref: `mcp#/$defs/${name}` }),
+ ])
+);
+const expectedFiles = [
+ 'BROWSER.md',
+ 'EMBEDDING.md',
+ 'LINUX.md',
+ 'MACOS.md',
+ 'README.md',
+ 'RECORDING.md',
+ 'SKILL.md',
+ 'WINDOWS.md',
+];
+const sourcePack = resolve(HERE, '../../../libs/cua-driver/rust/Skills/cua-driver');
+const driver = process.env.CUA_DRIVER_BINARY && resolve(process.env.CUA_DRIVER_BINARY);
+assert(driver, 'CUA_DRIVER_BINARY must name the source-built candidate');
+const args = process.env.CUA_DRIVER_MCP_ARGS
+ ? JSON.parse(process.env.CUA_DRIVER_MCP_ARGS)
+ : ['mcp', '--direct'];
+assert(Array.isArray(args) && args.every((arg) => typeof arg === 'string'));
+// An externally managed proxy must name its isolated socket explicitly.
+assert(
+ args.includes('--direct') || args.includes('--socket'),
+ 'use --direct or an explicit isolated --socket'
+);
+const state = await mkdtemp(join(tmpdir(), 'cua-modern-mcp-'));
+const env = {};
+for (const name of [
+ 'PATH',
+ 'SystemRoot',
+ 'WINDIR',
+ 'COMSPEC',
+ 'PATHEXT',
+ 'TMPDIR',
+ 'TEMP',
+ 'TMP',
+]) {
+ if (process.env[name]) env[name] = process.env[name];
+}
+Object.assign(env, {
+ HOME: state,
+ USERPROFILE: state,
+ APPDATA: join(state, 'config'),
+ LOCALAPPDATA: join(state, 'local'),
+ XDG_CONFIG_HOME: join(state, 'config'),
+ XDG_DATA_HOME: join(state, 'data'),
+ XDG_STATE_HOME: join(state, 'state'),
+ XDG_CACHE_HOME: join(state, 'cache'),
+ CUA_DRIVER_HOME: join(state, 'driver'),
+ CUA_DRIVER_RS_HOME: join(state, 'driver'),
+ CUA_DRIVER_PERMISSION_MODE: 'standard',
+ CUA_DRIVER_RS_TELEMETRY_ENABLED: 'false',
+ NO_COLOR: '1',
+});
+for (const subdir of ['config', 'local', 'data', 'state', 'cache', 'driver']) {
+ await mkdir(join(state, subdir));
+}
+
+const requests = new Map();
+const methods = [];
+const wireErrors = [];
+let omitCapabilities = false;
+let responseCount = 0;
+let sentRequestCount = 0;
+let errorResponseCount = 0;
+const observedMessages = new WeakSet();
+// Subclassing also keeps negotiation on this observed transport, without a
+// separate unobserved disposable probe process in SDK auto-negotiation.
+class ObservedTransport extends StdioClientTransport {
+ constructor(options) {
+ super(options);
+ let handler;
+ // Negotiation replaces onmessage after discovery. Wrap every assignment;
+ // an SDK handler may chain its predecessor, so validate each message once.
+ Object.defineProperty(this, 'onmessage', {
+ configurable: true,
+ get: () => handler,
+ set: (deliver) => {
+ handler =
+ deliver &&
+ ((message, ...rest) => {
+ this.observe(message);
+ deliver(message, ...rest);
+ });
+ },
+ });
+ }
+ observe(message) {
+ if (observedMessages.has(message)) return;
+ observedMessages.add(message);
+ try {
+ if (message.error) errorResponseCount += 1;
+ if (message.result) {
+ const method = requests.get(message.id);
+ const validate = validators[method];
+ assert(validate, `unexpected result for ${method}`);
+ assert(validate(message.result), `${method}: ${ajv.errorsText(validate.errors)}`);
+ assert.equal(message.result.resultType, 'complete');
+ assert.equal(
+ message.result._meta?.['io.modelcontextprotocol/serverInfo']?.name,
+ 'cua-driver'
+ );
+ if (method === 'server/discover' || method.endsWith('/list') || method.endsWith('/read')) {
+ assert.equal(message.result.ttlMs, 0);
+ assert.equal(message.result.cacheScope, 'private');
+ }
+ responseCount += 1;
+ }
+ } catch (error) {
+ wireErrors.push(error);
+ }
+ }
+ async send(message, options) {
+ if (message.method) {
+ methods.push(message.method);
+ assert.notEqual(
+ message.method,
+ 'initialize',
+ 'modern probe must never fall back to initialize'
+ );
+ assert.notEqual(message.method, 'notifications/initialized');
+ if (message.id !== undefined) {
+ sentRequestCount += 1;
+ requests.set(message.id, message.method);
+ assert.equal(message.params?._meta?.[VERSION_KEY], VERSION);
+ assert.equal(typeof message.params?._meta?.[CAPABILITIES_KEY], 'object');
+ if (omitCapabilities) {
+ message = structuredClone(message);
+ delete message.params._meta[CAPABILITIES_KEY];
+ }
+ }
+ }
+ return super.send(message, options);
+ }
+}
+
+const transport = new ObservedTransport({ command: driver, args, env, cwd: state, stderr: 'pipe' });
+let stderr = '';
+transport.stderr.on('data', (chunk) => {
+ stderr = `${stderr}${chunk}`.slice(-8192);
+});
+const client = new Client(
+ { name: 'cua-modern-mcp-compat', version: '1.0.0' },
+ {
+ capabilities: { extensions: { 'io.modelcontextprotocol/skills': {} } },
+ versionNegotiation: { mode: { pin: VERSION }, probe: { timeoutMs: 15000, maxRetries: 0 } },
+ }
+);
+const timeout = setTimeout(() => {
+ console.error('modern MCP probe exceeded 90 seconds');
+ void client.close().finally(() => process.exit(1));
+}, 90000);
+try {
+ await client.connect(transport);
+ assert.equal(client.getProtocolEra(), 'modern');
+ assert.equal(client.getNegotiatedProtocolVersion(), VERSION);
+ assert.equal(methods[0], 'server/discover');
+ const discovery = client.getDiscoverResult();
+ assert(discovery.supportedVersions.includes(VERSION));
+ assert.deepEqual(discovery.capabilities.extensions['io.modelcontextprotocol/skills'], {});
+ const { tools } = await client.listTools();
+ assert(tools.some((tool) => tool.name === 'get_config'));
+ const config = await client.callTool({ name: 'get_config', arguments: {} });
+ assert.notEqual(config.isError, true, 'read-only get_config failed');
+ assert(config.content.length > 0);
+
+ const catalog = await client.request({ method: 'skills/list', params: {} }, ResultSchema);
+ assert.equal(catalog.skills.length, 1);
+ assert.equal(catalog.nextCursor, undefined);
+ const skill = catalog.skills[0];
+ assert.equal(skill.uri, 'skill://cua-driver/SKILL.md');
+ const fetched = await client.request(
+ { method: 'skills/get', params: { uri: skill.uri } },
+ ResultSchema
+ );
+ assert.deepEqual(fetched.skill, skill);
+ const resources = await client.listResources();
+ assert.deepEqual(
+ resources.resources.map((item) => item.uri).sort(),
+ expectedFiles.map((name) => `skill://cua-driver/${name}`)
+ );
+ assert.deepEqual(
+ skill.resources.map((item) => item.uri).sort(),
+ expectedFiles.map((name) => `skill://cua-driver/${name}`)
+ );
+ let bytes = 0;
+ for (const name of expectedFiles) {
+ const uri = `skill://cua-driver/${name}`;
+ const manifest = skill.resources.find((item) => item.uri === uri);
+ const result = await client.readResource({ uri });
+ assert.equal(result.contents.length, 1);
+ const content = result.contents[0];
+ assert.equal(content.uri, uri);
+ assert.equal(content.mimeType, 'text/markdown');
+ const data = Buffer.from(content.text, 'utf8');
+ assert.deepEqual(
+ data,
+ readFileSync(join(sourcePack, name)),
+ `${name}: embedded source mismatch`
+ );
+ assert.equal(manifest.size, data.length);
+ assert.equal(manifest.digest, `sha256:${createHash('sha256').update(data).digest('hex')}`);
+ bytes += data.length;
+ if (name === 'SKILL.md') {
+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(content.text);
+ assert(frontmatter, 'missing skill frontmatter');
+ assert.deepEqual(skill.frontmatter, parseYaml(frontmatter[1]));
+ }
+ }
+ await assert.rejects(
+ client.readResource({ uri: 'skill://cua-driver/UNKNOWN.md' }),
+ (error) => error.code === -32602
+ );
+ omitCapabilities = true;
+ await assert.rejects(
+ client.request({ method: 'skills/list', params: {} }, ResultSchema),
+ (error) => error.code === -32602
+ );
+ omitCapabilities = false;
+ // A valid request after rejection proves capabilities are per-request.
+ await client.request({ method: 'skills/list', params: {} }, ResultSchema);
+ assert.deepEqual(wireErrors, [], wireErrors.map((error) => error.message).join('\n'));
+ assert(responseCount >= 15, 'every successful endpoint response must be schema-validated');
+ assert.equal(errorResponseCount, 2, 'both expected protocol errors must be observed');
+ assert.equal(
+ responseCount + errorResponseCount,
+ sentRequestCount,
+ 'wire validation missed a response'
+ );
+ console.log(
+ JSON.stringify(
+ {
+ sdk: '@modelcontextprotocol/[email protected]',
+ protocol: VERSION,
+ runtimeArgs: args,
+ tools: tools.length,
+ skills: 1,
+ resources: expectedFiles.length,
+ bytes,
+ schemaValidatedResponses: responseCount,
+ initialized: false,
+ nativeSkillActivation: 'not tested',
+ },
+ null,
+ 2
+ )
+ );
+} catch (error) {
+ if (stderr) console.error(stderr);
+ throw error;
+} finally {
+ clearTimeout(timeout);
+ await client.close();
+}
diff --git a/.github/scripts/cua-driver-mcp-compat/verify.mjs b/.github/scripts/cua-driver-mcp-compat/verify.mjs
index 205d50896f..8e804fb6e7 100644
--- a/.github/scripts/cua-driver-mcp-compat/verify.mjs
+++ b/.github/scripts/cua-driver-mcp-compat/verify.mjs
@@ -37,8 +37,14 @@ const PROBE_ENV = {
DISABLE_AUTOUPDATER: "1",
NO_COLOR: "1",
};
-const BIN_DIR = join(HERE, "node_modules", ".bin");
-const CODEX = join(BIN_DIR, process.platform === "win32" ? "codex.cmd" : "codex");
+const CODEX_SCRIPT = join(
+ HERE,
+ "node_modules",
+ "@openai",
+ "codex",
+ "bin",
+ "codex.js",
+);
function claudeBinary() {
const platform = process.platform === "darwin" ? "darwin" : process.platform;
@@ -251,14 +257,15 @@ async function claudeCodeProbe() {
async function codexProbe() {
const codexHome = await mkdtemp(join(tmpdir(), "cua-codex-mcp-"));
const env = { ...PROBE_ENV, CODEX_HOME: codexHome };
- const version = run(CODEX, ["--version"], { env });
+ const version = run(process.execPath, [CODEX_SCRIPT, "--version"], { env });
assert.match(version.stdout, /0\.146\.1/);
const commandConfig = `mcp_servers.cua_driver.command=${JSON.stringify(DRIVER)}`;
const argsConfig = `mcp_servers.cua_driver.args=${JSON.stringify(DRIVER_ARGS)}`;
const child = spawn(
- CODEX,
+ process.execPath,
[
+ CODEX_SCRIPT,
"app-server",
"--listen",
"stdio://",
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.py
index 5e05886b3d..89678e9dce 100644
--- a/.github/scripts/tests/test_cua_driver_release_wiring.py
+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py
@@ -822,6 +822,9 @@ fi
ci_workflow = self.read(
".github/workflows/ci-cua-driver-contract-clients.yml"
)
+ compatibility_probe = self.read(
+ ".github/scripts/cua-driver-mcp-compat/verify.mjs"
+ )
package = json.loads(
self.read(
".github/scripts/cua-driver-mcp-compat/package.json"
@@ -841,6 +844,15 @@ fi
self.assertIn("npm run verify", workflow)
self.assertIn("MCP discovery in pinned clients", ci_workflow)
self.assertIn("Verify discovery without model or account calls", ci_workflow)
+ self.assertNotIn("codex.cmd", compatibility_probe)
+ self.assertIn(
+ 'run(process.execPath, [CODEX_SCRIPT, "--version"]',
+ compatibility_probe,
+ )
+ self.assertIn(
+ "const child = spawn(\n process.execPath,\n [\n CODEX_SCRIPT,",
+ compatibility_probe,
+ )
self.assertEqual(
package["dependencies"],
{
@@ -868,7 +880,8 @@ fi
"mouse_button_up",
"mouse_drag",
"parallel_mouse_drag",
- ]
+ ],
+ "win32": ["debug_window_info"],
},
)
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.yml
index 3fea81abe1..84e1e1b573 100644
--- a/.github/workflows/ci-cua-driver-contract-clients.yml
+++ b/.github/workflows/ci-cua-driver-contract-clients.yml
@@ -67,9 +67,13 @@ concurrency:
jobs:
mcp-client-discovery:
- name: MCP discovery in pinned clients
- runs-on: ubuntu-latest
+ name: MCP discovery in pinned clients (${{ matrix.os }})
+ runs-on: ${{ matrix.os }}
timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: dtolnay/rust-toolchain@stable
@@ -80,8 +84,11 @@ jobs:
with:
node-version: "22"
cache: npm
- cache-dependency-path: .github/scripts/cua-driver-mcp-compat/package-lock.json
+ cache-dependency-path: |
+ .github/scripts/cua-driver-mcp-compat/package-lock.json
+ .github/scripts/cua-driver-mcp-compat/modern-client/package-lock.json
- name: Install Linux build dependencies
+ if: runner.os == 'Linux'
run: |
if [[ -f /etc/apt/apt-mirrors.txt ]]; then
sudo sed -i 's#http://azure.archive.ubuntu.com/ubuntu#https://archive.ubuntu.com/ubuntu#g' /etc/apt/apt-mirrors.txt
@@ -98,12 +105,25 @@ jobs:
run: npm ci --ignore-scripts
- name: Verify discovery without model or account calls
working-directory: .github/scripts/cua-driver-mcp-compat
+ shell: bash
+ env:
+ CUA_DRIVER_BINARY: ${{ github.workspace }}/libs/cua-driver/rust/target/release/cua-driver${{ runner.os == 'Windows' && '.exe' || '' }}
run: |
- VERSION=$(python3 -c 'import tomllib; print(tomllib.load(open("../../../libs/cua-driver/rust/Cargo.toml", "rb"))["workspace"]["package"]["version"])')
- CUA_DRIVER_BINARY="$GITHUB_WORKSPACE/libs/cua-driver/rust/target/release/cua-driver" \
+ VERSION=$(cargo metadata --no-deps --format-version 1 \
+ --manifest-path ../../../libs/cua-driver/rust/Cargo.toml \
+ | node -e 'let s=""; process.stdin.on("data", c => s += c); process.stdin.on("end", () => console.log(JSON.parse(s).packages.find(p => p.name === "cua-driver").version))')
CUA_DRIVER_EXPECTED_VERSION="$VERSION" \
npm run verify
+ - name: Install the pinned modern MCP client
+ working-directory: .github/scripts/cua-driver-mcp-compat/modern-client
+ run: npm ci --ignore-scripts
+
+ - name: Verify modern MCP and embedded skill resources
+ env:
+ CUA_DRIVER_BINARY: ${{ github.workspace }}/libs/cua-driver/rust/target/release/cua-driver${{ runner.os == 'Windows' && '.exe' || '' }}
+ run: node .github/scripts/cua-driver-mcp-compat/verify-modern.mjs
+
runtime-parity:
name: Portable contract parity (${{ matrix.os }})
runs-on: ${{ matrix.os }}
diff --git a/.github/workflows/ci-rust-windows.yml b/.github/workflows/ci-rust-windows.yml
index 4a3145c7b1..ffe14c97be 100644
--- a/.github/workflows/ci-rust-windows.yml
+++ b/.github/workflows/ci-rust-windows.yml
@@ -33,6 +33,11 @@ on:
- "libs/cua-driver/tests/fixtures/**"
- ".github/workflows/ci-rust-windows.yml"
workflow_dispatch:
+ inputs:
+ proxy_idle_seconds:
+ description: "Idle duration for MCP recovery diagnostic (1-3600 seconds)"
+ type: number
+ default: 1
permissions:
contents: read
@@ -45,7 +50,7 @@ jobs:
unit:
name: Rust Windows unit and compile
runs-on: windows-latest
- timeout-minutes: 30
+ timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && inputs.proxy_idle_seconds > 1 && 90 || 30 }}
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: dtolnay/rust-toolchain@stable
@@ -80,6 +85,16 @@ jobs:
- name: Run bounded UIA worker regressions
working-directory: libs/cua-driver/rust
run: "cargo test -p platform-windows windows_enum::tests:: --lib --locked"
+ - name: Run MCP proxy lifecycle regressions
+ working-directory: libs/cua-driver/rust
+ run: "cargo test -p cua-driver --bin cua-driver proxy::tests:: --locked"
+ - name: Run real MCP proxy recovery regression
+ working-directory: libs/cua-driver/rust
+ env:
+ CUA_PROXY_RECOVERY_IDLE_SECONDS: ${{ inputs.proxy_idle_seconds || 1 }}
+ run: cargo test -p cua-driver --test protocol_proxy_recovery_test --locked -- --nocapture
+ - name: Test sentinel setup barrier
+ run: node --test libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.test.js
- name: Run named-pipe readiness regression
working-directory: libs/cua-driver/rust
run: cargo test -p cua-driver-testkit stalled_pipe_attempt_is_bounded_and_does_not_block_the_next_probe --lib --locked
diff --git a/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx b/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
index 0976606c6f..7ab0539e32 100644
--- a/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
+++ b/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
@@ -294,6 +294,30 @@ libs/cua-driver/scripts/sync-vm-worktree.sh push \
"lume@${VM_IP}" '~/cua'
```
+### Seed TCC in a disposable worker without inherited grants
+
+Skip this section when the worker was cloned from a private seed whose signing
+identity and app-owned grants passed the preflight. For a disposable worker
+created from the public SIP-disabled image or another ungranted base, first
+install the exact candidate as the certificate-signed local app. Then run the
+checked-in helper from the host:
+
+```bash
+libs/cua-driver/tests/runners/macos-lume/seed-tcc.sh "$WORKER"
+```
+
+The helper refuses to write unless the guest identifies as `VirtualMac*`, SIP
+is disabled, the app is `com.trycua.driver.local`, and its code requirement is
+certificate-backed. It seeds only Accessibility and Screen Recording, restarts
+`tccd`, and verifies both rows. Do not copy its SQL or edit `TCC.db` manually.
+
+Restart `CuaDriverLocal.app` in the logged-in guest after seeding. Before the
+matrix, require `cua-driver-local permissions status --json` to report both
+grants and prove a fresh screenshot plus a reversible input action through the
+guest Driver. Database rows or a successful helper exit alone do not certify
+the desktop. The complete command options and signing prerequisites are in the
+repository's `libs/cua-driver/tests/runners/macos-lume/README.md`.
+
### Run the complete matrix in foreground Terminal
Open Terminal in the VM display and run:
diff --git a/libs/cua-driver/README.md b/libs/cua-driver/README.md
index 710afcdfa7..875d9758b0 100644
--- a/libs/cua-driver/README.md
+++ b/libs/cua-driver/README.md
@@ -2,6 +2,9 @@
Background computer-use driver for any agents. Speaks MCP over stdio; drives native macOS apps without stealing focus.
+See [MCP protocol and skills](docs/mcp-protocol-and-skills.md) for the modern
+stdio profile, legacy compatibility, bundled skill resources, and HTTP limits.
+
**[Documentation](https://cua.ai/docs/cua-driver)** - Installation, guides, and API reference.
## Integration surfaces
diff --git a/libs/cua-driver/contract/README.md b/libs/cua-driver/contract/README.md
index 2281ec9187..d81f91bd89 100644
--- a/libs/cua-driver/contract/README.md
+++ b/libs/cua-driver/contract/README.md
@@ -112,7 +112,7 @@ Compatibility is tracked separately at each boundary:
| `contract_version` | `0.8.0` | Generated manifest and typed SDK shape |
| `tools_list_schema_version` | `1` | cua-driver `tools/list` extension shape |
| `capability_version` | `1` | Additive capability-token vocabulary |
-| `mcp_protocol_version` | `2025-06-18` | MCP initialization protocol served to agent runtimes |
+| `mcp_protocol_version` | `2025-06-18` | Legacy `initialize.params.protocolVersion` and loopback HTTP compatibility version; modern stdio negotiation is endpoint-owned |
This implementation does not use WASM. UniFFI distributes the shared Rust
implementation to Python and Node. Permission identity follows the selected
diff --git a/libs/cua-driver/docs/mcp-protocol-and-skills.md b/libs/cua-driver/docs/mcp-protocol-and-skills.md
new file mode 100644
index 0000000000..904ccece93
--- /dev/null
+++ b/libs/cua-driver/docs/mcp-protocol-and-skills.md
@@ -0,0 +1,119 @@
+# MCP protocol and skills
+
+The Rust `cua-driver mcp` endpoint supports modern MCP `2026-07-28` over stdio
+and retains the legacy `initialize` flow with version `2025-06-18`. Direct and
+daemon-backed stdio use the same protocol and skill catalog.
+
+This document describes the implementation in PR #3609. It is not a claim
+that an existing installed release contains these changes.
+
+## Connect
+
+Keep the existing MCP server command:
+
+```json
+{
+ "command": "cua-driver",
+ "args": ["mcp"]
+}
+```
+
+A modern client sends protocol metadata on every request. Discovery does not
+require initialization:
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "server/discover",
+ "params": {
+ "_meta": {
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
+ "io.modelcontextprotocol/clientCapabilities": {}
+ }
+ }
+}
+```
+
+The response reports the supported modern version, tools, resources, and the
+`io.modelcontextprotocol/skills` extension. Every modern result includes
+`resultType: "complete"`. Discovery and list/read responses include conservative
+cache hints. Capabilities are per request; successful discovery does not excuse
+missing metadata on subsequent requests.
+
+Legacy clients negotiate `2025-06-18` through
+`initialize.params.protocolVersion`, then make metadata-free requests. The
+namespaced `io.modelcontextprotocol/protocolVersion` key is modern-only; using
+it with `2025-06-18` is rejected as an unsupported per-request version.
+Protocol metadata never grants desktop permissions, changes the runtime mode,
+or transfers another connection's session ownership. Repeat explicit Driver
+session names on calls as usual. When a response is lost, verify state before
+retrying an action.
+
+## Read the bundled skill
+
+Use `skills/list` to discover the catalog. Use `skills/get` with
+`uri: "skill://cua-driver/SKILL.md"` to retrieve the skill entry, including its
+full frontmatter and resource manifest. The entry lists every bundled file,
+with a `sha256:` digest and byte size.
+
+Use `resources/read` to fetch a listed URI. For example, a modern request is:
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "resources/read",
+ "params": {
+ "uri": "skill://cua-driver/SKILL.md",
+ "_meta": {
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
+ "io.modelcontextprotocol/clientCapabilities": {
+ "extensions": { "io.modelcontextprotocol/skills": {} }
+ }
+ }
+ }
+}
+```
+
+The eight-file pack includes the main skill, README, platform guides, browser
+guide, recording guide, and embedding guide. It is embedded in the endpoint
+binary, so serving it needs no separate skill installation. Only those exact
+resource URIs are readable. Directory listing, archives, arbitrary local
+files, and script execution are not supported by this endpoint.
+
+Clients verify each resource's raw UTF-8 bytes against the manifest before
+using it. Reading a resource does not activate a skill. The host owns skill
+selection, content-bound consent, and any execution approval. A base MCP client
+may support tools and resource reads without supporting native skill loading.
+
+The Skills extension follows accepted SEP-2640 at
+`d6b31a03504c15677d49b922b6b6ace0ef65728d`; its upstream publication is still
+pending. In particular, cache metadata for `skills/get` is unresolved upstream,
+so Driver does not add cache hints to that method.
+
+## HTTP limitation
+
+The authenticated loopback HTTP endpoint remains on legacy MCP. It explicitly
+rejects modern metadata and discovery requests. Use stdio for `2026-07-28`.
+Modern HTTP requires a reviewed application-handle contract so sessions can
+survive connection changes without weakening client isolation. OAuth and
+gateway ownership remain in RFC #3197.
+
+## Reproduce the protocol check
+
+From the repository root, install the isolated test dependencies and point the
+probe at the source-built candidate:
+
+```sh
+npm ci --ignore-scripts --prefix .github/scripts/cua-driver-mcp-compat/modern-client
+CUA_DRIVER_BINARY=/absolute/path/to/cua-driver \
+ node .github/scripts/cua-driver-mcp-compat/verify-modern.mjs
+```
+
+The probe uses `@modelcontextprotocol/client` 2.0.0 with the modern version
+pinned. It verifies discovery, a read-only tool call, skill enumeration and
+retrieval, complete resource bytes and hashes, and invalid-request rejection.
+It uses isolated state and makes no model or account calls. CI runs this probe
+on Linux, macOS, and Windows. This proves server/SDK interoperability, not
+native skill activation in a particular host.
diff --git a/libs/cua-driver/docs/test-harnesses-guide.md b/libs/cua-driver/docs/test-harnesses-guide.md
index d1d3778f01..17671d546c 100644
--- a/libs/cua-driver/docs/test-harnesses-guide.md
+++ b/libs/cua-driver/docs/test-harnesses-guide.md
@@ -316,6 +316,15 @@ Hosted results remain supplemental until the image and signing
identity provide the same release-parity guarantees as the maintained Lume
seed.
+Workers cloned from a granted private seed verify and reuse its app-owned TCC
+identity. A disposable SIP-disabled Lume worker without inherited grants must
+use `tests/runners/macos-lume/seed-tcc.sh` after installing the exact candidate
+as a certificate-signed `CuaDriverLocal.app`. The guarded helper is the only
+supported automated path: it verifies `VirtualMac*`, disabled SIP, the expected
+bundle identity, and the signed requirement before seeding only Accessibility
+and Screen Recording. Never hand-edit `TCC.db`. Restart the app afterward and
+prove live capture and input; database rows alone do not certify the desktop.
+
### Linux
Runner: `scripts/ci/linux/run-rust-e2e.sh`
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index ee79259b93..f2f45a370e 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -1155,6 +1155,7 @@ dependencies = [
"futures-util",
"httparse",
"image",
+ "jsonschema",
"libc",
"pip-preview",
"platform-linux",
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
index af64059418..ef089ba101 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
@@ -39,15 +39,16 @@ pub use inputs::{
ToolInput, TypeTextInput, MULTI_CALL_SESSION_DESCRIPTION,
};
pub use outputs::{
- advertised_output_schema, refusal_envelope_schema, ActionDelivery, ActionDeliveryMode,
- ActionEffect, ActionEscalation, ActionEscalationReason, ActionEscalationTarget, ActionEvidence,
- ActionEvidenceKind, ActionResult, ActionResultValidationError, ActionRoute,
- ClipboardReadOutput, ClipboardWriteOutput, CursorMotionOutput, CursorPointOutput,
- CursorPositionOutput, CursorThemeOutput, CursorVisualOutput, DesktopStateOutput,
- EffectiveScope, EndSessionOutput, GetAgentCursorStateOutput, ListSessionsOutput,
- ScreenSizeOutput, SessionClientKindOutput, SessionLifecycleState, SessionOutput,
- SessionStateOutput, SessionTransportOutput, SetAgentCursorEnabledOutput,
- SetAgentCursorMotionOutput, SetAgentCursorThemeOutput, StartSessionOutput, ToolOutput,
+ advertised_output_schema, conforming_error_envelope, is_refusal_envelope,
+ refusal_envelope_schema, ActionDelivery, ActionDeliveryMode, ActionEffect, ActionEscalation,
+ ActionEscalationReason, ActionEscalationTarget, ActionEvidence, ActionEvidenceKind,
+ ActionResult, ActionResultValidationError, ActionRoute, ClipboardReadOutput,
+ ClipboardWriteOutput, CursorMotionOutput, CursorPointOutput, CursorPositionOutput,
+ CursorThemeOutput, CursorVisualOutput, DesktopStateOutput, EffectiveScope, EndSessionOutput,
+ GetAgentCursorStateOutput, ListSessionsOutput, ScreenSizeOutput, SessionClientKindOutput,
+ SessionLifecycleState, SessionOutput, SessionStateOutput, SessionTransportOutput,
+ SetAgentCursorEnabledOutput, SetAgentCursorMotionOutput, SetAgentCursorThemeOutput,
+ StartSessionOutput, ToolOutput, TOOL_INVOCATION_FAILED_CODE,
};
pub use verification::{
BoundsExpectation, ElementPredicate, ElementSelector, PredicateOutcome, StatePredicate,
@@ -64,7 +65,9 @@ pub const CAPABILITY_VERSION: &str = "1";
/// Shape version for the checked-in generated client contract.
pub const CONTRACT_VERSION: &str = "0.8.0";
-/// MCP protocol version used by current cua-driver clients.
+/// Legacy version negotiated by `initialize.params.protocolVersion` and served
+/// by the loopback HTTP compatibility endpoint. Modern stdio discovery and
+/// per-request negotiation are defined by the endpoint implementation.
pub const MCP_PROTOCOL_VERSION: &str = "2025-06-18";
/// Tools whose successful result is the shared closed [`ActionResult`].
@@ -180,6 +183,8 @@ pub struct ContractManifest {
pub contract_version: String,
pub tools_list_schema_version: String,
pub capability_version: String,
+ /// Legacy initialize/HTTP compatibility version. This field retains its
+ /// historical name so generated SDK manifests remain backward compatible.
pub mcp_protocol_version: String,
pub transport: String,
pub tools: Vec<ToolContract>,
@@ -212,6 +217,7 @@ struct ToolIndexEntry {
capabilities: Vec<String>,
input_fields: BTreeSet<String>,
output_validator: OutputValidator,
+ advertises_output_schema: bool,
}
fn tool_index() -> &'static BTreeMap<String, ToolIndexEntry> {
@@ -229,12 +235,14 @@ fn tool_index() -> &'static BTreeMap<String, ToolIndexEntry> {
.flatten()
.map(|(name, _)| name.clone())
.collect();
+ let advertises_output_schema = tool.success_output_schema.is_some();
(
tool.name,
ToolIndexEntry {
capabilities: tool.capabilities,
input_fields,
output_validator: tool.output_validator,
+ advertises_output_schema,
},
)
})
@@ -262,6 +270,37 @@ pub fn tool_success_output_schema(name: &str) -> Option<Value> {
tool_contract(name).and_then(|contract| contract.success_output_schema)
}
+/// The `outputSchema` one tool advertises on `tools/list`, or `None` when it
+/// advertises none.
+///
+/// Action tools answer with the shared `ActionResult` shape; everything else
+/// uses its own success schema when it has one. Both are wrapped by
+/// [`advertised_output_schema`] so the refusal arm rides along, because MCP
+/// holds every `structuredContent` a tool emits — refusals included — to this
+/// schema.
+pub fn advertised_tool_output_schema(name: &str) -> Option<Value> {
+ let success = if is_action_result_tool(name) {
+ Some(<ActionResult as ToolOutput>::output_schema())
+ } else {
+ tool_success_output_schema(name)
+ };
+ success.map(advertised_output_schema)
+}
+
+/// Whether [`advertised_tool_output_schema`] would answer with a schema.
+///
+/// The `tools/call` boundary asks this once per call, so it reads the cached
+/// tool index instead of rebuilding the manifest and its schemas.
+/// `advertised_schema_presence_matches_the_cheap_predicate` pins the two
+/// against each other across the whole manifest.
+pub fn advertises_output_schema(name: &str) -> bool {
+ is_action_result_tool(name)
+ || name == "list_windows"
+ || tool_index()
+ .get(name)
+ .is_some_and(|entry| entry.advertises_output_schema)
+}
+
/// Validate a successful structured payload against the Rust output type that
/// also generates its SDK schema. Returns `Ok(false)` for non-SDK tools.
pub fn validate_success_output(name: &str, value: Value) -> Result<bool, String> {
@@ -296,6 +335,26 @@ mod tests {
assert!(manifest.experimental);
}
+ /// The `tools/call` boundary decides whether a client will validate a
+ /// payload from the cheap predicate, so a tool it disagrees with on would
+ /// be checked against a schema it never advertises, or skipped while a
+ /// client still validates it.
+ #[test]
+ fn advertised_schema_presence_matches_the_cheap_predicate() {
+ let mut names: Vec<String> = manifest().tools.into_iter().map(|tool| tool.name).collect();
+ names.extend(ACTION_RESULT_TOOLS.iter().map(|name| (*name).to_owned()));
+ names.push("list_windows".to_owned());
+ names.push("no_such_tool".to_owned());
+
+ for name in names {
+ assert_eq!(
+ advertised_tool_output_schema(&name).is_some(),
+ advertises_output_schema(&name),
+ "`{name}` disagrees on whether it advertises an output schema"
+ );
+ }
+ }
+
#[test]
fn every_action_result_tool_uses_the_closed_runtime_validator() {
let valid = serde_json::json!({
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
index 5caea810f8..0933fb5666 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
@@ -38,6 +38,61 @@ pub fn refusal_envelope_schema() -> Value {
})
}
+/// Marker code for structured error envelopes that carry no tool-specific
+/// refusal shape.
+///
+/// The transport and daemon failure paths answer with diagnostics like
+/// `{"exit_code": 1}` rather than a tool refusal. That payload satisfies
+/// neither arm of [`advertised_output_schema`]: it is missing the success
+/// arm's required keys while carrying a key the success arm does not allow,
+/// and it has none of the refusal arm's marker keys. Strict MCP clients then
+/// reject the whole response, so the error text in `content` never reaches the
+/// agent.
+pub const TOOL_INVOCATION_FAILED_CODE: &str = "tool_invocation_failed";
+
+/// Keys that make a payload recognisable to the refusal arm of
+/// [`advertised_output_schema`].
+const REFUSAL_MARKER_KEYS: [&str; 3] = ["refusal", "status", "code"];
+
+/// Whether a payload already satisfies the refusal arm of
+/// [`advertised_output_schema`].
+pub fn is_refusal_envelope(value: &Value) -> bool {
+ value.as_object().is_some_and(has_refusal_marker)
+}
+
+fn has_refusal_marker(object: &Map<String, Value>) -> bool {
+ REFUSAL_MARKER_KEYS
+ .iter()
+ .any(|marker| object.contains_key(*marker))
+}
+
+/// Guarantee a structured error payload is recognisable as a refusal.
+///
+/// Inserts [`TOOL_INVOCATION_FAILED_CODE`] when the payload carries none of the
+/// refusal marker keys, so any diagnostic an error path invents still validates
+/// against the advertised `outputSchema`. Payloads that already carry a marker
+/// are returned untouched.
+pub fn conforming_error_envelope(structured: Value) -> Value {
+ // Both arms require `type: object`, so a non-object diagnostic is kept as a
+ // value inside the envelope rather than being emitted as the envelope.
+ let mut object = match structured {
+ Value::Object(object) => object,
+ Value::Null => Map::new(),
+ other => {
+ let mut object = Map::new();
+ object.insert("detail".into(), other);
+ object
+ }
+ };
+ if !has_refusal_marker(&object) {
+ object.insert(
+ "code".into(),
+ Value::String(TOOL_INVOCATION_FAILED_CODE.into()),
+ );
+ }
+ Value::Object(object)
+}
+
/// Wrap a success schema into the shape advertised as the MCP `outputSchema`.
///
/// MCP requires every `structuredContent` a tool emits to validate against its
@@ -817,3 +872,46 @@ mod tests {
assert_eq!(result.validate_invariants(), Ok(()));
}
}
+
+#[cfg(test)]
+mod error_envelope_tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn a_diagnostic_without_a_marker_gains_one() {
+ let envelope = conforming_error_envelope(json!({"exit_code": 1}));
+
+ assert_eq!(envelope["code"], TOOL_INVOCATION_FAILED_CODE);
+ assert_eq!(envelope["exit_code"], 1);
+ }
+
+ #[test]
+ fn each_existing_marker_is_left_alone() {
+ for marker in ["refusal", "status", "code"] {
+ let envelope = conforming_error_envelope(json!({marker: "already-named"}));
+
+ assert_eq!(
+ envelope,
+ json!({marker: "already-named"}),
+ "guard rewrote a payload that already carries `{marker}`"
+ );
+ }
+ }
+
+ #[test]
+ fn a_non_object_diagnostic_becomes_an_object() {
+ let envelope = conforming_error_envelope(json!("daemon transport closed"));
+
+ assert_eq!(envelope["code"], TOOL_INVOCATION_FAILED_CODE);
+ assert_eq!(envelope["detail"], "daemon transport closed");
+ }
+
+ #[test]
+ fn an_absent_diagnostic_still_produces_a_refusal() {
+ assert_eq!(
+ conforming_error_envelope(Value::Null),
+ json!({"code": TOOL_INVOCATION_FAILED_CODE})
+ );
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
index 8bb3e214a0..5e6a53e3dd 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml
@@ -6,7 +6,7 @@ publish = false
[features]
default = ["yaml", "rego"]
-yaml = ["dep:serde_yaml_ng", "dep:regex"]
+yaml = ["dep:regex"]
rego = ["dep:regorus"]
[dependencies]
@@ -18,7 +18,7 @@ anyhow = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
async-trait = "0.1"
-serde_yaml_ng = { version = "0.10", optional = true }
+serde_yaml_ng = "0.10"
regex = { version = "1", optional = true }
regorus = { version = "0.10.1", optional = true }
# Used by the shared `image_utils` module — pure PNG/JPEG/resize/crosshair
@@ -48,6 +48,8 @@ time = { workspace = true }
getrandom = { workspace = true }
fs2 = { workspace = true }
hmac = { workspace = true }
+# Validate the raw wire payload; serde permits some shapes the schema rejects.
+jsonschema = { version = "0.46", default-features = false }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
@@ -57,13 +59,6 @@ libc = "0.2"
# a duplicate crate version.
[dev-dependencies]
tempfile = "3"
-# Test-only. Asserts the advertised `outputSchema` the way a strict MCP client
-# does — by validating real payloads against it. The runtime itself validates
-# success output by deserialising into the Rust type, so this stays out of the
-# shipped dependency graph.
-# Version matches the one regorus already pulls into this crate's graph, so
-# the test dependency reuses that build instead of adding a second copy.
-jsonschema = { version = "0.46", default-features = false }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging"] }
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
index 4638b9c264..b723100885 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
@@ -1,14 +1,10 @@
-//! MCP JSON-RPC 2.0 server over stdio — platform-independent core.
+//! Platform-independent Driver core and dual-era MCP dispatch.
//!
-//! Implements the Model Context Protocol (MCP) 2024-11-05 over stdio,
-//! matching the interface of `libs/cua-driver` (Swift/macOS) and
-//! `CuaDriver.Win` (.NET/Windows).
-//!
-//! # Protocol
-//! - Line-delimited JSON-RPC 2.0 on stdin/stdout
-//! - Methods: `initialize`, `notifications/initialized`, `tools/list`, `tools/call`
-//! - Each request has `jsonrpc: "2.0"`, `id` (any), `method`, optional `params`
-//! - Notifications (no `id`) are silently ignored
+//! Stdio supports legacy initialization and modern per-request negotiation.
+//! Protocol metadata does not grant Driver permissions or session ownership.
+
+pub mod mcp_skills;
+pub mod mcp_wire;
pub const RESPONSIBILITY_DISCLAIMED_ENV: &str = "CUA_DRIVER_RS_RESPONSIBILITY_DISCLAIMED";
@@ -66,6 +62,7 @@ pub mod ffmpeg_install;
pub mod health_report;
pub mod history;
pub mod image_utils;
+pub mod mcp_result;
pub mod page;
pub mod pip_hook;
pub mod policy;
@@ -90,5 +87,5 @@ pub mod video_ffmpeg;
pub mod window_inspection;
pub mod window_target;
-pub use cua_driver_contract::{CaptureScope, EscalationReason};
+pub use cua_driver_contract::{CaptureScope, EscalationReason, TOOL_INVOCATION_FAILED_CODE};
pub use recording::RecordingSession;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_result.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_result.rs
new file mode 100644
index 0000000000..a62d4e5a18
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_result.rs
@@ -0,0 +1,394 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The one place a `tools/call` result is held to the contract the driver
+//! advertises.
+//!
+//! MCP validates every `structuredContent` a tool emits against that tool's
+//! advertised `outputSchema` — payloads sent with `isError: true` included —
+//! and rejects a response whose payload matches neither arm (`-32602`), or a
+//! successful response that declares a schema and carries no structured
+//! payload at all (`-32600`). Either way the client discards the whole
+//! response, so the message the driver placed in `content` never reaches the
+//! agent.
+//!
+//! Individual result constructors cannot enforce that: `ToolResult::error`
+//! leaves `structuredContent` unset, the transport paths invent diagnostics
+//! like `{"exit_code": 1}`, and the proxy synthesises an empty success when the
+//! daemon answers `ok` with no result. So the rule lives here instead, on the
+//! single path every direct and daemon-backed `tools/call` result passes
+//! through.
+
+use serde_json::{json, Value};
+use std::{
+ collections::HashMap,
+ sync::{Arc, LazyLock, Mutex},
+};
+use tracing::warn;
+
+use cua_driver_contract::{
+ advertised_tool_output_schema, advertises_output_schema, conforming_error_envelope,
+ is_refusal_envelope, validate_success_output,
+};
+
+/// Marker code for a result the driver replaced because the tool's own payload
+/// could not be advertised under its `outputSchema`.
+pub const TOOL_OUTPUT_INVALID_CODE: &str = "tool_output_invalid";
+
+type CachedValidator = Result<Arc<jsonschema::Validator>, String>;
+static OUTPUT_VALIDATORS: LazyLock<Mutex<HashMap<String, CachedValidator>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+fn validate_wire_output(tool: &str, structured: &Value) -> Result<(), String> {
+ // Only published tools reach this cache, so arbitrary client names cannot grow it.
+ let validator = OUTPUT_VALIDATORS
+ .lock()
+ .map_err(|_| "output schema cache unavailable".to_owned())?
+ .entry(tool.to_owned())
+ .or_insert_with(|| {
+ let schema = advertised_tool_output_schema(tool)
+ .ok_or_else(|| "advertised output schema unavailable".to_owned())?;
+ jsonschema::validator_for(&schema)
+ .map(Arc::new)
+ .map_err(|error| format!("invalid advertised output schema: {error}"))
+ })
+ .clone()?;
+ if validator.is_valid(structured) {
+ Ok(())
+ } else {
+ Err("structured content does not match the advertised output schema".to_owned())
+ }
+}
+
+/// Hold one `tools/call` result to the tool's advertised `outputSchema`.
+///
+/// - An error result keeps its diagnostic, normalized into the refusal arm so
+/// a strict client accepts it and reads the `content` message.
+/// - A successful result for a tool that advertises a schema must carry a
+/// structured payload that the schema accepts. A missing or rejected payload
+/// becomes a conforming internal-error result, because the alternative is a
+/// response the client drops entirely.
+/// - A successful result for a tool that advertises no schema is returned
+/// unchanged: there is nothing for a client to validate it against.
+pub fn conforming_tool_result(tool: &str, result: Value) -> Value {
+ conforming_tool_result_inner(tool, result, advertises_output_schema(tool))
+}
+
+/// Reject contracts this proxy cannot safely normalize errors against. An older
+/// daemon may omit its schema; that does not promise the local success contract.
+pub fn validate_proxy_output_schema(tool: &str, schema: Option<&Value>) -> Result<(), String> {
+ if let Some(schema) = schema {
+ if advertised_tool_output_schema(tool).as_ref() != Some(schema) {
+ return Err(format!(
+ "incompatible daemon output schema for {tool}; use matching proxy and daemon versions"
+ ));
+ }
+ }
+ Ok(())
+}
+
+/// Apply the result boundary using the executing daemon's advertised contract.
+/// Only matching canonical schemas enter the bounded validator cache.
+pub fn conforming_proxy_tool_result(
+ tool: &str,
+ result: Value,
+ schema: Option<&Value>,
+) -> Result<Value, String> {
+ validate_proxy_output_schema(tool, schema)?;
+ Ok(conforming_tool_result_inner(tool, result, schema.is_some()))
+}
+
+fn conforming_tool_result_inner(tool: &str, result: Value, has_schema: bool) -> Value {
+ let Value::Object(mut result) = result else {
+ return internal_error_result(format!(
+ "internal result mismatch for {tool}: tool result is not an object"
+ ));
+ };
+
+ if result.get("isError").and_then(Value::as_bool) == Some(true) {
+ let structured = result.remove("structuredContent").unwrap_or(Value::Null);
+ result.insert(
+ "structuredContent".to_owned(),
+ conforming_error_envelope(structured),
+ );
+ return Value::Object(result);
+ }
+
+ if !has_schema {
+ return Value::Object(result);
+ }
+
+ match result.get("structuredContent") {
+ None | Some(Value::Null) => {
+ warn!(
+ tool,
+ "successful tool result declared an output schema but carried no structured content"
+ );
+ invalid_output_result(result, format!(
+ "internal output mismatch for {tool}: tool advertises an output schema but returned no structured content"
+ ))
+ }
+ // A refusal payload satisfies the advertised schema's other arm. The
+ // typed success validator would reject it, so ask the arm it belongs
+ // to rather than replacing a payload a client accepts.
+ Some(structured) if is_refusal_envelope(structured) => Value::Object(result),
+ Some(structured) => match validate_wire_output(tool, structured)
+ .and_then(|()| validate_success_output(tool, structured.clone()))
+ {
+ Ok(_) => Value::Object(result),
+ Err(error) => {
+ warn!(
+ tool,
+ "successful tool result carried structured content its output schema rejects"
+ );
+ invalid_output_result(
+ result,
+ format!("internal output mismatch for {tool}: {error}"),
+ )
+ }
+ },
+ }
+}
+
+fn invalid_output_result(original: serde_json::Map<String, Value>, message: String) -> Value {
+ let mut result = internal_error_result(message);
+ if let Some(Value::Array(content)) = original.get("content") {
+ result["content"]
+ .as_array_mut()
+ .unwrap()
+ .extend(content.clone());
+ }
+ if let Some(structured) = original.get("structuredContent") {
+ // Preserve evidence as an explicitly invalid diagnostic, never as success.
+ result["structuredContent"]["invalid_output"] = structured.clone();
+ }
+ result
+}
+
+/// Build the `isError: true` result for a call that produced no usable tool
+/// payload, already normalized into the refusal arm.
+pub fn internal_error_result(message: impl Into<String>) -> Value {
+ let message = format!(
+ "{}; the tool may have executed. Verify state before retrying.",
+ message.into()
+ );
+ json!({
+ "content": [{"type": "text", "text": message}],
+ "isError": true,
+ "structuredContent": {"code": TOOL_OUTPUT_INVALID_CODE, "execution_state": "unknown"},
+ })
+}
+
+/// Build a tool-level error result carrying a caller-supplied diagnostic.
+///
+/// The diagnostic is passed through untouched here; [`conforming_tool_result`]
+/// is what normalizes it, so every error path gets the same treatment whether
+/// or not it went through this constructor.
+pub fn tool_error_result(message: impl Into<String>, structured: Value) -> Value {
+ let message = message.into();
+ json!({
+ "content": [{"type": "text", "text": message}],
+ "isError": true,
+ "structuredContent": structured,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ //! The boundary is asserted the way a strict MCP client sees it: every
+ //! payload leaving it is validated against the schema the tool actually
+ //! advertises.
+
+ use super::*;
+ use cua_driver_contract::{advertised_tool_output_schema, TOOL_INVOCATION_FAILED_CODE};
+
+ /// An action tool, so the advertised schema is the shared `ActionResult`
+ /// one plus the refusal arm.
+ const ACTION_TOOL: &str = "click";
+ /// Advertises no `outputSchema` at all.
+ const UNSCHEMED_TOOL: &str = "no_such_tool";
+
+ #[track_caller]
+ fn assert_conforms(tool: &str, result: &Value) {
+ let schema = advertised_tool_output_schema(tool).expect("tool advertises a schema");
+ let compiled = jsonschema::validator_for(&schema).expect("schema compiles");
+ let structured = &result["structuredContent"];
+
+ assert!(
+ compiled.is_valid(structured),
+ "advertised schema rejected {structured}"
+ );
+ }
+
+ /// The shape this boundary exists for: the bare diagnostic the transport
+ /// paths invent satisfies neither arm, which is what produced the `-32602`
+ /// reports.
+ #[test]
+ fn a_bare_exit_code_diagnostic_does_not_validate() {
+ let schema = advertised_tool_output_schema(ACTION_TOOL).expect("schema");
+ let compiled = jsonschema::validator_for(&schema).expect("schema compiles");
+
+ assert!(!compiled.is_valid(&json!({"exit_code": 1})));
+ }
+
+ #[test]
+ fn an_error_diagnostic_gains_a_refusal_marker() {
+ let result = conforming_tool_result(
+ ACTION_TOOL,
+ tool_error_result("daemon transport closed", json!({"exit_code": 1})),
+ );
+
+ assert_conforms(ACTION_TOOL, &result);
+ // The diagnostic survives; only the marker is added.
+ assert_eq!(result["structuredContent"]["exit_code"], 1);
+ assert_eq!(
+ result["structuredContent"]["code"],
+ TOOL_INVOCATION_FAILED_CODE
+ );
+ assert_eq!(result["content"][0]["text"], "daemon transport closed");
+ }
+
+ /// `ToolResult::error` leaves `structuredContent` unset, and every tool
+ /// that refuses through it lands here.
+ #[test]
+ fn an_error_without_any_payload_gains_one() {
+ let result = conforming_tool_result(
+ ACTION_TOOL,
+ json!({"content": [{"type": "text", "text": "Unknown tool: nope"}], "isError": true}),
+ );
+
+ assert_conforms(ACTION_TOOL, &result);
+ assert_eq!(
+ result["structuredContent"]["code"],
+ TOOL_INVOCATION_FAILED_CODE
+ );
+ }
+
+ /// The guard adds a marker; it does not relabel a payload that already
+ /// names its own refusal.
+ #[test]
+ fn an_existing_refusal_code_is_preserved() {
+ let result = conforming_tool_result(
+ ACTION_TOOL,
+ tool_error_result("denied", json!({"code": "permission_denied"})),
+ );
+
+ assert_conforms(ACTION_TOOL, &result);
+ assert_eq!(result["structuredContent"]["code"], "permission_denied");
+ }
+
+ /// The proxy's empty-success fallback: a client that was promised a schema
+ /// rejects this response outright rather than reading it as an error.
+ #[test]
+ fn a_success_missing_its_structured_payload_becomes_an_error() {
+ let result = conforming_tool_result(ACTION_TOOL, json!({"content": [], "isError": false}));
+
+ assert_conforms(ACTION_TOOL, &result);
+ assert_eq!(result["isError"], true);
+ assert_eq!(
+ result["structuredContent"]["code"],
+ TOOL_OUTPUT_INVALID_CODE
+ );
+ }
+
+ #[test]
+ fn a_success_whose_payload_the_schema_rejects_becomes_an_error() {
+ let result = conforming_tool_result(
+ ACTION_TOOL,
+ json!({
+ "content": [],
+ "isError": false,
+ "structuredContent": {"clicked": true},
+ }),
+ );
+
+ assert_conforms(ACTION_TOOL, &result);
+ assert_eq!(result["isError"], true);
+ assert_eq!(
+ result["structuredContent"]["code"],
+ TOOL_OUTPUT_INVALID_CODE
+ );
+ }
+
+ #[test]
+ fn a_conforming_success_is_returned_untouched() {
+ let structured = json!({
+ "effect": "confirmed",
+ "route": "accessibility",
+ "delivery": {"mode": "background"},
+ "evidence": [{"kind": "value_readback"}],
+ });
+ let success = json!({
+ "content": [{"type": "text", "text": "clicked"}],
+ "isError": false,
+ "structuredContent": structured,
+ });
+
+ let result = conforming_tool_result(ACTION_TOOL, success.clone());
+
+ assert_conforms(ACTION_TOOL, &result);
+ assert_eq!(result, success);
+ }
+
+ #[test]
+ fn a_success_missing_required_nullable_fields_becomes_a_conforming_error() {
+ let structured = json!({
+ "session": "schema-test",
+ "capture_scope": "window",
+ "effective_scope": "window",
+ "desktop_capture_authorized": false,
+ "desktop_unlocked": false,
+ });
+ let tool = "get_session_state";
+ assert!(validate_success_output(tool, structured.clone()).is_ok());
+ let result = conforming_tool_result(
+ tool,
+ json!({
+ "content": [{"type": "text", "text": "action completed"}],
+ "isError": false,
+ "structuredContent": structured,
+ }),
+ );
+
+ assert_conforms(tool, &result);
+ assert_eq!(result["isError"], true);
+ assert_eq!(
+ result["structuredContent"]["code"],
+ TOOL_OUTPUT_INVALID_CODE
+ );
+ assert_eq!(result["structuredContent"]["execution_state"], "unknown");
+ assert_eq!(
+ result["structuredContent"]["invalid_output"]["session"],
+ "schema-test"
+ );
+ assert!(result["content"][0]["text"]
+ .as_str()
+ .unwrap()
+ .contains("Verify state before retrying"));
+ assert_eq!(result["content"][1]["text"], "action completed");
+ }
+
+ /// A tool with no advertised schema has no contract to violate, so its
+ /// successful payload must not be second-guessed here.
+ #[test]
+ fn a_success_from_a_tool_without_a_schema_is_untouched() {
+ let success = json!({
+ "content": [{"type": "text", "text": "ok"}],
+ "isError": false,
+ "structuredContent": {"anything": "goes"},
+ });
+
+ assert_eq!(
+ conforming_tool_result(UNSCHEMED_TOOL, success.clone()),
+ success
+ );
+ }
+
+ #[test]
+ fn a_result_that_is_not_an_object_becomes_a_conforming_error() {
+ let result = conforming_tool_result(ACTION_TOOL, json!("not a result"));
+
+ assert_conforms(ACTION_TOOL, &result);
+ assert_eq!(result["isError"], true);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_skills.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_skills.rs
new file mode 100644
index 0000000000..1ce8f0691a
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_skills.rs
@@ -0,0 +1,337 @@
+//! Read-only transport for the canonical, compiled-in Cua Driver skill pack.
+//!
+//! Implements SEP-2640 at d6b31a03504c15677d49b922b6b6ace0ef65728d.
+//! Reading these resources neither activates a skill nor grants execution authority.
+
+use std::sync::OnceLock;
+
+use serde_json::{json, Map, Value};
+use sha2::{Digest, Sha256};
+
+use crate::protocol::{Request, Response};
+
+const SKILL_URI: &str = "skill://cua-driver/SKILL.md";
+const URI_PREFIX: &str = "skill://cua-driver/";
+
+// This is the entire resource namespace. Never resolve a client URI on disk.
+const FILES: &[(&str, &str)] = &[
+ (
+ "BROWSER.md",
+ include_str!("../../../Skills/cua-driver/BROWSER.md"),
+ ),
+ (
+ "EMBEDDING.md",
+ include_str!("../../../Skills/cua-driver/EMBEDDING.md"),
+ ),
+ (
+ "LINUX.md",
+ include_str!("../../../Skills/cua-driver/LINUX.md"),
+ ),
+ (
+ "MACOS.md",
+ include_str!("../../../Skills/cua-driver/MACOS.md"),
+ ),
+ (
+ "README.md",
+ include_str!("../../../Skills/cua-driver/README.md"),
+ ),
+ (
+ "RECORDING.md",
+ include_str!("../../../Skills/cua-driver/RECORDING.md"),
+ ),
+ (
+ "SKILL.md",
+ include_str!("../../../Skills/cua-driver/SKILL.md"),
+ ),
+ (
+ "WINDOWS.md",
+ include_str!("../../../Skills/cua-driver/WINDOWS.md"),
+ ),
+];
+
+struct Pack {
+ entry: Value,
+ resources: Vec<Value>,
+}
+
+fn parse_frontmatter(source: &str) -> Result<Value, String> {
+ let mut lines = source.lines();
+ if lines.next() != Some("---") {
+ return Err("skill must start with YAML frontmatter".into());
+ }
+ let mut yaml = String::new();
+ for line in lines {
+ if line == "---" {
+ let value: Value = serde_yaml_ng::from_str(&yaml).map_err(|e| e.to_string())?;
+ if !value.is_object()
+ || value.get("name").and_then(Value::as_str) != Some("cua-driver")
+ || value.get("description").and_then(Value::as_str).is_none()
+ {
+ return Err("skill frontmatter must describe cua-driver".into());
+ }
+ return Ok(value);
+ }
+ yaml.push_str(line);
+ yaml.push('\n');
+ }
+ Err("skill frontmatter is not terminated".into())
+}
+
+fn pack() -> &'static Pack {
+ static PACK: OnceLock<Pack> = OnceLock::new();
+ PACK.get_or_init(|| {
+ let frontmatter = parse_frontmatter(include_str!("../../../Skills/cua-driver/SKILL.md"))
+ .expect("embedded canonical skill must have valid JSON-compatible frontmatter");
+ let mut manifest = Vec::with_capacity(FILES.len());
+ let mut resources = Vec::with_capacity(FILES.len());
+ for (name, text) in FILES {
+ let uri = format!("{URI_PREFIX}{name}");
+ manifest.push(json!({
+ "uri": uri,
+ "digest": format!("sha256:{:x}", Sha256::digest(text.as_bytes())),
+ "size": text.len(),
+ }));
+ let mut resource = json!({
+ "uri": uri,
+ "name": name,
+ "mimeType": "text/markdown",
+ "size": text.len(),
+ });
+ if *name == "SKILL.md" {
+ resource["name"] = frontmatter["name"].clone();
+ resource["description"] = frontmatter["description"].clone();
+ }
+ resources.push(resource);
+ }
+ Pack {
+ entry: json!({"uri": SKILL_URI, "frontmatter": frontmatter, "resources": manifest}),
+ resources,
+ }
+ })
+}
+
+/// Capabilities shared by every MCP transport serving this pack.
+pub fn capabilities() -> Value {
+ json!({
+ "tools": {},
+ "resources": {},
+ "extensions": {"io.modelcontextprotocol/skills": {}},
+ })
+}
+
+fn params(request: &Request) -> Result<Option<&Map<String, Value>>, &'static str> {
+ match &request.params {
+ None => Ok(None),
+ Some(Value::Object(params)) => Ok(Some(params)),
+ Some(_) => Err("params must be an object"),
+ }
+}
+
+fn required_uri(params: Option<&Map<String, Value>>) -> Result<&str, &'static str> {
+ params
+ .and_then(|params| params.get("uri"))
+ .and_then(Value::as_str)
+ .ok_or("uri must be a string")
+}
+
+fn result(request: &Request) -> Result<Value, &'static str> {
+ let params = params(request)?;
+ // A complete, single-page catalog has no valid continuation cursor.
+ if params.is_some_and(|params| params.contains_key("cursor")) {
+ return Err("this resource catalog has no continuation cursor");
+ }
+ match request.method.as_str() {
+ "skills/list" => Ok(json!({"skills": [&pack().entry]})),
+ "skills/get" => {
+ if required_uri(params)? != SKILL_URI {
+ return Err("unknown skill URI");
+ }
+ Ok(json!({"skill": &pack().entry}))
+ }
+ "resources/list" => Ok(json!({"resources": &pack().resources})),
+ "resources/read" => {
+ let uri = required_uri(params)?;
+ let name = uri.strip_prefix(URI_PREFIX).ok_or("unknown resource URI")?;
+ let (_, text) = FILES
+ .iter()
+ .find(|(file, _)| *file == name)
+ .ok_or("unknown resource URI")?;
+ Ok(json!({"contents": [{"uri": uri, "mimeType": "text/markdown", "text": text}]}))
+ }
+ _ => unreachable!("handle filters methods"),
+ }
+}
+
+/// Handle skill/resource methods; the transport adds version-specific envelopes.
+pub fn handle(request: &Request, id: Value) -> Option<Response> {
+ if !matches!(
+ request.method.as_str(),
+ "skills/list" | "skills/get" | "resources/list" | "resources/read"
+ ) {
+ return None;
+ }
+ Some(match result(request) {
+ Ok(result) => Response::ok(id, result),
+ Err(message) => Response::error(id, -32602, message),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::protocol::ResponseBody;
+
+ fn request(method: &str, params: Option<Value>) -> Request {
+ Request {
+ jsonrpc: "2.0".into(),
+ id: Some(json!(42)),
+ method: method.into(),
+ params,
+ }
+ }
+
+ fn call(method: &str, params: Option<Value>) -> Value {
+ let response = handle(&request(method, params), json!(42)).unwrap();
+ assert_eq!(response.id, json!(42));
+ match response.body {
+ ResponseBody::Result { result } => result,
+ ResponseBody::Error { error } => panic!("unexpected error: {error:?}"),
+ }
+ }
+
+ fn invalid(method: &str, params: Option<Value>) {
+ match handle(&request(method, params), json!(42)).unwrap().body {
+ ResponseBody::Error { error } => assert_eq!(error.code, -32602),
+ ResponseBody::Result { result } => panic!("unexpected success: {result}"),
+ }
+ }
+
+ #[test]
+ fn manifest_matches_every_raw_embedded_resource() {
+ let listed = call("skills/list", None);
+ assert_eq!(listed["skills"].as_array().unwrap().len(), 1);
+ assert!(listed.get("resultType").is_none());
+ assert!(listed.get("ttlMs").is_none());
+ assert!(listed.get("cacheScope").is_none());
+ let entry = &listed["skills"][0];
+ assert_eq!(entry["uri"], SKILL_URI);
+ assert_eq!(
+ call("skills/get", Some(json!({"uri": SKILL_URI})))["skill"],
+ *entry
+ );
+ let manifest = entry["resources"].as_array().unwrap();
+ let resources = call("resources/list", Some(json!({})));
+ assert_eq!(manifest.len(), 8);
+ assert_eq!(
+ resources["resources"].as_array().unwrap().len(),
+ manifest.len()
+ );
+ for (index, (name, text)) in FILES.iter().enumerate() {
+ let uri = format!("{URI_PREFIX}{name}");
+ assert_eq!(manifest[index]["uri"], uri);
+ assert_eq!(manifest[index]["size"], text.len());
+ assert_eq!(
+ manifest[index]["digest"],
+ format!("sha256:{:x}", Sha256::digest(text.as_bytes()))
+ );
+ assert_eq!(resources["resources"][index]["uri"], uri);
+ let read = call("resources/read", Some(json!({"uri": uri})));
+ assert_eq!(read["contents"].as_array().unwrap().len(), 1);
+ assert_eq!(read["contents"][0]["mimeType"], "text/markdown");
+ assert_eq!(
+ read["contents"][0]["text"].as_str().unwrap().as_bytes(),
+ text.as_bytes()
+ );
+ }
+ }
+
+ #[test]
+ fn full_frontmatter_preserves_nested_metadata_and_scalar_types() {
+ let source = include_str!("../../../Skills/cua-driver/SKILL.md");
+ let yaml = source.splitn(3, "---").nth(1).unwrap();
+ let expected: Value = serde_yaml_ng::from_str(yaml).unwrap();
+ assert_eq!(pack().entry["frontmatter"], expected);
+ assert!(expected["version"].is_string());
+ assert_eq!(
+ expected["metadata"]["openclaw"]["envVars"][0]["required"],
+ false
+ );
+ let extended = "---\nname: cua-driver\ndescription: |\n A multiline\n description.\nversion: '1.2.3'\nfuture: {enabled: true, count: 7, values: [null, 1.5, text]}\n---\nbody";
+ let parsed = parse_frontmatter(extended).unwrap();
+ assert_eq!(parsed["description"], "A multiline\ndescription.\n");
+ assert_eq!(
+ parsed["future"],
+ json!({"enabled": true, "count": 7, "values": [null, 1.5, "text"]})
+ );
+ assert!(parse_frontmatter("---\nname: cua-driver\n").is_err());
+ }
+
+ #[test]
+ fn uri_allowlist_rejects_aliases_traversal_and_foreign_resources() {
+ for uri in [
+ "skill://cua-driver",
+ "skill://cua-driver/",
+ "skill://cua-driver/unknown.md",
+ "skill://cua-driver/../SKILL.md",
+ "skill://cua-driver/./SKILL.md",
+ "skill://cua-driver/%53KILL.md",
+ "skill://cua-driver/%2e%2e/SKILL.md",
+ "skill://cua-driver/SKILL.md?query=1",
+ "skill://cua-driver/SKILL.md#fragment",
+ "skill://cua-driver/SKILL.md/",
+ "skill://cua-driver//SKILL.md",
+ "skill://cua-driver/skill.md",
+ "skill://CUA-DRIVER/SKILL.md",
+ "skill://foreign/SKILL.md",
+ "file:///etc/passwd",
+ "https://cua.ai/SKILL.md",
+ "skill://cua-driver/..\\SKILL.md",
+ "skill://cua-driver/SKILL.md\0",
+ ] {
+ invalid("resources/read", Some(json!({"uri": uri})));
+ invalid("skills/get", Some(json!({"uri": uri})));
+ }
+ invalid(
+ "skills/get",
+ Some(json!({"uri": "skill://cua-driver/BROWSER.md"})),
+ );
+ }
+
+ #[test]
+ fn malformed_params_and_cursors_are_invalid() {
+ for method in [
+ "skills/list",
+ "skills/get",
+ "resources/list",
+ "resources/read",
+ ] {
+ for params in [json!(null), json!(1), json!([]), json!("invalid")] {
+ invalid(method, Some(params));
+ }
+ for cursor in [json!("next"), json!(""), json!(null), json!(5)] {
+ invalid(method, Some(json!({"uri": SKILL_URI, "cursor": cursor})));
+ }
+ }
+ for method in ["skills/get", "resources/read"] {
+ invalid(method, None);
+ invalid(method, Some(json!({})));
+ invalid(method, Some(json!({"uri": 7})));
+ }
+ }
+
+ #[test]
+ fn only_supported_methods_and_capabilities_are_exposed() {
+ assert_eq!(
+ capabilities(),
+ json!({"tools": {}, "resources": {}, "extensions": {"io.modelcontextprotocol/skills": {}}})
+ );
+ for method in [
+ "tools/call",
+ "resources/directory/read",
+ "skills/execute",
+ "resources/templates/list",
+ ] {
+ assert!(handle(&request(method, None), json!(42)).is_none());
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_wire.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_wire.rs
new file mode 100644
index 0000000000..7b3d30db79
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_wire.rs
@@ -0,0 +1,339 @@
+//! Shared legacy and per-request MCP semantics for the stdio adapters.
+
+use serde_json::{json, Value};
+
+use crate::protocol::{initialize_result, Request, Response, ResponseBody};
+
+pub const MODERN_PROTOCOL_VERSION: &str = "2026-07-28";
+pub const PROTOCOL_VERSION_KEY: &str = "io.modelcontextprotocol/protocolVersion";
+pub const CLIENT_CAPABILITIES_KEY: &str = "io.modelcontextprotocol/clientCapabilities";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ProtocolEra {
+ Legacy,
+ Modern,
+}
+
+/// Only a legacy initialize permits subsequent metadata-free stdio requests.
+/// Modern capabilities are validated on each request and are never retained.
+#[derive(Debug, Default)]
+pub struct ProtocolSession {
+ legacy_initialized: bool,
+}
+
+impl ProtocolSession {
+ pub fn validate(&mut self, req: &Request) -> Result<ProtocolEra, Response> {
+ let era = classify_request(req)?;
+ if era == ProtocolEra::Legacy {
+ if req.method == "initialize" {
+ // Preserve the historical permissive initialize params contract.
+ self.legacy_initialized = true;
+ } else if !self.legacy_initialized {
+ return Err(invalid_params(
+ req,
+ "Missing required per-request MCP metadata",
+ ));
+ }
+ }
+ Ok(era)
+ }
+}
+
+fn invalid_params(req: &Request, message: &str) -> Response {
+ Response::error(req.id.clone().unwrap_or(Value::Null), -32602, message)
+}
+
+fn valid_request_id(req: &Request) -> bool {
+ req.id
+ .as_ref()
+ .is_some_and(|id| id.is_string() || id.as_i64().is_some() || id.as_u64().is_some())
+}
+
+/// Classify an individual request, retaining legacy compatibility for embedders.
+/// Stdio adapters additionally use `ProtocolSession` to reject absent metadata.
+pub fn classify_request(req: &Request) -> Result<ProtocolEra, Response> {
+ let meta = req.params.as_ref().and_then(|params| params.get("_meta"));
+ let modern_keys_present = meta.is_some_and(|meta| {
+ meta.get(PROTOCOL_VERSION_KEY).is_some() || meta.get(CLIENT_CAPABILITIES_KEY).is_some()
+ });
+ if !modern_keys_present && req.method != "server/discover" {
+ if meta.is_some_and(|meta| !meta.is_object()) {
+ return Err(invalid_params(req, "MCP _meta must be an object"));
+ }
+ return Ok(ProtocolEra::Legacy);
+ }
+ if req.jsonrpc != "2.0" || !valid_request_id(req) {
+ return Err(Response::error(
+ Value::Null,
+ -32600,
+ "Invalid JSON-RPC request",
+ ));
+ }
+ if !req.params.as_ref().is_some_and(Value::is_object) {
+ return Err(invalid_params(req, "MCP params must be an object"));
+ }
+ let version = meta
+ .and_then(|meta| meta.get(PROTOCOL_VERSION_KEY))
+ .and_then(Value::as_str)
+ .ok_or_else(|| invalid_params(req, "Missing or invalid MCP protocolVersion metadata"))?;
+ if version != MODERN_PROTOCOL_VERSION {
+ return Err(Response::error_with_data(
+ req.id.clone().unwrap_or(Value::Null),
+ -32022,
+ "Unsupported protocol version",
+ Some(json!({"supported": [MODERN_PROTOCOL_VERSION], "requested": version})),
+ ));
+ }
+ if !meta
+ .and_then(|meta| meta.get(CLIENT_CAPABILITIES_KEY))
+ .is_some_and(Value::is_object)
+ {
+ return Err(invalid_params(
+ req,
+ "Missing or invalid MCP clientCapabilities metadata",
+ ));
+ }
+ Ok(ProtocolEra::Modern)
+}
+
+pub fn server_capabilities() -> Value {
+ let mut capabilities = crate::mcp_skills::capabilities();
+ capabilities["tools"] = json!({});
+ capabilities
+}
+
+/// Methods that do not require platform tool execution, shared by both adapters.
+pub fn handle_metadata_request(req: &Request, id: Value) -> Option<Response> {
+ match req.method.as_str() {
+ "server/discover" => Some(Response::ok(
+ id,
+ json!({
+ "supportedVersions": [MODERN_PROTOCOL_VERSION],
+ "capabilities": server_capabilities(),
+ "instructions": initialize_result()["instructions"],
+ }),
+ )),
+ "ping" => Some(Response::ok(id, json!({}))),
+ _ => crate::mcp_skills::handle(req, id),
+ }
+}
+
+/// Add only protocol envelope fields; tool structured content remains untouched.
+pub fn finish_response(era: ProtocolEra, method: &str, mut response: Response) -> Response {
+ if era == ProtocolEra::Modern {
+ if let ResponseBody::Result { result } = &mut response.body {
+ if let Some(result) = result.as_object_mut() {
+ result.insert("resultType".into(), json!("complete"));
+ let meta = result.entry("_meta").or_insert_with(|| json!({}));
+ if !meta.is_object() {
+ *meta = json!({});
+ }
+ meta["io.modelcontextprotocol/serverInfo"] =
+ json!({"name": "cua-driver", "version": env!("CARGO_PKG_VERSION")});
+ if method == "server/discover"
+ || method.ends_with("/list")
+ || method.ends_with("/read")
+ {
+ result.insert("ttlMs".into(), json!(0));
+ result.insert("cacheScope".into(), json!("private"));
+ }
+ }
+ }
+ }
+ response
+}
+
+/// Reject malformed calls and modern unknown tools before any tool invocation.
+pub fn validate_tool_call(
+ req: &Request,
+ id: Value,
+ era: ProtocolEra,
+ inventory: &Value,
+) -> Result<(), Response> {
+ if req.method != "tools/call" {
+ return Ok(());
+ }
+ let call = req
+ .tool_call()
+ .map_err(|error| Response::error(id.clone(), -32602, format!("Invalid params: {error}")))?;
+ if !call.args.is_object() {
+ return Err(Response::error(
+ id,
+ -32602,
+ "Tool arguments must be an object",
+ ));
+ }
+ if era == ProtocolEra::Modern
+ && !inventory["tools"].as_array().is_some_and(|tools| {
+ tools
+ .iter()
+ .any(|tool| tool["name"].as_str() == Some(call.name.as_str()))
+ })
+ {
+ return Err(Response::error(
+ id,
+ -32602,
+ format!("Unknown tool: {}", call.name),
+ ));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn request(method: &str, meta: Value) -> Request {
+ serde_json::from_value(json!({
+ "jsonrpc": "2.0", "id": 1, "method": method, "params": {"_meta": meta}
+ }))
+ .unwrap()
+ }
+
+ fn modern_meta() -> Value {
+ json!({PROTOCOL_VERSION_KEY: MODERN_PROTOCOL_VERSION, CLIENT_CAPABILITIES_KEY: {}})
+ }
+
+ #[test]
+ fn modern_versions_and_capabilities_are_validated_per_request() {
+ let mut session = ProtocolSession::default();
+ assert_eq!(
+ session.validate(&request("ping", modern_meta())).unwrap(),
+ ProtocolEra::Modern
+ );
+ for meta in [
+ json!({}),
+ json!({PROTOCOL_VERSION_KEY: MODERN_PROTOCOL_VERSION}),
+ json!({PROTOCOL_VERSION_KEY: MODERN_PROTOCOL_VERSION, CLIENT_CAPABILITIES_KEY: []}),
+ ] {
+ let error = serde_json::to_value(session.validate(&request("ping", meta)).unwrap_err())
+ .unwrap();
+ assert_eq!(error["error"]["code"], -32602);
+ }
+ let error = serde_json::to_value(
+ session
+ .validate(&request(
+ "ping",
+ json!({
+ PROTOCOL_VERSION_KEY: "unknown", CLIENT_CAPABILITIES_KEY: {}
+ }),
+ ))
+ .unwrap_err(),
+ )
+ .unwrap();
+ assert_eq!(error["error"]["code"], -32022);
+ assert_eq!(
+ error["error"]["data"],
+ json!({"supported": [MODERN_PROTOCOL_VERSION], "requested": "unknown"})
+ );
+ }
+
+ #[test]
+ fn only_legacy_initialize_enables_metadata_free_requests() {
+ let mut session = ProtocolSession::default();
+ let legacy = request("ping", json!({}));
+ assert!(session.validate(&legacy).is_err());
+ assert_eq!(
+ session.validate(&request("initialize", json!({}))).unwrap(),
+ ProtocolEra::Legacy
+ );
+ assert_eq!(session.validate(&legacy).unwrap(), ProtocolEra::Legacy);
+ assert!(session
+ .validate(&request(
+ "ping",
+ json!({PROTOCOL_VERSION_KEY: MODERN_PROTOCOL_VERSION})
+ ))
+ .is_err());
+
+ // Namespaced per-request negotiation belongs only to the modern
+ // protocol. Legacy clients negotiate in initialize params, then omit
+ // this metadata on later requests.
+ let error = serde_json::to_value(
+ session
+ .validate(&request(
+ "ping",
+ json!({
+ PROTOCOL_VERSION_KEY: "2025-06-18",
+ CLIENT_CAPABILITIES_KEY: {}
+ }),
+ ))
+ .unwrap_err(),
+ )
+ .unwrap();
+ assert_eq!(error["error"]["code"], -32022);
+ assert_eq!(
+ error["error"]["data"],
+ json!({
+ "supported": [MODERN_PROTOCOL_VERSION],
+ "requested": "2025-06-18"
+ })
+ );
+ }
+
+ #[test]
+ fn modern_discovery_and_tool_envelopes_follow_canonical_shapes() {
+ let req = request("server/discover", modern_meta());
+ let response = finish_response(
+ ProtocolEra::Modern,
+ &req.method,
+ handle_metadata_request(&req, json!(1)).unwrap(),
+ );
+ let result = serde_json::to_value(response).unwrap()["result"].clone();
+ assert_eq!(result["resultType"], "complete");
+ assert_eq!(
+ result["supportedVersions"],
+ json!([MODERN_PROTOCOL_VERSION])
+ );
+ assert_eq!(result["ttlMs"], 0);
+ assert_eq!(result["cacheScope"], "private");
+ assert_eq!(
+ result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
+ "cua-driver"
+ );
+ assert!(result.get("serverInfo").is_none());
+ let structured = json!({"resultType": "domain-value", "private": [1, 2]});
+ let response = finish_response(
+ ProtocolEra::Modern,
+ "tools/call",
+ Response::ok(
+ json!(1),
+ json!({"content": [], "structuredContent": structured}),
+ ),
+ );
+ let result = serde_json::to_value(response).unwrap()["result"].clone();
+ assert_eq!(result["structuredContent"], structured);
+ assert_eq!(result["resultType"], "complete");
+ assert!(result.get("ttlMs").is_none());
+ }
+
+ #[test]
+ fn legacy_errors_omit_optional_data() {
+ let error = serde_json::to_value(Response::error(json!(1), -32602, "invalid")).unwrap();
+ assert!(error["error"].get("data").is_none());
+ }
+
+ #[test]
+ fn modern_invalid_jsonrpc_envelopes_are_rejected() {
+ for (jsonrpc, id) in [
+ ("1.0", json!(1)),
+ ("2.0", json!(true)),
+ ("2.0", json!(1.5)),
+ ("2.0", json!({})),
+ ] {
+ let req = serde_json::from_value(json!({
+ "jsonrpc": jsonrpc, "id": id, "method": "ping",
+ "params": {"_meta": modern_meta()}
+ }))
+ .unwrap();
+ let response = serde_json::to_value(classify_request(&req).unwrap_err()).unwrap();
+ assert_eq!(response["error"]["code"], -32600);
+ assert!(response["id"].is_null());
+ }
+ let req = serde_json::from_value(json!({
+ "jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": []
+ }))
+ .unwrap();
+ let response = serde_json::to_value(classify_request(&req).unwrap_err()).unwrap();
+ assert_eq!(response["error"]["code"], -32602);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs
index 1ce408ffc6..ec46f81507 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs
@@ -203,6 +203,8 @@ pub enum ResponseBody {
pub struct RpcError {
pub code: i64,
pub message: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub data: Option<Value>,
}
impl Response {
@@ -215,6 +217,15 @@ impl Response {
}
pub fn error(id: Value, code: i64, message: impl Into<String>) -> Self {
+ Self::error_with_data(id, code, message, None)
+ }
+
+ pub fn error_with_data(
+ id: Value,
+ code: i64,
+ message: impl Into<String>,
+ data: Option<Value>,
+ ) -> Self {
Self {
jsonrpc: "2.0",
id,
@@ -222,6 +233,7 @@ impl Response {
error: RpcError {
code,
message: message.into(),
+ data,
},
},
}
@@ -331,7 +343,7 @@ impl ToolResult {
pub fn initialize_result() -> Value {
serde_json::json!({
"protocolVersion": "2025-06-18",
- "capabilities": { "tools": {} },
+ "capabilities": crate::mcp_wire::server_capabilities(),
"serverInfo": { "name": "cua-driver", "version": env!("CARGO_PKG_VERSION") },
"instructions": agent_instructions()
})
@@ -369,7 +381,7 @@ fn agent_instructions() -> String {
format!(
r#"cua-driver: cross-platform background computer-use automation.
-Before UI work, classify the desired outcome. For non-GUI outcomes, prefer a client-provided app API/SDK, headless/background interface, CLI, or filesystem operation and read the result back in that semantic domain. This server has no shell.
+For non-GUI outcomes, prefer a client-provided app API/SDK, headless/background interface, CLI, or filesystem operation and read the result back in that semantic domain. This server has no shell.
On continuation/recent-work, when available, call `history_status`; if ready, make one bounded initial `history_query` before broad discovery; otherwise continue.
@@ -381,7 +393,7 @@ Workflow per turn:
2. Act with the fresh index.
3. `verify_state(pid, window_id, expect)` checks bounded postconditions. `unknown` is not success; `include_screenshot:true` lets the multimodal agent judge visual evidence.
-If the `cua-driver` skill is loaded, follow SKILL.md plus {platform_skill_pointer}."#
+Read `skill://cua-driver/SKILL.md` via `skills/get` or `resources/read`. Hosts control activation/consent. When activated, follow SKILL.md and {platform_skill_pointer}."#
)
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
index 30b31c3f62..2f2402f5b2 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
@@ -5,6 +5,7 @@ use std::time::Instant;
use tracing::warn;
use crate::authorization::authorize_tool_call;
+use crate::mcp_result::{conforming_tool_result, tool_error_result};
use crate::protocol::{initialize_result, InitializeMetadata, Request, Response, ResponseBody};
use crate::tool::ToolRegistry;
@@ -878,9 +879,39 @@ async fn handle_request_inner(
id: serde_json::Value,
provider: &dyn ToolProvider,
transport_session: Option<&str>,
+) -> Response {
+ let era = match crate::mcp_wire::classify_request(&req) {
+ Ok(era) => era,
+ Err(response) => return response,
+ };
+ if req.method == "tools/call" {
+ if let Err(response) =
+ crate::mcp_wire::validate_tool_call(&req, id.clone(), era, &provider.tools_list())
+ {
+ return response;
+ }
+ }
+ let method = req.method.clone();
+ let response =
+ if let Some(response) = crate::mcp_wire::handle_metadata_request(&req, id.clone()) {
+ response
+ } else {
+ dispatch_request(req, id, provider, transport_session, era).await
+ };
+ crate::mcp_wire::finish_response(era, &method, response)
+}
+
+async fn dispatch_request(
+ req: Request,
+ id: serde_json::Value,
+ provider: &dyn ToolProvider,
+ transport_session: Option<&str>,
+ era: crate::mcp_wire::ProtocolEra,
) -> Response {
match req.method.as_str() {
- "initialize" => Response::ok(id, initialize_result()),
+ "initialize" if era == crate::mcp_wire::ProtocolEra::Legacy => {
+ Response::ok(id, initialize_result())
+ }
"tools/list" => Response::ok(id, provider.tools_list()),
@@ -891,9 +922,12 @@ async fn handle_request_inner(
if let Err(error) = authorize_tool_call(&call.name, &call.args) {
return Response::ok(
id,
- tool_error_result(
- error.to_string(),
- serde_json::json!({"code": "permission_denied"}),
+ conforming_tool_result(
+ &call.name,
+ tool_error_result(
+ error.to_string(),
+ serde_json::json!({"code": "permission_denied"}),
+ ),
),
);
}
@@ -927,13 +961,14 @@ async fn handle_request_inner(
}
}
- match provider.invoke_tool(&call.name, call.args).await {
- Ok(result) => Response::ok(id, result),
- Err(error) => Response::ok(
- id,
- tool_error_result(error, serde_json::json!({"exit_code": 1})),
- ),
- }
+ // Both arms answer through the shared boundary, so a tool
+ // payload and an invocation failure are held to the same
+ // advertised `outputSchema`.
+ let result = match provider.invoke_tool(&call.name, call.args).await {
+ Ok(result) => result,
+ Err(error) => tool_error_result(error, serde_json::json!({"exit_code": 1})),
+ };
+ Response::ok(id, conforming_tool_result(&call.name, result))
}
},
@@ -944,12 +979,158 @@ async fn handle_request_inner(
}
}
-fn tool_error_result(message: String, structured: serde_json::Value) -> serde_json::Value {
- serde_json::json!({
- "content": [{"type": "text", "text": message}],
- "isError": true,
- "structuredContent": structured,
- })
+#[cfg(test)]
+mod dispatch_contract_tests {
+ //! The boundary itself is unit-tested in `crate::mcp_result`; these pin
+ //! that `tools/call` dispatch actually routes through it, on the path a
+ //! strict MCP client exercises.
+
+ use super::*;
+ use cua_driver_contract::{advertised_tool_output_schema, TOOL_INVOCATION_FAILED_CODE};
+
+ struct NeverInvokeProvider;
+
+ #[async_trait::async_trait]
+ impl ToolProvider for NeverInvokeProvider {
+ fn tools_list(&self) -> serde_json::Value {
+ serde_json::json!({"tools": [{"name": "get_config"}]})
+ }
+
+ async fn invoke_tool(
+ &self,
+ _name: &str,
+ _arguments: serde_json::Value,
+ ) -> Result<serde_json::Value, String> {
+ panic!("invalid requests must not execute tools")
+ }
+ }
+
+ #[tokio::test]
+ async fn modern_invalid_requests_never_execute_tools() {
+ for (version, capabilities, name, arguments, expected_code) in [
+ (
+ "2026-07-28",
+ serde_json::json!({}),
+ "unknown",
+ serde_json::json!({}),
+ -32602,
+ ),
+ (
+ "2026-07-28",
+ serde_json::json!({}),
+ "get_config",
+ serde_json::json!([]),
+ -32602,
+ ),
+ (
+ "2026-07-28",
+ serde_json::Value::Null,
+ "get_config",
+ serde_json::json!({}),
+ -32602,
+ ),
+ (
+ "unknown",
+ serde_json::json!({}),
+ "get_config",
+ serde_json::json!({}),
+ -32022,
+ ),
+ ] {
+ let req = serde_json::from_value(serde_json::json!({
+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": name, "arguments": arguments, "_meta": {
+ "io.modelcontextprotocol/protocolVersion": version,
+ "io.modelcontextprotocol/clientCapabilities": capabilities
+ }}
+ }))
+ .unwrap();
+ let response = handle_request(req, serde_json::json!(1), &NeverInvokeProvider).await;
+ let wire = serde_json::to_value(response).unwrap();
+ assert_eq!(wire["error"]["code"], expected_code);
+ }
+ }
+
+ struct StubProvider(Result<serde_json::Value, String>);
+
+ #[async_trait::async_trait]
+ impl ToolProvider for StubProvider {
+ fn tools_list(&self) -> serde_json::Value {
+ serde_json::json!({"tools": []})
+ }
+
+ async fn invoke_tool(
+ &self,
+ _name: &str,
+ _arguments: serde_json::Value,
+ ) -> Result<serde_json::Value, String> {
+ self.0.clone()
+ }
+ }
+
+ fn call_request(name: &str) -> Request {
+ serde_json::from_value(serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": name, "arguments": {} }
+ }))
+ .expect("request parses")
+ }
+
+ fn result_of(response: Response) -> serde_json::Value {
+ match response.body {
+ ResponseBody::Result { result } => result,
+ ResponseBody::Error { error } => panic!("expected a result, got {}", error.message),
+ }
+ }
+
+ #[track_caller]
+ fn assert_conforms(tool: &str, structured: &serde_json::Value) {
+ let schema = advertised_tool_output_schema(tool).expect("tool advertises a schema");
+ assert!(
+ jsonschema::validator_for(&schema)
+ .expect("schema compiles")
+ .is_valid(structured),
+ "advertised schema rejected {structured}"
+ );
+ }
+
+ /// Reverting the boundary call fails this with the bug as the message:
+ /// the advertised schema rejects the bare `{"exit_code": 1}` diagnostic.
+ #[tokio::test]
+ async fn an_invocation_failure_is_dispatched_as_a_conforming_refusal() {
+ let provider = StubProvider(Err("daemon transport closed".to_owned()));
+
+ let result =
+ result_of(handle_request(call_request("click"), serde_json::json!(1), &provider).await);
+
+ assert_conforms("click", &result["structuredContent"]);
+ // The diagnostic survives the normalization; only the marker is added.
+ assert_eq!(result["structuredContent"]["exit_code"], 1);
+ assert_eq!(
+ result["structuredContent"]["code"],
+ TOOL_INVOCATION_FAILED_CODE
+ );
+ }
+
+ /// The class of failure the two `exit_code` paths were only one instance
+ /// of: a provider result that is invalid under the advertised schema no
+ /// longer reaches the client as a success.
+ #[tokio::test]
+ async fn a_provider_success_that_violates_the_schema_is_replaced() {
+ let provider = StubProvider(Ok(serde_json::json!({"content": [], "isError": false})));
+
+ let result =
+ result_of(handle_request(call_request("click"), serde_json::json!(1), &provider).await);
+
+ assert_conforms("click", &result["structuredContent"]);
+ assert_eq!(result["isError"], true);
+ assert_eq!(
+ result["structuredContent"]["code"],
+ crate::mcp_result::TOOL_OUTPUT_INVALID_CODE
+ );
+ }
}
#[cfg(test)]
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index b3ea0b6e4d..c69c0a3e2c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -179,26 +179,18 @@ impl ToolDef {
"capabilities": caps,
"risk": risk,
});
- let output_schema = if crate::action_record::is_action_tool(&self.name) {
- Some(
- <cua_driver_contract::ActionResult as cua_driver_contract::ToolOutput>::output_schema(
- ),
- )
- } else {
- cua_driver_contract::tool_success_output_schema(&self.name)
- };
- if let Some(output_schema) = output_schema {
- // Advertise the refusal envelope alongside the success shape. MCP
- // holds every `structuredContent` we emit — refusals included — to
- // the advertised schema, and a success-only schema made strict
- // clients discard our refusal message in favour of a schema error.
+ // Advertise the refusal envelope alongside the success shape. MCP
+ // holds every `structuredContent` we emit — refusals included — to
+ // the advertised schema, and a success-only schema made strict
+ // clients discard our refusal message in favour of a schema error.
+ // The `tools/call` boundary answers from the same lookup, so what a
+ // client is promised and what it is held to cannot drift.
+ if let Some(output_schema) = cua_driver_contract::advertised_tool_output_schema(&self.name)
+ {
entry
.as_object_mut()
.expect("tool list entry is an object")
- .insert(
- "outputSchema".into(),
- cua_driver_contract::advertised_output_schema(output_schema),
- );
+ .insert("outputSchema".into(), output_schema);
}
entry
}
@@ -1601,10 +1593,11 @@ impl ToolRegistry {
if result.is_error != Some(true) && crate::action_record::is_action_tool(resolved_name) {
if let Err(error) = publish_action_result(&mut result) {
result = ToolResult::error(format!(
- "internal action outcome mismatch for {resolved_name}: {error}"
+ "internal action outcome mismatch for {resolved_name}: {error}; the tool may have executed. Verify state before retrying."
))
.with_structured(serde_json::json!({
"code": "action_outcome_mismatch",
+ "execution_state": "unknown",
"tool": resolved_name,
"detail": error,
}));
@@ -1616,10 +1609,11 @@ impl ToolRegistry {
cua_driver_contract::validate_success_output(resolved_name, structured)
{
result = ToolResult::error(format!(
- "internal typed output mismatch for {resolved_name}: {error}"
+ "internal typed output mismatch for {resolved_name}: {error}; the tool may have executed. Verify state before retrying."
))
.with_structured(serde_json::json!({
"code": "typed_output_mismatch",
+ "execution_state": "unknown",
"tool": resolved_name,
"detail": error,
}));
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
index 6b37c06e67..d26e2e64c4 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
@@ -70,6 +70,10 @@ impl ForegroundSentinel {
.args(&electron.args)
.env("CUA_E2E_SENTINEL", "1")
.env("CUA_E2E_SENTINEL_JOURNAL", &journal_path)
+ .env(
+ "CUA_E2E_SENTINEL_CONTROL",
+ journal_path.with_extension("control.json"),
+ )
.env("CUA_E2E_USER_DATA_DIR", user_data.path())
.env("CUA_ELECTRON_CDP_PORT", cdp_port.to_string())
.stdout(Stdio::null())
@@ -119,13 +123,13 @@ impl ForegroundSentinel {
.wait_for_hyprland_sentinel_geometry()
.map_err(|error| error.to_string())?;
}
- try_activate_native_foreground(driver, target)?;
+ activate_and_drain_setup_click(driver, target, &journal_path)?;
// Electron may already be focused before its preload listener is ready.
// The compositor observation is the authoritative Wayland focus gate.
wait_for_native_focus_stable(target);
} else {
wait_for_journal(&journal_path, focus_deadline, r#""kind":"ready""#, "ready");
- try_activate_native_foreground(driver, target)?;
+ activate_and_drain_setup_click(driver, target, &journal_path)?;
wait_for_native_focus_stable(target);
// On macOS the Electron renderer can report `document.hasFocus()`
// as false at DOMContentLoaded, then become natively focused
@@ -288,7 +292,7 @@ impl ForegroundSentinel {
}
}
- activate_native_foreground(driver, self.target);
+ activate_and_drain_setup_click(driver, self.target, &self.journal_path)?;
#[cfg(target_os = "linux")]
set_sway_fullscreen(driver, self.target, true)?;
wait_for_native_focus_stable(self.target);
@@ -334,15 +338,12 @@ impl ForegroundSentinel {
driver: &mut impl Driver,
target: TargetWindow,
) -> Result<(), String> {
- activate_native_foreground(driver, self.target);
+ activate_and_drain_setup_click(driver, self.target, &self.journal_path)?;
wait_for_native_focus_stable(self.target);
std::thread::sleep(Duration::from_millis(100));
reset_journal(&self.journal_path)?;
- // Windows establishes focus with a physical click. Its DOM `click`
- // can arrive after the native focus transition and the first journal
- // reset, falsely attributing setup input to the background action.
- // A later heartbeat is an event-loop barrier: once observed, clear the
- // journal again so the action boundary starts from a quiet sentinel.
+ // This heartbeat checks liveness only. Windows setup input has already
+ // crossed its explicit renderer/main journal barrier before the reset.
wait_for_event(&self.journal_path, "heartbeat", Duration::from_secs(2))?;
reset_journal(&self.journal_path)?;
self.assert_background_posture(target)
@@ -476,9 +477,52 @@ fn is_wayland_session() -> bool {
.is_ok_and(|session| session.eq_ignore_ascii_case("wayland"))
}
-fn activate_native_foreground(driver: &mut impl Driver, target: TargetWindow) {
- try_activate_native_foreground(driver, target)
- .unwrap_or_else(|error| panic!("could not activate foreground sentinel: {error}"));
+fn activate_and_drain_setup_click(
+ driver: &mut impl Driver,
+ target: TargetWindow,
+ _journal_path: &std::path::Path,
+) -> Result<(), String> {
+ #[cfg(target_os = "windows")]
+ let token = {
+ use std::sync::atomic::{AtomicU64, Ordering};
+ static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);
+ let token = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed).to_string();
+ fs::write(
+ _journal_path.with_extension("control.json"),
+ serde_json::json!({ "token": token }).to_string(),
+ )
+ .map_err(|error| format!("arm sentinel setup click: {error}"))?;
+ wait_for_setup_click_marker(_journal_path, "setup-click-armed", &token)?;
+ token
+ };
+ try_activate_native_foreground(driver, target)?;
+ #[cfg(target_os = "windows")]
+ wait_for_setup_click_marker(_journal_path, "setup-click-drained", &token)?;
+ Ok(())
+}
+
+#[cfg(target_os = "windows")]
+fn wait_for_setup_click_marker(
+ path: &std::path::Path,
+ kind: &str,
+ token: &str,
+) -> Result<(), String> {
+ let deadline = Instant::now() + Duration::from_secs(3);
+ loop {
+ let events = read_journal_events(path)?;
+ if events
+ .iter()
+ .any(|event| event_kind(event) == Some(kind) && event["token"].as_str() == Some(token))
+ {
+ return Ok(());
+ }
+ if Instant::now() >= deadline {
+ return Err(format!(
+ "sentinel setup barrier {kind:?} token {token:?} timed out: {events:?}"
+ ));
+ }
+ std::thread::sleep(Duration::from_millis(25));
+ }
}
fn raise_for_focus_canary(driver: &mut impl Driver, target: TargetWindow) -> Result<(), String> {
diff --git a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
index bfcf45650a..8e114a211f 100644
--- a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
@@ -81,6 +81,7 @@ embed-resource = "2"
# response accessors). Dev-only — never linked into the shipped driver.
cua-driver-testkit = { path = "../cua-driver-testkit" }
cua-driver-contract = { path = "../cua-driver-contract" }
+jsonschema = { version = "0.46", default-features = false }
tokio = { workspace = true, features = ["full"] }
image = { workspace = true }
base64 = { workspace = true }
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index 6d59ad90eb..46584ae7b7 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -1726,11 +1726,21 @@ where
on_startup(daemon, true);
}
+ run_mcp_runtime(crate::proxy::run_proxy(socket_path))
+}
+
+pub(crate) fn run_mcp_runtime<T>(future: impl std::future::Future<Output = T>) -> T {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("tokio runtime");
- rt.block_on(crate::proxy::run_proxy(socket_path))
+ let result = rt.block_on(future);
+ // Tokio stdin uses an uncancellable blocking read. After control loss the
+ // MCP client can still hold stdin open; waiting for that read during Drop
+ // would keep the failed proxy process alive and prevent client recovery.
+ // run_proxy has already dropped its scoped daemon control connection.
+ rt.shutdown_background();
+ result
}
/// Emit a stable, machine-readable JSON description of the cua-driver CLI
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
index 61b8fb6d0d..4a61d595a0 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
@@ -138,6 +138,15 @@ async fn serve_conn(
)
.await?;
} else {
+ if let Some(error) =
+ unsupported_protocol_error(&req.body, req.protocol_version.as_deref())
+ {
+ write_http(&mut stream, 400, error.as_bytes(), keep_alive).await?;
+ if !keep_alive {
+ return Ok(());
+ }
+ continue;
+ }
match dispatch(&req.body, &sdk, &transport_session).await {
Some(resp_json) => {
write_http(&mut stream, 200, resp_json.as_bytes(), keep_alive).await?
@@ -163,6 +172,9 @@ async fn dispatch(
sdk: &Arc<crate::sdk_adapter::SdkAdapter>,
transport_session: &str,
) -> Option<String> {
+ if let Some(error) = unsupported_protocol_error(body, None) {
+ return Some(error);
+ }
let mut req: Request = match serde_json::from_slice(body) {
Ok(r) => r,
Err(_) => return Some(serialize(&Response::parse_error())),
@@ -198,6 +210,41 @@ async fn dispatch(
Some(serialize(&response))
}
+fn is_legacy_protocol(version: &str) -> bool {
+ matches!(version, "2024-11-05" | "2025-03-26" | "2025-06-18")
+}
+
+// HTTP still uses connection-scoped sessions. A legacy error permits dual-era
+// clients to fall back to initialize; -32022 would falsely identify a modern
+// endpoint and tell clients to retry per-request version negotiation here.
+fn unsupported_protocol_error(body: &[u8], header: Option<&str>) -> Option<String> {
+ let body: serde_json::Value = serde_json::from_slice(body).unwrap_or_default();
+ let requested = header
+ .filter(|version| !is_legacy_protocol(version))
+ .map(serde_json::Value::from)
+ .or_else(|| {
+ let params = body.get("params")?;
+ params
+ .get("_meta")
+ .and_then(|meta| meta.get("io.modelcontextprotocol/protocolVersion"))
+ .filter(|version| !version.as_str().is_some_and(is_legacy_protocol))
+ .cloned()
+ })
+ .or_else(|| {
+ (body.get("method")?.as_str()? == "server/discover")
+ .then(|| serde_json::Value::from("2026-07-28"))
+ })?;
+ Some(serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": body.get("id").cloned().unwrap_or(serde_json::Value::Null),
+ "error": {
+ "code": -32600,
+ "message": "This HTTP endpoint supports legacy MCP only. Modern MCP is currently available over stdio; use cua-driver mcp or request HTTP protocol version 2025-06-18.",
+ "data": {"supported": ["2025-06-18"], "requested": requested}
+ }
+ }).to_string())
+}
+
fn http_tool_observation_timer(
req: &Request,
is_known_tool: impl Fn(&str) -> bool,
@@ -250,6 +297,7 @@ struct HttpRequest {
/// false if the client sent `Connection: close` or spoke HTTP/1.0).
keep_alive: bool,
authorized: bool,
+ protocol_version: Option<String>,
}
/// Read one HTTP/1.1 request, or `None` on clean EOF. Minimal: request line +
@@ -284,6 +332,7 @@ async fn read_http_request(
let mut has_origin = false;
let mut keep_alive = version.eq_ignore_ascii_case("HTTP/1.1"); // 1.1 defaults to keep-alive
let mut authorized = false;
+ let mut protocol_version = None;
for line in lines {
if let Some((k, v)) = line.split_once(':') {
let (k, v) = (k.trim(), v.trim());
@@ -301,6 +350,11 @@ async fn read_http_request(
authorized = v.split_once(' ').is_some_and(|(scheme, candidate)| {
scheme.eq_ignore_ascii_case("bearer") && constant_time_equal(candidate, token)
});
+ } else if k.eq_ignore_ascii_case("mcp-protocol-version") {
+ // Keep an unsupported value even if a later duplicate is legacy.
+ if protocol_version.as_deref().is_none_or(is_legacy_protocol) {
+ protocol_version = Some(v.to_owned());
+ }
}
}
}
@@ -318,6 +372,7 @@ async fn read_http_request(
has_origin,
keep_alive,
authorized,
+ protocol_version,
}))
}
@@ -370,6 +425,7 @@ async fn write_http(
let reason = match status {
200 => "OK",
202 => "Accepted",
+ 400 => "Bad Request",
403 => "Forbidden",
401 => "Unauthorized",
405 => "Method Not Allowed",
@@ -437,6 +493,126 @@ mod tests {
sdk.shutdown().await.expect("SDK shutdown");
}
+ #[tokio::test]
+ async fn http_rejects_modern_requests_before_dispatch() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
+ let sdk = crate::sdk_adapter::SdkAdapter::load(crate::build_driver_without_cursor())
+ .await
+ .expect("SDK adapter");
+ let tool_call = json!({
+ "jsonrpc": "2.0", "id": 7, "method": "tools/call",
+ "params": {"name": "unknown", "arguments": {}}
+ });
+ let mut modern_tool_call = tool_call.clone();
+ modern_tool_call["params"]["_meta"] = json!({
+ "io.modelcontextprotocol/protocolVersion": "2026-07-28"
+ });
+ let discover = json!({"jsonrpc": "2.0", "id": 7, "method": "server/discover"});
+ for (headers, body, requested) in [
+ (
+ "mCp-PrOtOcOl-VeRsIoN: 2026-07-28\r\n",
+ &tool_call,
+ "2026-07-28",
+ ),
+ ("MCP-Protocol-Version: future\r\n", &tool_call, "future"),
+ ("", &modern_tool_call, "2026-07-28"),
+ ("", &discover, "2026-07-28"),
+ (
+ "MCP-Protocol-Version: 2025-06-18\r\n",
+ &modern_tool_call,
+ "2026-07-28",
+ ),
+ (
+ "MCP-Protocol-Version: future\r\nMCP-Protocol-Version: 2025-06-18\r\n",
+ &tool_call,
+ "future",
+ ),
+ ] {
+ let body = body.to_string();
+ let request = format!(
+ "POST /mcp HTTP/1.1\r\nAuthorization: Bearer 0123456789abcdef0123456789abcdef\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let response = serve_raw_request(sdk.clone(), request.as_bytes()).await;
+ assert!(
+ response.starts_with("HTTP/1.1 400 Bad Request\r\n"),
+ "{response}"
+ );
+ let response: serde_json::Value =
+ serde_json::from_str(response.split_once("\r\n\r\n").unwrap().1).unwrap();
+ assert_eq!(response["id"], 7);
+ assert_eq!(response["error"]["code"], -32600);
+ assert_eq!(
+ response["error"]["data"],
+ json!({
+ "supported": ["2025-06-18"], "requested": requested
+ })
+ );
+ assert!(response["error"]["message"]
+ .as_str()
+ .unwrap()
+ .contains("stdio"));
+ assert!(response.get("result").is_none());
+ }
+ for body in [&modern_tool_call, &discover] {
+ let response = dispatch(body.to_string().as_bytes(), &sdk, "http-test")
+ .await
+ .unwrap();
+ let response: serde_json::Value = serde_json::from_str(&response).unwrap();
+ assert_eq!(response["error"]["code"], -32600);
+ }
+ for (headers, status) in [
+ ("Authorization: Bearer wrong\r\n", "401 Unauthorized"),
+ ("Authorization: Bearer 0123456789abcdef0123456789abcdef\r\nOrigin: https://example.com\r\n", "403 Forbidden"),
+ ] {
+ let body = discover.to_string();
+ let request = format!(
+ "POST /mcp HTTP/1.1\r\n{headers}MCP-Protocol-Version: 2026-07-28\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let response = serve_raw_request(sdk.clone(), request.as_bytes()).await;
+ assert!(response.starts_with(&format!("HTTP/1.1 {status}\r\n")));
+ assert!(!response.contains("Modern MCP is currently available"));
+ }
+ sdk.shutdown().await.expect("SDK shutdown");
+ }
+
+ #[tokio::test]
+ async fn http_keeps_legacy_initialize_negotiation() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
+ let sdk = crate::sdk_adapter::SdkAdapter::load(crate::build_driver_without_cursor())
+ .await
+ .expect("SDK adapter");
+ let body = json!({
+ "jsonrpc": "2.0", "id": 1, "method": "initialize",
+ "params": {"protocolVersion": "2025-11-25", "capabilities": {},
+ "clientInfo": {"name": "legacy-test", "version": "1"}}
+ })
+ .to_string();
+ for version in [
+ None,
+ Some("2024-11-05"),
+ Some("2025-03-26"),
+ Some("2025-06-18"),
+ ] {
+ let header = version
+ .map(|version| format!("MCP-Protocol-Version: {version}\r\n"))
+ .unwrap_or_default();
+ let request = format!(
+ "POST /mcp HTTP/1.1\r\nAuthorization: Bearer 0123456789abcdef0123456789abcdef\r\n{header}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let response = serve_raw_request(sdk.clone(), request.as_bytes()).await;
+ assert!(response.starts_with("HTTP/1.1 200 OK\r\n"), "{response}");
+ let response: serde_json::Value =
+ serde_json::from_str(response.split_once("\r\n\r\n").unwrap().1).unwrap();
+ assert_eq!(response["result"]["protocolVersion"], "2025-06-18");
+ assert!(response["result"].get("protocolVersions").is_none());
+ assert!(response["result"]["capabilities"].get("apps").is_none());
+ }
+ sdk.shutdown().await.expect("SDK shutdown");
+ }
+
#[test]
fn apply_session_identity_mirrors_session_to_session_id() {
let mut req: Request = serde_json::from_value(json!({
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
index 195e63d1c4..401a09b0b9 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -18,6 +18,7 @@
use std::sync::Arc;
+use cua_driver_core::mcp_wire::{self, ProtocolSession};
use cua_driver_core::policy::{authorize_tool_call, validate_configured_policy};
use cua_driver_core::protocol::{initialize_result, Request, Response};
use cua_driver_core::server::{
@@ -27,7 +28,9 @@ use cua_driver_core::server::{
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader};
use tracing::{debug, error, warn};
-use crate::serve::{is_daemon_listening, send_request, DaemonRequest, ToolObservationOrigin};
+use crate::serve::{
+ is_daemon_listening, send_request, DaemonRequest, DaemonResponse, ToolObservationOrigin,
+};
/// Run stdio MCP directly over an SDK-owned runtime.
///
@@ -58,6 +61,7 @@ pub async fn run_direct(driver: Arc<cua_driver_sdk::CuaDriver>) -> anyhow::Resul
let mut writer = tokio::io::BufWriter::new(stdout);
let mut line = String::new();
let mut session_observed = false;
+ let mut protocol_session = ProtocolSession::default();
let transport_session = format!("mcp-{}", uuid::Uuid::new_v4());
struct DirectTransportCleanup {
sdk: Arc<crate::sdk_adapter::SdkAdapter>,
@@ -89,6 +93,25 @@ pub async fn run_direct(driver: Arc<cua_driver_sdk::CuaDriver>) -> anyhow::Resul
}
Ok(request) if request.is_notification() => continue,
Ok(mut request) => {
+ let admission = protocol_session.validate(&request).and_then(|era| {
+ if request.method == "tools/call" {
+ mcp_wire::validate_tool_call(
+ &request,
+ request.id.clone().unwrap_or_default(),
+ era,
+ &sdk.tools_list(),
+ )?;
+ }
+ Ok(era)
+ });
+ if let Err(response) = admission {
+ writer
+ .write_all(serde_json::to_string(&response)?.as_bytes())
+ .await?;
+ writer.write_all(b"\n").await?;
+ writer.flush().await?;
+ continue;
+ }
apply_direct_session_identity(&mut request, &transport_session);
let initialize_metadata = (!session_observed)
.then(|| request.initialize_metadata())
@@ -220,17 +243,15 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
// calls. Besides lifecycle cleanup, that registered control channel is the
// trust boundary used by destructive `browser_prepare` calls.
let (control_ready_tx, control_ready_rx) = tokio::sync::oneshot::channel();
- {
- let socket = socket_path.clone();
- let sid = session_id.clone();
- tokio::spawn(async move {
- run_control_connection(socket, sid, control_ready_tx).await;
- });
- }
- tokio::time::timeout(std::time::Duration::from_secs(4), control_ready_rx)
- .await
- .map_err(|_| anyhow::anyhow!("daemon did not acknowledge the MCP control session"))?
- .map_err(|_| anyhow::anyhow!("daemon control session closed before acknowledgement"))?;
+ let control = run_control_connection(socket_path.clone(), session_id.clone(), control_ready_tx);
+ tokio::pin!(control);
+ supervise_control_connection(&mut control, async {
+ tokio::time::timeout(std::time::Duration::from_secs(4), control_ready_rx)
+ .await
+ .map_err(|_| anyhow::anyhow!("daemon did not acknowledge the MCP control session"))?
+ .map_err(|_| anyhow::anyhow!("daemon control session closed before acknowledgement"))
+ })
+ .await?;
// Cache the tool list once at startup. The daemon's registry is
// static for the lifetime of the daemon, so polling on every
@@ -242,17 +263,34 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();
- run_proxy_io(
- BufReader::new(stdin),
- tokio::io::BufWriter::new(stdout),
- &socket_path,
- &cached_tools_list,
- &session_id,
- daemon_observes_tool_calls,
+ supervise_control_connection(
+ &mut control,
+ run_proxy_io(
+ BufReader::new(stdin),
+ tokio::io::BufWriter::new(stdout),
+ &socket_path,
+ &cached_tools_list,
+ &session_id,
+ daemon_observes_tool_calls,
+ ),
)
.await
}
+/// Keep the MCP transport alive only while its daemon-owned identity is live.
+/// Dropping the scoped control future also closes its socket on stdin EOF,
+/// startup failure, or cancellation; no detached task can retain the session.
+async fn supervise_control_connection<T>(
+ control: impl std::future::Future<Output = ()>,
+ work: impl std::future::Future<Output = anyhow::Result<T>>,
+) -> anyhow::Result<T> {
+ tokio::select! {
+ biased;
+ _ = control => anyhow::bail!("daemon control session closed; reconnect the MCP client"),
+ result = work => result,
+ }
+}
+
/// Run the service-owned stdio loop over caller-provided I/O.
///
/// A clean reader EOF must return `Ok(())` promptly. The caller then drops the
@@ -272,6 +310,7 @@ where
{
let mut line = String::new();
let mut session_observed = false;
+ let mut protocol_session = ProtocolSession::default();
loop {
line.clear();
@@ -295,6 +334,23 @@ where
continue;
}
Ok(req) => {
+ let admission = protocol_session.validate(&req).and_then(|era| {
+ mcp_wire::validate_tool_call(
+ &req,
+ req.id.clone().unwrap_or_default(),
+ era,
+ cached_tools_list,
+ )?;
+ Ok(era)
+ });
+ if let Err(response) = admission {
+ writer
+ .write_all(serde_json::to_string(&response)?.as_bytes())
+ .await?;
+ writer.write_all(b"\n").await?;
+ writer.flush().await?;
+ continue;
+ }
let initialize_metadata = (!session_observed)
.then(|| req.initialize_metadata())
.flatten();
@@ -391,10 +447,9 @@ fn proxy_knows_tool(cached_tools_list: &serde_json::Value, name: &str) -> bool {
/// `session_begin` and fires `session_end` when this connection EOFs — which
/// the kernel triggers on proxy exit AND on kill -9.
///
-/// On any read result/error (daemon-side close, broken pipe), the loop exits
-/// and the task ends; the proxy keeps running on its per-call connections. A
-/// connect failure (racing daemon startup) is logged and swallowed — it must
-/// not bail the proxy.
+/// On EOF/error (daemon-side close, broken pipe), this future completes and
+/// its supervisor closes the MCP proxy. Per-call connections must never keep
+/// serving the ended identity. Startup connection failures follow the same path.
async fn run_control_connection(
socket_path: String,
session_id: String,
@@ -451,6 +506,10 @@ async fn run_control_connection(
match reader.read_line(&mut buf).await {
Ok(0) | Err(_) => return,
Ok(_) => {
+ if let Err(error) = validate_session_begin_ack(&buf) {
+ warn!("control connection: {error}");
+ return;
+ }
let _ = control_ready.send(());
}
}
@@ -498,6 +557,10 @@ async fn run_control_connection(
match reader.read_line(&mut buf).await {
Ok(0) | Err(_) => return,
Ok(_) => {
+ if let Err(error) = validate_session_begin_ack(&buf) {
+ warn!("control connection: {error}");
+ return;
+ }
let _ = control_ready.send(());
}
}
@@ -517,6 +580,21 @@ async fn run_control_connection(
}
}
+fn validate_session_begin_ack(line: &str) -> Result<(), String> {
+ let response: DaemonResponse = serde_json::from_str(line)
+ .map_err(|_| "malformed session_begin acknowledgement".to_owned())?;
+ if !response.ok
+ || response
+ .result
+ .as_ref()
+ .and_then(|result| result.get("session_begin"))
+ != Some(&serde_json::Value::Bool(true))
+ {
+ return Err("daemon did not acknowledge session_begin".to_owned());
+ }
+ Ok(())
+}
+
/// Mint a session id unique among the live proxies sharing one daemon, for the
/// lifetime of this proxy process. `pid + process-start nanos` is dep-free and
/// sufficient: two proxies can't share a pid concurrently, and the nanos guard
@@ -562,6 +640,8 @@ fn fetch_tools_list_from_daemon(
.and_then(|v| v.as_array())
.ok_or_else(|| anyhow::anyhow!("daemon list response missing `tools` array"))?;
+ validate_daemon_output_schemas(tools_array)?;
+
// Reshape the daemon's `{name, description, input_schema, output_schema,
// read_only, ..., capabilities}` envelope into MCP's `{name, description,
// inputSchema, outputSchema, annotations: {...}, capabilities}` shape.
@@ -679,6 +759,48 @@ fn fetch_tools_list_from_daemon(
))
}
+fn validate_daemon_output_schemas(tools: &[serde_json::Value]) -> anyhow::Result<()> {
+ for tool in tools {
+ let name = tool
+ .get("name")
+ .and_then(serde_json::Value::as_str)
+ .ok_or_else(|| anyhow::anyhow!("daemon tool entry missing name"))?;
+ cua_driver_core::mcp_result::validate_proxy_output_schema(name, tool.get("output_schema"))
+ .map_err(anyhow::Error::msg)?;
+ }
+ Ok(())
+}
+
+fn proxy_output_schema<'a>(
+ tools: &'a serde_json::Value,
+ name: &str,
+) -> Option<&'a serde_json::Value> {
+ let tools = tools.get("tools")?.as_array()?;
+ tools
+ .iter()
+ .find(|tool| tool.get("name").and_then(serde_json::Value::as_str) == Some(name))
+ .or_else(|| {
+ (name == "type_text_chars")
+ .then(|| {
+ tools.iter().find(|tool| {
+ tool.get("name").and_then(serde_json::Value::as_str) == Some("type_text")
+ })
+ })
+ .flatten()
+ })?
+ .get("outputSchema")
+}
+
+fn proxy_tool_result_response(
+ id: serde_json::Value,
+ result: Result<serde_json::Value, String>,
+) -> Response {
+ match result {
+ Ok(result) => Response::ok(id, result),
+ Err(error) => Response::error(id, -32603, error),
+ }
+}
+
fn daemon_owns_tool_observation(result: &serde_json::Value) -> bool {
result
.get("tool_observation_owner")
@@ -701,9 +823,45 @@ async fn handle_proxy_request(
cached_tools_list: &Arc<serde_json::Value>,
session_id: &str,
daemon_observes_tool_calls: bool,
+) -> Response {
+ let era = match mcp_wire::classify_request(&req) {
+ Ok(era) => era,
+ Err(response) => return response,
+ };
+ if let Err(response) = mcp_wire::validate_tool_call(&req, id.clone(), era, cached_tools_list) {
+ return response;
+ }
+ let method = req.method.clone();
+ let response = if let Some(response) = mcp_wire::handle_metadata_request(&req, id.clone()) {
+ response
+ } else {
+ handle_proxy_tool_request(
+ req,
+ id,
+ socket_path,
+ cached_tools_list,
+ session_id,
+ daemon_observes_tool_calls,
+ )
+ .await
+ };
+ mcp_wire::finish_response(era, &method, response)
+}
+
+async fn handle_proxy_tool_request(
+ req: Request,
+ id: serde_json::Value,
+ socket_path: &str,
+ cached_tools_list: &Arc<serde_json::Value>,
+ session_id: &str,
+ daemon_observes_tool_calls: bool,
) -> Response {
match req.method.as_str() {
- "initialize" => Response::ok(id, initialize_result()),
+ "initialize"
+ if mcp_wire::classify_request(&req).ok() == Some(mcp_wire::ProtocolEra::Legacy) =>
+ {
+ Response::ok(id, initialize_result())
+ }
"tools/list" => Response::ok(id, (**cached_tools_list).clone()),
@@ -711,15 +869,26 @@ async fn handle_proxy_request(
Err(e) => Response::error(id, -32602, format!("Invalid params: {e}")),
Ok(call) => {
if let Err(error) = authorize_tool_call(&call.name, &call.args) {
- return Response::error(id, -32603, error.to_string());
+ return proxy_tool_result_response(
+ id,
+ cua_driver_core::mcp_result::conforming_proxy_tool_result(
+ &call.name,
+ cua_driver_core::mcp_result::tool_error_result(
+ error.to_string(),
+ serde_json::json!({"code": "permission_denied"}),
+ ),
+ proxy_output_schema(cached_tools_list, &call.name),
+ ),
+ );
}
forward_tool_call(
id,
- call.name,
+ call.name.clone(),
call.args,
socket_path,
session_id,
daemon_observes_tool_calls,
+ proxy_output_schema(cached_tools_list, &call.name).cloned(),
)
.await
}
@@ -751,6 +920,7 @@ async fn forward_tool_call(
socket_path: &str,
session_id: &str,
daemon_observes_tool_calls: bool,
+ output_schema: Option<serde_json::Value>,
) -> Response {
cua_driver_core::tool_args::sanitize_reserved_args(&mut args);
let req = DaemonRequest {
@@ -787,40 +957,55 @@ async fn forward_tool_call(
Ok(Ok(r)) => r,
};
- if !resp.ok {
- // MCP separates two failure modes:
- // - JSON-RPC errors → `Response::error(...)`, used for
- // transport / protocol failures (unknown method, bad
- // params shape, server crash).
- // - Tool-level errors → `Response::ok(...)` carrying a
- // `CallTool.Result` with `isError: true` and the error
- // message in `content[]`. The tool ran, returned a
- // well-formed result that says "I failed."
- //
- // A non-`ok` daemon response means the tool call reached the
- // daemon and the daemon decided the tool returned an error
- // (or rejected the call). That's tool-level, not transport-
- // level, so the core protocol surfaces it as `Response::ok` with
- // `isError: true`. Mirror that shape here — CodeRabbit #2.
+ proxy_tool_result_response(
+ id,
+ daemon_response_to_tool_result(&name, resp, output_schema.as_ref()),
+ )
+}
+
+/// Translate one `DaemonResponse` into the `CallTool.Result` the MCP client
+/// receives.
+///
+/// MCP separates two failure modes:
+/// - JSON-RPC errors → `Response::error(...)`, used for transport /
+/// protocol failures (unknown method, bad params shape, server crash).
+/// Those are handled by the caller, above.
+/// - Tool-level errors → `Response::ok(...)` carrying a `CallTool.Result`
+/// with `isError: true` and the error message in `content[]`. The tool
+/// ran, returned a well-formed result that says "I failed."
+///
+/// A non-`ok` daemon response means the tool call reached the daemon and the
+/// daemon decided the tool returned an error (or rejected the call). That's
+/// tool-level, not transport-level, so the core protocol surfaces it as
+/// `Response::ok` with `isError: true`. Mirror that shape here — CodeRabbit #2.
+///
+/// Every branch — including the empty result synthesised for an `ok` response
+/// that carries none — leaves through the same boundary the direct dispatch
+/// uses, so a daemon-backed call is held to the tool's advertised
+/// `outputSchema` exactly as a direct one is.
+fn daemon_response_to_tool_result(
+ name: &str,
+ resp: DaemonResponse,
+ output_schema: Option<&serde_json::Value>,
+) -> Result<serde_json::Value, String> {
+ let result = if resp.ok {
+ resp.result.unwrap_or_else(|| {
+ serde_json::json!({
+ "content": [],
+ "isError": false
+ })
+ })
+ } else {
let msg = resp
.error
.unwrap_or_else(|| "daemon reported failure".into());
let exit_code = resp.exit_code.unwrap_or(1);
- let result = serde_json::json!({
- "content": [{ "type": "text", "text": msg }],
- "isError": true,
- "structuredContent": { "exit_code": exit_code }
- });
- return Response::ok(id, result);
- }
-
- let result = resp.result.unwrap_or_else(|| {
- serde_json::json!({
- "content": [],
- "isError": false
- })
- });
- Response::ok(id, result)
+ cua_driver_core::mcp_result::tool_error_result(
+ msg,
+ serde_json::json!({ "exit_code": exit_code }),
+ )
+ };
+ cua_driver_core::mcp_result::conforming_proxy_tool_result(name, result, output_schema)
}
// ── Tests ────────────────────────────────────────────────────────────────────
@@ -832,7 +1017,274 @@ async fn forward_tool_call(
#[cfg(test)]
mod tests {
use super::*;
- use crate::serve::DaemonResponse;
+
+ #[tokio::test]
+ async fn modern_proxy_metadata_and_rejections_need_no_daemon_call() {
+ use serde_json::json;
+ let meta = json!({
+ mcp_wire::PROTOCOL_VERSION_KEY: mcp_wire::MODERN_PROTOCOL_VERSION,
+ mcp_wire::CLIENT_CAPABILITIES_KEY: {}
+ });
+ let mut input = Vec::new();
+ for (id, method, mut params) in [
+ (1, "server/discover", json!({})),
+ (2, "skills/list", json!({})),
+ (
+ 3,
+ "resources/read",
+ json!({"uri":"skill://cua-driver/SKILL.md"}),
+ ),
+ (4, "tools/call", json!({"name":"get_config","arguments":[]})),
+ (
+ 5,
+ "tools/call",
+ json!({"name":"unknown_tool","arguments":{"session":"must-not-start"}}),
+ ),
+ ] {
+ params["_meta"] = meta.clone();
+ serde_json::to_writer(
+ &mut input,
+ &json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}),
+ )
+ .unwrap();
+ input.push(b'\n');
+ }
+ let inventory = Arc::new(json!({"tools":[{"name":"get_config"}]}));
+ let mut output = Vec::new();
+ run_proxy_io(
+ BufReader::new(input.as_slice()),
+ &mut output,
+ "unreachable-test-endpoint",
+ &inventory,
+ "modern-test",
+ false,
+ )
+ .await
+ .unwrap();
+ let replies: Vec<serde_json::Value> = String::from_utf8(output)
+ .unwrap()
+ .lines()
+ .map(|line| serde_json::from_str(line).unwrap())
+ .collect();
+ assert_eq!(replies.len(), 5);
+ assert_eq!(
+ replies[0]["result"]["supportedVersions"],
+ json!(["2026-07-28"])
+ );
+ assert_eq!(
+ replies[1]["result"]["skills"][0]["uri"],
+ "skill://cua-driver/SKILL.md"
+ );
+ assert!(replies[2]["result"]["contents"][0]["text"]
+ .as_str()
+ .unwrap()
+ .starts_with("---"));
+ for reply in &replies[..3] {
+ assert_eq!(reply["result"]["resultType"], "complete");
+ assert_eq!(reply["result"]["cacheScope"], "private");
+ }
+ for reply in &replies[3..] {
+ assert_eq!(reply["error"]["code"], -32602);
+ }
+ }
+
+ #[tokio::test]
+ async fn proxy_authorization_refusal_is_a_tool_error_without_forwarding() {
+ const CHILD_ENV: &str = "CUA_DRIVER_PROXY_REFUSAL_TEST_CHILD";
+ if std::env::var_os(CHILD_ENV).is_none() {
+ // Policy configuration is process-wide and immutable; keep this
+ // denial out of other tests without mutating the parent environment.
+ let directory = tempfile::tempdir().expect("temporary policy directory");
+ let policy = directory.path().join("deny.yaml");
+ std::fs::write(&policy, "deny:\n tools: [click]\n").expect("write policy");
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "proxy::tests::proxy_authorization_refusal_is_a_tool_error_without_forwarding",
+ "--nocapture",
+ ])
+ .env(CHILD_ENV, "1")
+ .env(cua_driver_core::policy::POLICY_FILE_ENV, &policy)
+ .env_remove(cua_driver_core::policy::MANAGED_POLICY_FILE_ENV)
+ .output()
+ .expect("run isolated refusal test");
+ assert!(
+ output.status.success(),
+ "isolated refusal test failed: {}{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ return;
+ }
+
+ let directory = tempfile::tempdir().expect("temporary socket directory");
+ let socket = directory.path().join("daemon.sock");
+ #[cfg(unix)]
+ let listener = tokio::net::UnixListener::bind(&socket).expect("bind test daemon");
+ let request = serde_json::from_value(serde_json::json!({
+ "jsonrpc": "2.0", "id": 19, "method": "tools/call",
+ "params": {"name": "click", "arguments": {"pid": 42, "x": 10, "y": 20}}
+ }))
+ .expect("valid tool request");
+ let cached_tools = Arc::new(serde_json::json!({"tools": [{"name": "click"}]}));
+ let response = handle_proxy_request(
+ request,
+ serde_json::json!(19),
+ socket.to_str().unwrap(),
+ &cached_tools,
+ "refusal-test-session",
+ false,
+ );
+ #[cfg(unix)]
+ let response = tokio::select! {
+ response = response => response,
+ connection = listener.accept() => {
+ drop(connection);
+ panic!("a locally denied call must never connect to the daemon");
+ }
+ };
+ #[cfg(not(unix))]
+ let response = response.await;
+ let value = serde_json::to_value(response).expect("serialize response");
+ assert_eq!(value["id"], 19);
+ assert!(value.get("error").is_none(), "{value}");
+ let result = &value["result"];
+ assert_eq!(result["isError"], true);
+ assert_eq!(result["structuredContent"]["code"], "permission_denied");
+ assert_eq!(result["content"][0]["type"], "text");
+ assert!(result["content"][0]["text"]
+ .as_str()
+ .unwrap()
+ .contains("explicitly denied"));
+ }
+
+ #[test]
+ fn control_disconnect_exits_with_stdin_open() {
+ const CHILD_ENV: &str = "CUA_TEST_MCP_CONTROL_STDIN_CHILD";
+ if std::env::var_os(CHILD_ENV).is_some() {
+ let result = crate::cli::run_mcp_runtime(async {
+ let cached_tools = Arc::new(serde_json::json!({"tools": []}));
+ supervise_control_connection(
+ // Let run_proxy_io park in the real blocking stdin read.
+ tokio::time::sleep(std::time::Duration::from_millis(100)),
+ run_proxy_io(
+ BufReader::new(tokio::io::stdin()),
+ tokio::io::sink(),
+ "unused.sock",
+ &cached_tools,
+ "disconnect",
+ false,
+ ),
+ )
+ .await
+ });
+ assert!(result.is_err());
+ return;
+ }
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "proxy::tests::control_disconnect_exits_with_stdin_open",
+ "--nocapture",
+ ])
+ .env(CHILD_ENV, "1")
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .unwrap();
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ loop {
+ if let Some(status) = child.try_wait().unwrap() {
+ assert!(
+ status.success(),
+ "MCP runtime subprocess failed: {:?}",
+ child.wait_with_output().unwrap()
+ );
+ break;
+ }
+ if std::time::Instant::now() >= deadline {
+ child.kill().unwrap();
+ child.wait().unwrap();
+ panic!("control disconnect left the MCP process waiting for client stdin EOF");
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ }
+
+ #[tokio::test]
+ async fn control_disconnect_ends_idle_proxy() {
+ let (control, daemon) = tokio::io::duplex(64);
+ let control = async move {
+ let mut reader = BufReader::new(control);
+ let mut line = String::new();
+ let _ = reader.read_line(&mut line).await;
+ };
+ let proxy =
+ supervise_control_connection(control, std::future::pending::<anyhow::Result<()>>());
+ tokio::pin!(proxy);
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(25), &mut proxy)
+ .await
+ .is_err(),
+ "an idle live control connection must remain usable"
+ );
+ drop(daemon);
+ let error = tokio::time::timeout(std::time::Duration::from_millis(250), proxy)
+ .await
+ .expect("control EOF must end the proxy promptly")
+ .unwrap_err();
+ assert!(error.to_string().contains("reconnect the MCP client"));
+ }
+
+ #[tokio::test]
+ async fn proxy_eof_drops_its_control_connection() {
+ let (control, daemon) = tokio::io::duplex(64);
+ let control = async move {
+ let mut reader = BufReader::new(control);
+ let mut line = String::new();
+ let _ = reader.read_line(&mut line).await;
+ };
+ let cached_tools = Arc::new(serde_json::json!({"tools": []}));
+ let mut writer = Vec::new();
+ supervise_control_connection(
+ control,
+ run_proxy_io(
+ BufReader::new(&b""[..]),
+ &mut writer,
+ "unused.sock",
+ &cached_tools,
+ "eof",
+ false,
+ ),
+ )
+ .await
+ .unwrap();
+ let mut daemon = BufReader::new(daemon);
+ let mut line = String::new();
+ assert_eq!(
+ tokio::time::timeout(
+ std::time::Duration::from_millis(250),
+ daemon.read_line(&mut line)
+ )
+ .await
+ .expect("proxy EOF must release daemon session ownership")
+ .unwrap(),
+ 0
+ );
+ }
+
+ #[tokio::test]
+ async fn closed_control_prevents_ready_request_dispatch() {
+ let dispatched = std::sync::atomic::AtomicBool::new(false);
+ let result = supervise_control_connection(async {}, async {
+ dispatched.store(true, std::sync::atomic::Ordering::SeqCst);
+ Ok(())
+ })
+ .await;
+ assert!(result.is_err());
+ assert!(!dispatched.load(std::sync::atomic::Ordering::SeqCst));
+ }
#[tokio::test]
async fn proxy_loop_returns_promptly_on_clean_eof() {
@@ -889,20 +1341,94 @@ mod tests {
assert!(response.get("result").is_some());
}
- /// Reconstruct the `!resp.ok` branch in isolation so we can assert
- /// on the serialized shape without spinning up a real daemon /
- /// tokio runtime. Keep this in sync with `forward_tool_call`.
- fn build_tool_error_response(id: serde_json::Value, resp: DaemonResponse) -> Response {
- let msg = resp
- .error
- .unwrap_or_else(|| "daemon reported failure".into());
- let exit_code = resp.exit_code.unwrap_or(1);
- let result = serde_json::json!({
- "content": [{ "type": "text", "text": msg }],
- "isError": true,
- "structuredContent": { "exit_code": exit_code }
- });
- Response::ok(id, result)
+ #[test]
+ fn session_begin_requires_a_positive_typed_acknowledgement() {
+ assert!(
+ validate_session_begin_ack(r#"{"ok":true,"result":{"session_begin":true}}"#).is_ok()
+ );
+ for line in [
+ "not JSON",
+ r#"{"ok":false,"error":"denied"}"#,
+ r#"{"ok":false,"result":{"session_begin":true}}"#,
+ r#"{"ok":true}"#,
+ r#"{"ok":true,"result":{"session_begin":false}}"#,
+ r#"{"ok":true,"result":{"session_begin":"true"}}"#,
+ r#"{"ok":true,"result":{"other":true}}"#,
+ ] {
+ assert!(validate_session_begin_ack(line).is_err(), "accepted {line}");
+ }
+ }
+
+ #[test]
+ fn incompatible_daemon_schema_is_rejected_before_advertising() {
+ let schema = serde_json::json!({"type": "object", "required": ["legacy_clicked"]});
+ let tools = vec![serde_json::json!({"name": "click", "output_schema": schema})];
+ let error = validate_daemon_output_schemas(&tools)
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("incompatible daemon output schema for click"));
+ assert!(error.contains("matching proxy and daemon versions"));
+
+ let daemon_resp = DaemonResponse {
+ ok: true,
+ result: Some(serde_json::json!({
+ "content": [], "structuredContent": {"legacy_clicked": true}
+ })),
+ error: None,
+ exit_code: None,
+ };
+ let response = proxy_tool_result_response(
+ serde_json::json!(1),
+ daemon_response_to_tool_result("click", daemon_resp, Some(&schema)),
+ );
+ let response = serde_json::to_value(response).unwrap();
+ assert_eq!(response["error"]["code"], -32603);
+ assert!(response.get("result").is_none());
+ }
+
+ #[test]
+ fn daemon_without_schema_preserves_legacy_success() {
+ let tools = vec![serde_json::json!({"name": "click"})];
+ validate_daemon_output_schemas(&tools).unwrap();
+ for result in [
+ serde_json::json!({"content": [], "isError": false}),
+ serde_json::json!({
+ "content": [], "isError": false,
+ "structuredContent": {"legacy_clicked": true}
+ }),
+ ] {
+ let daemon_resp = DaemonResponse {
+ ok: true,
+ result: Some(result.clone()),
+ error: None,
+ exit_code: None,
+ };
+ assert_eq!(
+ daemon_response_to_tool_result("click", daemon_resp, None).unwrap(),
+ result
+ );
+ }
+ }
+
+ #[test]
+ fn matching_daemon_schema_retains_local_output_validation() {
+ let tools =
+ vec![serde_json::json!({"name": "click", "output_schema": click_output_schema()})];
+ validate_daemon_output_schemas(&tools).unwrap();
+ }
+
+ fn click_output_schema() -> Option<serde_json::Value> {
+ cua_driver_contract::advertised_tool_output_schema("click")
+ }
+
+ /// Serialize the production conversion the way the proxy answers it, so
+ /// these assertions run against `forward_tool_call`'s own branch without
+ /// spinning up a real daemon.
+ fn tool_call_response(id: serde_json::Value, resp: DaemonResponse) -> Response {
+ Response::ok(
+ id,
+ daemon_response_to_tool_result("click", resp, click_output_schema().as_ref()).unwrap(),
+ )
}
#[test]
@@ -913,7 +1439,7 @@ mod tests {
error: Some("missing required field `pid`".into()),
exit_code: Some(64),
};
- let resp = build_tool_error_response(serde_json::json!(7), daemon_resp);
+ let resp = tool_call_response(serde_json::json!(7), daemon_resp);
let value = serde_json::to_value(&resp).expect("serialize");
// Top-level JSON-RPC envelope: success (`result`), not error.
@@ -934,6 +1460,13 @@ mod tests {
assert_eq!(result["content"][0]["type"], "text");
assert_eq!(result["content"][0]["text"], "missing required field `pid`");
assert_eq!(result["structuredContent"]["exit_code"], 64);
+ // Strict MCP clients validate this payload against the tool's
+ // advertised `outputSchema`. The refusal marker is what keeps the
+ // response readable instead of being discarded as `-32602`.
+ assert_eq!(
+ result["structuredContent"]["code"],
+ cua_driver_core::TOOL_INVOCATION_FAILED_CODE
+ );
}
#[test]
@@ -944,7 +1477,7 @@ mod tests {
error: None,
exit_code: None,
};
- let resp = build_tool_error_response(serde_json::json!("abc"), daemon_resp);
+ let resp = tool_call_response(serde_json::json!("abc"), daemon_resp);
let value = serde_json::to_value(&resp).expect("serialize");
assert_eq!(value["result"]["isError"], serde_json::json!(true));
assert_eq!(
@@ -952,6 +1485,61 @@ mod tests {
"daemon reported failure"
);
assert_eq!(value["result"]["structuredContent"]["exit_code"], 1);
+ assert_eq!(
+ value["result"]["structuredContent"]["code"],
+ cua_driver_core::TOOL_INVOCATION_FAILED_CODE
+ );
+ }
+
+ /// An `ok` daemon response that carries no result used to be forwarded as
+ /// an empty success. For a tool that declares an `outputSchema` that is a
+ /// response a strict client rejects outright (`-32600`), so the boundary
+ /// converts it into an error the client can actually read.
+ #[test]
+ fn an_ok_daemon_response_with_no_result_becomes_a_conforming_error() {
+ let daemon_resp = DaemonResponse {
+ ok: true,
+ result: None,
+ error: None,
+ exit_code: None,
+ };
+
+ let result =
+ daemon_response_to_tool_result("click", daemon_resp, click_output_schema().as_ref())
+ .unwrap();
+
+ assert_eq!(result["isError"], serde_json::json!(true));
+ assert_eq!(
+ result["structuredContent"]["code"],
+ cua_driver_core::mcp_result::TOOL_OUTPUT_INVALID_CODE
+ );
+ }
+
+ /// A daemon result that already conforms is forwarded untouched.
+ #[test]
+ fn a_conforming_daemon_success_is_forwarded_unchanged() {
+ let result = serde_json::json!({
+ "content": [{ "type": "text", "text": "clicked" }],
+ "isError": false,
+ "structuredContent": {
+ "effect": "confirmed",
+ "route": "accessibility",
+ "delivery": { "mode": "background" },
+ "evidence": [{ "kind": "value_readback" }],
+ },
+ });
+ let daemon_resp = DaemonResponse {
+ ok: true,
+ result: Some(result.clone()),
+ error: None,
+ exit_code: None,
+ };
+
+ assert_eq!(
+ daemon_response_to_tool_result("click", daemon_resp, click_output_schema().as_ref())
+ .unwrap(),
+ result
+ );
}
#[test]
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_proxy_recovery_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_proxy_recovery_test.rs
new file mode 100644
index 0000000000..326b407062
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_proxy_recovery_test.rs
@@ -0,0 +1,432 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Real stdio proxies and a real daemon, with selective control-channel loss.
+//! Set CUA_PROXY_RECOVERY_IDLE_SECONDS=1200 for a long-idle diagnostic replay.
+//! This injects a known transport failure; it does not reproduce an unknown trigger.
+
+#![cfg(any(unix, target_os = "windows"))]
+
+use cua_driver_testkit::spawn_in_job;
+use serde_json::{json, Value};
+use std::io::{BufRead, Write};
+use std::process::{Child, ChildStdin, Command, Stdio};
+use std::sync::mpsc::{self, Receiver};
+use std::time::{Duration, Instant};
+use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
+use tokio::sync::{mpsc as async_mpsc, oneshot};
+
+const BOUND: Duration = Duration::from_secs(10);
+
+trait Stream: AsyncRead + AsyncWrite + Unpin + Send {}
+impl<T: AsyncRead + AsyncWrite + Unpin + Send> Stream for T {}
+type Connection = Box<dyn Stream>;
+
+async fn copy_until_disconnect<A: Stream, B: Stream>(incoming: &mut A, upstream: &mut B) {
+ let (mut client_read, mut client_write) = tokio::io::split(incoming);
+ let (mut daemon_read, mut daemon_write) = tokio::io::split(upstream);
+ // Named pipes cannot half-close: AsyncWrite::shutdown only flushes. Drop
+ // both handles on either EOF so the relay preserves peer-disconnect semantics.
+ tokio::select! {
+ _ = tokio::io::copy(&mut client_read, &mut daemon_write) => {},
+ _ = tokio::io::copy(&mut daemon_read, &mut client_write) => {},
+ }
+}
+
+async fn connect(endpoint: &str) -> std::io::Result<Connection> {
+ #[cfg(unix)]
+ return Ok(Box::new(tokio::net::UnixStream::connect(endpoint).await?));
+ #[cfg(target_os = "windows")]
+ {
+ let deadline = Instant::now() + BOUND;
+ loop {
+ match tokio::net::windows::named_pipe::ClientOptions::new().open(endpoint) {
+ Ok(pipe) => return Ok(Box::new(pipe)),
+ Err(error) if Instant::now() >= deadline => return Err(error),
+ Err(_) => tokio::time::sleep(Duration::from_millis(20)).await,
+ }
+ }
+ }
+}
+
+// Forward the handshake and all responses unchanged. Only a session_begin
+// connection can be cut; per-call connections and the daemon stay alive.
+async fn forward(
+ incoming: Connection,
+ daemon: String,
+ controls: async_mpsc::UnboundedSender<oneshot::Sender<()>>,
+) {
+ let mut incoming = BufReader::new(incoming);
+ let mut first = String::new();
+ if !matches!(tokio::time::timeout(BOUND, incoming.read_line(&mut first)).await, Ok(Ok(n)) if n > 0)
+ {
+ return;
+ }
+ let request: Value = serde_json::from_str(&first).expect("relay request JSON");
+ let mut upstream = connect(&daemon)
+ .await
+ .expect("connect relay to real daemon");
+ upstream.write_all(first.as_bytes()).await.unwrap();
+ if request["method"] == "session_begin" {
+ let (cut, cut_rx) = oneshot::channel();
+ controls.send(cut).unwrap();
+ tokio::select! {
+ _ = cut_rx => {},
+ _ = copy_until_disconnect(&mut incoming, &mut upstream) => {},
+ }
+ } else {
+ copy_until_disconnect(&mut incoming, &mut upstream).await;
+ }
+}
+
+async fn relay(
+ endpoint: &str,
+ daemon: String,
+ controls: async_mpsc::UnboundedSender<oneshot::Sender<()>>,
+) -> tokio::task::JoinHandle<()> {
+ #[cfg(unix)]
+ {
+ let listener = tokio::net::UnixListener::bind(endpoint).unwrap();
+ tokio::spawn(async move {
+ loop {
+ let (stream, _) = listener.accept().await.unwrap();
+ tokio::spawn(forward(Box::new(stream), daemon.clone(), controls.clone()));
+ }
+ })
+ }
+ #[cfg(target_os = "windows")]
+ {
+ use tokio::net::windows::named_pipe::ServerOptions;
+ let mut listener = ServerOptions::new()
+ .first_pipe_instance(true)
+ .create(endpoint)
+ .unwrap();
+ let endpoint = endpoint.to_owned();
+ tokio::spawn(async move {
+ loop {
+ listener.connect().await.unwrap();
+ let next = ServerOptions::new().create(&endpoint).unwrap();
+ let stream = std::mem::replace(&mut listener, next);
+ tokio::spawn(forward(Box::new(stream), daemon.clone(), controls.clone()));
+ }
+ })
+ }
+}
+
+struct Process(Child, #[allow(dead_code)] tempfile::TempDir);
+
+impl Process {
+ fn spawn(args: &[&str]) -> Self {
+ let driver_home = tempfile::tempdir().expect("isolated driver state");
+ let idle_seconds = recovery_idle_seconds();
+ let mut command = Command::new(env!("CARGO_BIN_EXE_cua-driver"));
+ command
+ .args(args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::inherit())
+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")
+ // This test isolates transport lifetime from intentional session expiry.
+ .env(
+ "CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS",
+ (idle_seconds + 60).max(300).to_string(),
+ )
+ .env("HOME", driver_home.path())
+ .env("USERPROFILE", driver_home.path())
+ .env("LOCALAPPDATA", driver_home.path())
+ .env("XDG_STATE_HOME", driver_home.path())
+ .env("CUA_DRIVER_HOME", driver_home.path())
+ .env("CUA_DRIVER_LOCAL_HOME", driver_home.path())
+ .env("CUA_DRIVER_RS_HOME", driver_home.path());
+ Self(
+ spawn_in_job(&mut command).expect("spawn source-built driver"),
+ driver_home,
+ )
+ }
+
+ fn exit(&mut self) -> std::process::ExitStatus {
+ let deadline = Instant::now() + BOUND;
+ loop {
+ if let Some(status) = self.0.try_wait().unwrap() {
+ return status;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "driver process did not exit within {BOUND:?}"
+ );
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
+}
+
+fn recovery_idle_seconds() -> u64 {
+ let seconds = std::env::var("CUA_PROXY_RECOVERY_IDLE_SECONDS")
+ .map(|value| {
+ value
+ .parse::<u64>()
+ .expect("idle seconds must be an integer")
+ })
+ .unwrap_or(1);
+ assert!(
+ (1..=3600).contains(&seconds),
+ "idle seconds must be 1..=3600"
+ );
+ seconds
+}
+
+impl Drop for Process {
+ fn drop(&mut self) {
+ let _ = self.0.kill();
+ let _ = self.0.wait();
+ }
+}
+
+struct Client {
+ process: Process,
+ stdin: Option<ChildStdin>,
+ responses: Receiver<Value>,
+ id: u64,
+}
+
+impl Client {
+ fn spawn(endpoint: &str) -> Self {
+ let mut process = Process::spawn(&["mcp", "--socket", endpoint]);
+ let stdin = process.0.stdin.take();
+ let stdout = process.0.stdout.take().unwrap();
+ let (tx, responses) = mpsc::channel();
+ std::thread::spawn(move || {
+ for line in std::io::BufReader::new(stdout).lines() {
+ let response =
+ serde_json::from_str(&line.expect("read MCP stdout")).expect("MCP JSON");
+ if tx.send(response).is_err() {
+ break;
+ }
+ }
+ });
+ let mut client = Self {
+ process,
+ stdin,
+ responses,
+ id: 0,
+ };
+ let response = client.request(
+ "initialize",
+ json!({
+ "protocolVersion":"2024-11-05", "capabilities":{},
+ "clientInfo":{"name":"proxy-recovery-test","version":"1"}
+ }),
+ );
+ assert!(response["result"]["serverInfo"].is_object(), "{response}");
+ writeln!(
+ client.stdin.as_mut().unwrap(),
+ "{}",
+ json!({"jsonrpc":"2.0","method":"notifications/initialized"})
+ )
+ .unwrap();
+ client
+ }
+
+ fn request(&mut self, method: &str, params: Value) -> Value {
+ self.id += 1;
+ writeln!(
+ self.stdin.as_mut().unwrap(),
+ "{}",
+ json!({
+ "jsonrpc":"2.0", "id":self.id, "method":method, "params":params
+ })
+ )
+ .unwrap();
+ let deadline = Instant::now() + BOUND;
+ loop {
+ let response = self
+ .responses
+ .recv_timeout(deadline.saturating_duration_since(Instant::now()))
+ .expect("bounded MCP response");
+ if response["id"] == self.id {
+ assert!(response.get("error").is_none(), "{response}");
+ return response;
+ }
+ }
+ }
+
+ fn call(&mut self, name: &str, arguments: Value) {
+ let inventory = self.request("tools/list", json!({}));
+ let schema = inventory["result"]["tools"]
+ .as_array()
+ .expect("advertised tools")
+ .iter()
+ .find(|tool| tool["name"] == name)
+ .and_then(|tool| tool.get("outputSchema"));
+ if name == "get_session_state" {
+ assert!(schema.is_some(), "session state must advertise a schema");
+ }
+ let response = self.request("tools/call", json!({"name":name,"arguments":arguments}));
+ assert_ne!(response["result"]["isError"], true, "{response}");
+ assert!(response["result"]["content"].is_array(), "{response}");
+ if let Some(schema) = schema {
+ let structured = response["result"]
+ .get("structuredContent")
+ .expect("schema-bearing success must contain structured output");
+ assert!(jsonschema::is_valid(schema, structured), "{response}");
+ }
+ }
+
+ fn eof(&self) {
+ assert!(
+ matches!(
+ self.responses.recv_timeout(BOUND),
+ Err(mpsc::RecvTimeoutError::Disconnected)
+ ),
+ "MCP stdout must close promptly without additional responses"
+ );
+ }
+}
+
+async fn daemon_request(endpoint: &str, request: Value) -> Value {
+ tokio::time::timeout(BOUND, async {
+ let mut stream = connect(endpoint).await.unwrap();
+ stream
+ .write_all(format!("{request}\n").as_bytes())
+ .await
+ .unwrap();
+ let mut line = String::new();
+ BufReader::new(stream).read_line(&mut line).await.unwrap();
+ let response: Value = serde_json::from_str(&line).unwrap();
+ assert_eq!(response["ok"], true, "{response}");
+ response["result"].clone()
+ })
+ .await
+ .expect("bounded daemon request")
+}
+
+async fn session_absent(endpoint: &str, label: &str) {
+ let deadline = Instant::now() + BOUND;
+ loop {
+ let result = daemon_request(endpoint, json!({"method":"sessions_list"})).await;
+ let sessions = result["sessions"]
+ .as_array()
+ .expect("operator sessions array");
+ if !sessions.iter().any(|session| session["session"] == label) {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "session {label} was not cleaned up: {result}"
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+}
+
+async fn session_active(endpoint: &str, label: &str) {
+ let result = daemon_request(endpoint, json!({"method":"sessions_list"})).await;
+ assert!(
+ result["sessions"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|session| session["session"] == label && session["state"] == "active"),
+ "expected active session {label}: {result}"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn real_proxies_recover_from_control_loss_without_waiting_for_stdin() {
+ #[cfg(unix)]
+ let directory = tempfile::Builder::new()
+ .prefix("cua-recovery-")
+ .tempdir_in("/tmp")
+ .unwrap();
+ #[cfg(unix)]
+ let (daemon_endpoint, proxy_endpoint) = (
+ directory.path().join("d.sock").display().to_string(),
+ directory.path().join("p.sock").display().to_string(),
+ );
+ #[cfg(target_os = "windows")]
+ let (daemon_endpoint, proxy_endpoint) = (
+ format!(r"\\.\pipe\cua-recovery-{}-daemon", std::process::id()),
+ format!(r"\\.\pipe\cua-recovery-{}-proxy", std::process::id()),
+ );
+ let mut daemon = Process::spawn(&[
+ "serve",
+ "--socket",
+ &daemon_endpoint,
+ "--no-overlay",
+ "--no-permissions-gate",
+ "--dangerously-bypass-approvals",
+ ]);
+ let deadline = Instant::now() + BOUND;
+ loop {
+ assert!(
+ daemon.0.try_wait().unwrap().is_none(),
+ "daemon exited during startup"
+ );
+ if connect(&daemon_endpoint).await.is_ok() {
+ break;
+ }
+ assert!(Instant::now() < deadline, "daemon readiness timeout");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ let (control_tx, mut controls) = async_mpsc::unbounded_channel();
+ let relay_task = relay(&proxy_endpoint, daemon_endpoint.clone(), control_tx).await;
+ let mut idle = Client::spawn(&proxy_endpoint);
+ let idle_control = tokio::time::timeout(BOUND, controls.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ idle.call("start_session", json!({"session":"idle-client"}));
+ let mut peer = Client::spawn(&proxy_endpoint);
+ let _peer_control = tokio::time::timeout(BOUND, controls.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ peer.call("start_session", json!({"session":"peer-client"}));
+ session_active(&daemon_endpoint, "peer-client").await;
+ session_active(&daemon_endpoint, "idle-client").await;
+
+ let idle_seconds = recovery_idle_seconds();
+ tokio::time::sleep(Duration::from_secs(idle_seconds)).await;
+ drop(peer.stdin.take());
+ assert!(
+ peer.process.exit().success(),
+ "peer stdin EOF should exit successfully"
+ );
+ peer.eof();
+ session_absent(&daemon_endpoint, "peer-client").await;
+ session_active(&daemon_endpoint, "idle-client").await;
+ idle.call("get_config", json!({"session":"idle-client"}));
+ idle.call("get_session_state", json!({"session":"idle-client"}));
+
+ let mut survivor = Client::spawn(&proxy_endpoint);
+ let _survivor_control = tokio::time::timeout(BOUND, controls.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ survivor.call("start_session", json!({"session":"survivor"}));
+ idle_control
+ .send(())
+ .expect("idle control must still be connected");
+ assert!(idle.stdin.is_some(), "retain stdin during control loss");
+ assert!(
+ !idle.process.exit().success(),
+ "lost control must fail the proxy"
+ );
+ idle.eof();
+ session_absent(&daemon_endpoint, "idle-client").await;
+ session_active(&daemon_endpoint, "survivor").await;
+ survivor.call("get_config", json!({"session":"survivor"}));
+ assert!(
+ daemon.0.try_wait().unwrap().is_none(),
+ "daemon must survive selective loss"
+ );
+
+ let mut fresh = Client::spawn(&proxy_endpoint);
+ let _fresh_control = tokio::time::timeout(BOUND, controls.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ fresh.call("get_config", json!({}));
+ fresh.call("start_session", json!({"session":"fresh-client"}));
+ fresh.call("get_session_state", json!({"session":"fresh-client"}));
+ survivor.call("get_config", json!({"session":"survivor"}));
+ relay_task.abort();
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
index 1399c59198..77653ba961 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
@@ -78,8 +78,15 @@ fn policies_are_isolated_immutable_and_enforced_over_mcp() {
"get_screen_size",
json!({"session": "scope-desktop"}),
);
+ // Every error result now carries a refusal marker, so "no code at all" no
+ // longer distinguishes a permitted call from one that failed for an
+ // unrelated environment reason (a runner with no display, say). Assert
+ // what this test is actually about: the scope policy did not refuse it.
assert!(
- code(&desktop_screen_size).is_none(),
+ !matches!(
+ code(&desktop_screen_size),
+ Some("desktop_scope_disabled" | "desktop_escalation_required")
+ ),
"desktop scope should permit global screen geometry: {desktop_screen_size}"
);
diff --git a/libs/cua-driver/scripts/tests/test_macos_lume_runner.py b/libs/cua-driver/scripts/tests/test_macos_lume_runner.py
index 267dd9d275..1f980a552b 100644
--- a/libs/cua-driver/scripts/tests/test_macos_lume_runner.py
+++ b/libs/cua-driver/scripts/tests/test_macos_lume_runner.py
@@ -22,6 +22,10 @@ REPO_ROOT = Path(__file__).resolve().parents[4]
RUN_ALL = REPO_ROOT / "libs/cua-driver/tests/runners/macos-lume/run-all.sh"
SEED_TCC = REPO_ROOT / "libs/cua-driver/tests/runners/macos-lume/seed-tcc.sh"
SEED_TCC_GUEST = REPO_ROOT / "libs/cua-driver/tests/runners/macos-lume/seed-tcc-guest.sh"
+HARNESS_GUIDE = REPO_ROOT / "libs/cua-driver/docs/test-harnesses-guide.md"
+PUBLIC_LUME_TEST_GUIDE = (
+ REPO_ROOT / "docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx"
+)
RUN_RUST_E2E = REPO_ROOT / "scripts/ci/macos/run-rust-e2e.sh"
ELECTRON_BUILD = REPO_ROOT / "libs/cua-driver/tests/fixtures/apps/cross-platform/electron/build.sh"
ELECTRON_LOCK = (
@@ -317,6 +321,21 @@ def test_tcc_host_seed_accepts_multiple_vms() -> None:
assert "CUA_TCC_READ_SUDO_PASSWORD=1" in text
+ "document",
+ [HARNESS_GUIDE, PUBLIC_LUME_TEST_GUIDE],
+ ids=lambda path: path.name,
+)
+def test_harness_guides_route_automated_tcc_through_guarded_helper(document: Path) -> None:
+ text = document.read_text(encoding="utf-8")
+ assert "tests/runners/macos-lume/seed-tcc.sh" in text
+ assert "VirtualMac" in text
+ assert "SIP" in text
+ assert "certificate" in text
+ assert "TCC.db" in text
+ assert "rows alone" in text or "helper exit alone" in text
+
+
def test_tcc_host_seed_runs_the_guest_helper_once_per_vm(tmp_path: Path) -> None:
fake_bin = tmp_path / "bin"
fake_lume = fake_bin / "lume"
diff --git a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/main.js b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/main.js
index 82e1cf17c6..2800fcbfb7 100644
--- a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/main.js
+++ b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/main.js
@@ -12,6 +12,7 @@ const nativeWayland = process.platform === 'linux' && Boolean(process.env.WAYLAN
const customCuaCompositor = process.env.CUA_E2E_WAYLAND_SESSION === 'cua-compositor';
const fixtureJournalUrl = process.env.CUA_E2E_FIXTURE_JOURNAL_URL || '';
const sentinelJournalPath = process.env.CUA_E2E_SENTINEL_JOURNAL || '';
+const sentinelControlPath = process.env.CUA_E2E_SENTINEL_CONTROL || '';
if (process.env.CUA_E2E_USER_DATA_DIR) {
app.setPath('userData', process.env.CUA_E2E_USER_DATA_DIR);
}
@@ -59,6 +60,7 @@ ipcMain.on('cua-e2e-sentinel-event', (_event, entry) => {
let mainWindow;
let sentinelHeartbeatTimer;
+let sentinelSetupToken;
function createWindow() {
const fixedTitle = sentinelMode
@@ -144,6 +146,17 @@ function createWindow() {
if (!sentinelHeartbeatTimer) {
sentinelHeartbeatTimer = setInterval(() => {
if (mainWindow && !mainWindow.isDestroyed()) {
+ if (process.platform === 'win32' && sentinelControlPath) {
+ // A partially written request is retried on the next tick.
+ let request;
+ try {
+ request = JSON.parse(fs.readFileSync(sentinelControlPath, 'utf8'));
+ } catch {}
+ if (typeof request?.token === 'string' && request.token !== sentinelSetupToken) {
+ sentinelSetupToken = request.token;
+ mainWindow.webContents.send('cua-e2e-sentinel-arm-setup-click', request.token);
+ }
+ }
mainWindow.webContents.send('cua-e2e-sentinel-heartbeat-probe');
}
}, 100);
diff --git a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.js b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.js
index 5911a4e473..8cfcbc06bd 100644
--- a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.js
+++ b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.js
@@ -11,6 +11,7 @@ contextBridge.exposeInMainWorld('cuaE2E', {
});
const sentinelMode = fixtureConfig.sentinelMode;
+let setupClick;
function record(kind, details = {}) {
if (!sentinelMode) return;
@@ -19,9 +20,24 @@ function record(kind, details = {}) {
at_ms: Date.now(),
...details,
});
+ if (setupClick) {
+ const expected = ['pointerdown', 'pointerup', 'click'];
+ if (kind === expected[setupClick.step]) setupClick.step += 1;
+ if (setupClick.step === expected.length) {
+ const token = setupClick.token;
+ setupClick = undefined;
+ // Same renderer/channel as the pointer events: main journals this only
+ // after it has synchronously appended the complete setup click.
+ record('setup-click-drained', { token });
+ }
+ }
}
if (sentinelMode) {
+ ipcRenderer.on('cua-e2e-sentinel-arm-setup-click', (_event, token) => {
+ setupClick = { token, step: 0 };
+ record('setup-click-armed', { token });
+ });
window.addEventListener('DOMContentLoaded', () => {
document.body.innerHTML = `
<main style="min-height:100vh;background:#146c43;color:white;display:grid;place-content:center;text-align:center;font:24px system-ui">
diff --git a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.test.js b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.test.js
new file mode 100644
index 0000000000..e9e112dd28
--- /dev/null
+++ b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.test.js
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const vm = require('node:vm');
+
+function sentinelRenderer() {
+ const listeners = new Map();
+ const ipcListeners = new Map();
+ const pending = [];
+ vm.runInNewContext(fs.readFileSync(path.join(__dirname, 'preload.js'), 'utf8'), {
+ require: () => ({
+ contextBridge: { exposeInMainWorld() {} },
+ ipcRenderer: {
+ sendSync: () => ({ sentinelMode: true }),
+ send: (channel, entry) => pending.push({ channel, entry }),
+ on: (channel, handler) => ipcListeners.set(channel, handler),
+ },
+ }),
+ window: { addEventListener: (kind, handler) => listeners.set(kind, handler) },
+ });
+ return {
+ arm: token => ipcListeners.get('cua-e2e-sentinel-arm-setup-click')(null, token),
+ heartbeat: () => ipcListeners.get('cua-e2e-sentinel-heartbeat-probe')(),
+ input: kind => listeners.get(kind)({ button: 0, clientX: 10, clientY: 20 }),
+ pending,
+ };
+}
+
+test('setup barrier follows the full click on the same journal IPC channel', () => {
+ const renderer = sentinelRenderer();
+ renderer.arm('first');
+ renderer.heartbeat();
+ renderer.input('pointerdown');
+ renderer.input('pointerup');
+ assert.equal(renderer.pending.some(({ entry }) => entry.kind === 'setup-click-drained'), false);
+ renderer.input('click');
+ assert.deepEqual(renderer.pending.map(({ entry }) => entry.kind), [
+ 'setup-click-armed', 'heartbeat', 'pointerdown', 'pointerup', 'click', 'setup-click-drained',
+ ]);
+ assert.ok(renderer.pending.every(({ channel }) => channel === 'cua-e2e-sentinel-event'));
+ assert.equal(renderer.pending.at(-1).entry.token, 'first');
+ // An action's later pointer input remains observable after setup completes.
+ renderer.input('pointerdown');
+ assert.equal(renderer.pending.at(-1).entry.kind, 'pointerdown');
+});
+
+test('heartbeats, stale clicks, and partial clicks cannot complete a new setup token', () => {
+ const renderer = sentinelRenderer();
+ renderer.input('pointerdown');
+ renderer.input('pointerup');
+ renderer.input('click');
+ renderer.arm('first');
+ renderer.input('pointerdown');
+ renderer.arm('second');
+ renderer.input('pointerup');
+ renderer.input('click');
+ renderer.heartbeat();
+ assert.equal(renderer.pending.some(({ entry }) => entry.kind === 'setup-click-drained'), false);
+ renderer.input('pointerdown');
+ renderer.input('pointerup');
+ renderer.input('click');
+ assert.equal(renderer.pending.at(-1).entry.kind, 'setup-click-drained');
+ assert.equal(renderer.pending.at(-1).entry.token, 'second');
+});
diff --git a/rfcs/3197-local-modern-mcp-and-skills.md b/rfcs/3197-local-modern-mcp-and-skills.md
new file mode 100644
index 0000000000..28ea0f7c5e
--- /dev/null
+++ b/rfcs/3197-local-modern-mcp-and-skills.md
@@ -0,0 +1,193 @@
+---
+title: Local modern MCP and embedded skills
+authors:
+ - f-trycua
+created: 2026-09-07
+last_updated: 2026-09-07
+status: review
+discussion: https://github.com/trycua/cua/issues/3197
+rfc_pr: https://github.com/trycua/cua/pull/3609
+implementation:
+ - https://github.com/trycua/cua/pull/3609
+supersedes:
+superseded_by:
+---
+
+# RFC: Local modern MCP and embedded skills
+
+## Summary
+
+Add MCP `2026-07-28` to the existing Rust stdio server while retaining legacy
+initialization. Serve the canonical bundled Cua Driver skill through the
+Skills extension and base Resources methods. This is the local protocol
+increment of [#3197](https://github.com/trycua/cua/issues/3197), selected for
+implementation in [#3609](https://github.com/trycua/cua/pull/3609). It does not
+resolve the optional OAuth gateway decisions in
+[#3198](https://github.com/trycua/cua/pull/3198).
+
+## Motivation
+
+Modern MCP clients negotiate each request instead of requiring `initialize`.
+The previous Driver adapter only supports initialization-based clients.
+Separately, agents need the Driver workflow instructions and companion files
+without requiring a second tool server or an installation into host skill
+directories.
+
+## Goals
+
+- Serve modern and legacy stdio clients through the canonical Rust runtime.
+- Support discovery, strict per-request metadata, and modern result envelopes.
+- Expose one complete, verifiable skill pack with bounded lazy reads.
+- Preserve Driver authorization, session ownership, and unknown-outcome retry
+ guidance across direct and daemon-backed stdio paths.
+
+## Non-goals
+
+- OAuth, public HTTP, tunnels, remote desktop grants, or gateway ownership.
+- Modern HTTP application handles and cross-connection lifecycle.
+- Client-side skill activation, consent storage, or script execution.
+- Arbitrary installed skills, directory traversal, dynamic skills, archives,
+ optional directory listing, subscriptions, tasks, or server-initiated requests.
+- Replacing the installer integrity work in
+ [#2295](https://github.com/trycua/cua/issues/2295).
+
+## Terminology
+
+**Modern MCP** means protocol version `2026-07-28`, not the JSON-RPC version or
+an SDK major version. **Legacy** means initialization-based MCP. **Skill
+serving** provides bytes and metadata; the client separately controls loading,
+activation, and permission decisions.
+
+## Current state
+
+The shared [dispatcher](../libs/cua-driver/rust/crates/cua-driver-core/src/server.rs)
+and [stdio adapter](../libs/cua-driver/rust/crates/cua-driver/src/proxy.rs) own MCP
+translation. The SDK and daemon own execution. The
+[HTTP adapter](../libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs) binds
+session ownership to each TCP connection. The eight-file
+[canonical skill](../libs/cua-driver/rust/Skills/cua-driver/SKILL.md) is already
+versioned with Driver releases.
+
+## Proposal
+
+Pin implementation and conformance fixtures to the
+[base specification](https://github.com/modelcontextprotocol/modelcontextprotocol/tree/e76e9c572c6f2bfcb730357101acc90f2f802e02/schema/2026-07-28)
+and [SEP-2640](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/d6b31a03504c15677d49b922b6b6ace0ef65728d/seps/2640-skills-extension.md).
+The SEP text is accepted, but its upstream pull request remains open. Describe
+support as the pinned proposal implementation until publication is finalized.
+
+### Stdio protocol
+
+A legacy `initialize` selects legacy behavior for metadata-free requests on
+that stdio connection. Modern requests carry both
+`params._meta["io.modelcontextprotocol/protocolVersion"]` and
+`params._meta["io.modelcontextprotocol/clientCapabilities"]`. Capabilities are
+never inferred from a prior request. A modern request may arrive without any
+initialization. Missing or malformed metadata fails before tool invocation.
+
+`server/discover` reports the modern version and supported capabilities.
+Modern successful results include `resultType: "complete"`; discovery and
+list/read results include conservative `ttlMs: 0` and `cacheScope: "private"`
+hints where specified. Unsupported versions return `-32022` with the requested
+and supported versions. Metadata stays outside tool arguments and does not
+establish a principal or a Driver session.
+
+Existing stdio process/control ownership remains the application lifetime.
+Disconnect invalidates that owner as before. Reconnection does not replay
+actions or revive an old owner's sessions. A lost action response remains an
+unknown outcome requiring verification.
+
+### Embedded skills
+
+Embed the existing eight Markdown files into the Rust core at build time.
+Construct one immutable catalog containing the full YAML frontmatter and each
+file's raw-byte SHA-256 digest and byte length. A single static catalog page
+enumerates every file; reads use exact URI matching rather than filesystem
+resolution. No runtime network, home-directory reads, symlinks, or extraction
+are involved.
+
+Publish `skill://cua-driver/SKILL.md` through `skills/list` and `skills/get`.
+Expose all eight files through `resources/list` and `resources/read`.
+Declare `resources` and the `io.modelcontextprotocol/skills` extension in both
+legacy initialization and modern discovery. Do not declare optional directory
+reads or other unimplemented capabilities. Both direct and daemon-backed
+stdio serve the pack embedded in the MCP endpoint binary. The pack version
+identifies that endpoint, not an attestation of the executing daemon's build.
+Mixed-version daemons remain subject to the existing SDK contract checks and
+explicit output-schema compatibility check. Clients must use the advertised
+tool inventory; operators should update the endpoint and daemon together.
+
+The URI is stable; the complete digest set identifies the content revision.
+The host must verify bytes against that set and handle changed-content consent
+according to the pinned SEP. Serving or reading a skill grants no authority to
+execute code, broaden policy, or activate a skill in the host.
+
+### HTTP boundary
+
+Keep the authenticated loopback HTTP endpoint on the legacy protocol. Reject
+modern version metadata, modern version headers, and modern discovery before
+dispatch, with a diagnostic directing callers to stdio. HTTP must not silently
+advertise a modern profile whose application identity still depends on one TCP
+connection. Modern HTTP remains a later increment of the existing RFC.
+The rejection uses HTTP 400 and legacy `-32600`, rather than the modern
+`-32022` negotiation signal, so dual-era clients may fall back to initialization.
+
+## Alternatives considered
+
+A modern-only server would break deployed legacy clients. A second TypeScript
+execution facade, as explored in [#2824](https://github.com/trycua/cua/pull/2824),
+would require equivalent runtime authority and lifecycle behavior. This
+proposal instead exposes instructions from the canonical Rust endpoint.
+Dynamic reads of installed packs would couple serving to mutable local files
+and installer provenance; embedding gives the initial server a bounded source.
+
+## Compatibility and migration
+
+Keep existing tool signatures and the legacy initialization version. Select
+modern behavior through explicit request metadata. Installed skill directories
+and plugin generation are unchanged. Advertise only the transport/profile
+actually implemented; a base MCP client is not assumed to implement Skills.
+Rollback uses the prior Driver release and its legacy protocol configuration.
+
+## Security, privacy, and telemetry
+
+The manifest proves consistency with served bytes, not trustworthiness of a
+server. Keep host consent and execution approval separate. Exact resource
+allowlists reject paths, encoded aliases, unknown schemes, query strings, and
+foreign origins. Preserve the existing bounded telemetry policy: do not record
+arbitrary request metadata, skill bodies, or client capability payloads.
+
+## Implementation plan
+
+1. Add shared version validation, discovery, and result-envelope helpers.
+2. Add immutable skill metadata and exact resource reads.
+3. Integrate direct/proxy stdio and reject unsupported modern HTTP requests.
+4. Add protocol fixtures, real-process coverage, documentation, and client proof.
+
+## Test and acceptance plan
+
+Require tests for metadata errors before execution, unsupported versions,
+legacy negotiation, modern discovery and result envelopes, direct/proxy parity,
+raw-byte hashes and sizes, full frontmatter equality, complete manifests, and
+rejected resource aliases. Verify a real modern stdio client can discover the
+server, enumerate skills, retrieve a skill, and read its resources. Report
+native host activation separately from raw protocol interoperability.
+
+Ordinary cross-platform CI must pass. Canonical desktop certification belongs
+to the stable landing candidate. The macOS VM capacity blocker remains an
+environment prerequisite; prior source-PR certification is not certification
+of this new implementation.
+
+## Unresolved questions
+
+- Final upstream publication and any subsequent SEP-2640 changes.
+- Which host versions support native Skills activation and consent.
+- Trusted application handles and client isolation for modern HTTP.
+- Whether to serve only the host platform documents in a later pack revision.
+- A daemon/endpoint skill-pack attestation for mixed-version deployment.
+
+## Decision record
+
+The maintainer selected this local implementation increment on 2026-09-07.
+The proposal and implementation remain in draft review. Selection does not
+declare the broader gateway RFC accepted or claim the acceptance tests passed.