Skip to content

first draft - #2320

Draft
wrenj wants to merge 7 commits into
mainfrom
mcpappsa2ui
Draft

wrenj wants to merge 7 commits into
mainfrom
mcpappsa2ui

Conversation

@wrenj

@wrenj wrenj commented Aug 18, 2026

Copy link
Copy Markdown
Collaborator

No description provided.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for A2UI v1.0 over the Model Context Protocol (MCP), enabling dynamic dual-mode capability negotiation between Native A2UI Mode and Iframe Sandboxed Mode. It adds Python and TypeScript SDK helpers, a formal protocol specification, and a complete dual-mode sample application. The review feedback highlights several opportunities to improve the robustness and security of the implementation. Specifically, it is recommended to refactor the Python capability negotiation helper to avoid fragile type checks, add defensive error handling in the TypeScript action dispatcher and payload extractor to prevent runtime crashes, implement the fallback logic in the Python server tool, and secure the postMessage target origin in the sandbox proxy to prevent data leakage.

Comment on lines +21 to +83
def supports_native_a2ui(client_capabilities: Any) -> bool:
"""Determines whether an MCP client advertises native A2UI support.

Inspects client capabilities or initialize parameters for the
'io.modelcontextprotocol/ui' extension advertising 'application/a2ui+json'
in its mimeTypes list.

Args:
client_capabilities: A dictionary, types.ClientCapabilities, or
InitializeParams object representing client capabilities.

Returns:
True if the client explicitly supports application/a2ui+json, False otherwise.
"""
if client_capabilities is None:
return False

# Extract dictionary representation if pydantic / custom model
caps: dict[str, Any] = {}
if isinstance(client_capabilities, dict):
caps = client_capabilities
elif hasattr(client_capabilities, "model_dump"):
try:
caps = client_capabilities.model_dump(by_alias=True)
except Exception:
caps = {}
elif hasattr(client_capabilities, "dict"):
try:
caps = client_capabilities.dict()
except Exception:
caps = {}
elif hasattr(client_capabilities, "__dict__"):
caps = client_capabilities.__dict__

# If wrapped under 'capabilities' (e.g. InitializeParams)
if "capabilities" in caps and isinstance(caps["capabilities"], dict):
caps = caps["capabilities"]

# Extract extensions
extensions = caps.get("extensions")
if extensions is None and hasattr(client_capabilities, "extensions"):
extensions = getattr(client_capabilities, "extensions")

if not isinstance(extensions, dict):
return False

ui_ext = extensions.get(MCP_UI_EXTENSION_KEY)
if ui_ext is None:
return False

if isinstance(ui_ext, dict):
mime_types = ui_ext.get("mimeTypes") or ui_ext.get("mime_types")
elif hasattr(ui_ext, "mimeTypes"):
mime_types = getattr(ui_ext, "mimeTypes")
elif hasattr(ui_ext, "mime_types"):
mime_types = getattr(ui_ext, "mime_types")
else:
mime_types = None

if isinstance(mime_types, (list, tuple, set)):
return A2UI_MIME_TYPE in mime_types

return False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation of supports_native_a2ui relies on fragile type checks (isinstance(client_capabilities, dict)) and nested dictionary conversions (model_dump, dict, __dict__). If client_capabilities is an object whose capabilities or extensions attributes are also custom objects (rather than dictionaries), the unwrapping logic fails or returns False prematurely. Refactoring this to use a simple helper function that dynamically retrieves keys/attributes is much more robust and maintainable.

def supports_native_a2ui(client_capabilities: Any) -> bool:
    """Determines whether an MCP client advertises native A2UI support.

    Inspects client capabilities or initialize parameters for the
    'io.modelcontextprotocol/ui' extension advertising 'application/a2ui+json'
    in its mimeTypes list.

    Args:
        client_capabilities: A dictionary, types.ClientCapabilities, or
            InitializeParams object representing client capabilities.

    Returns:
        True if the client explicitly supports application/a2ui+json, False otherwise.
    """
    if client_capabilities is None:
        return False

    def get_field(obj: Any, key: str) -> Any:
        if isinstance(obj, dict):
            return obj.get(key)
        return getattr(obj, key, None)

    # Handle wrapping under 'capabilities' (e.g. InitializeParams)
    caps = get_field(client_capabilities, "capabilities")
    if caps is None:
        caps = client_capabilities

    extensions = get_field(caps, "extensions")
    if extensions is None:
        return False

    ui_ext = get_field(extensions, MCP_UI_EXTENSION_KEY)
    if ui_ext is None:
        return False

    mime_types = get_field(ui_ext, "mimeTypes")
    if mime_types is None:
        mime_types = get_field(ui_ext, "mime_types")

    if isinstance(mime_types, (list, tuple, set)):
        return A2UI_MIME_TYPE in mime_types

    return False

Comment on lines +91 to +97
if (typeof surfaceModel.dispatchError === 'function') {
const message = err instanceof Error ? err.message : String(err);
await surfaceModel.dispatchError({
code: 'MCP_TOOL_ERROR',
message: `Failed to execute MCP tool '${action.name}': ${message}`,
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If surfaceModel.dispatchError throws an error or rejects, it will result in an unhandled promise rejection because the subscribe listener is an asynchronous function. Wrapping the call in a try-catch block prevents unexpected runtime crashes or unhandled rejections during error dispatching.

      if (typeof surfaceModel.dispatchError === 'function') {
        const message = err instanceof Error ? err.message : String(err);
        try {
          await surfaceModel.dispatchError({
            code: 'MCP_TOOL_ERROR',
            message: `Failed to execute MCP tool '${action.name}': ${message}`,
          });
        } catch (dispatchErr) {
          console.error('Failed to dispatch error to surface model:', dispatchErr);
        }
      }

Comment on lines +62 to +64

for (const item of result.content) {
// 1. Embedded resource format: { type: 'resource', resource: { mimeType: 'application/a2ui+json', text: '...' } }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If result.content contains null, undefined, or non-object items, accessing item.type or item.mimeType directly will throw a TypeError and crash the application. Adding a defensive check at the beginning of the loop ensures robust execution.

  for (const item of result.content) {
    if (!item || typeof item !== 'object') {
      continue;
    }
    // 1. Embedded resource format: { type: 'resource', resource: { mimeType: 'application/a2ui+json', text: '...' } }
    if (item.type === 'resource' && item.resource) {

Comment on lines +147 to +152
def get_counter_app(native: bool = False) -> types.CallToolResult:
return create_a2ui_tool_result(
get_counter_a2ui(COUNTER),
text_fallback=f"Current count: {COUNTER}",
resource_uri="a2ui://counter-view",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The native parameter in get_counter_app is currently ignored, meaning the tool always returns the native A2UI payload regardless of the client's capabilities or the parameter value. Implementing the conditional logic to return the fallback HTML app when native is False makes the fallback mode functional and matches the tool's description.

    def get_counter_app(native: bool = False) -> types.CallToolResult:
        if not native:
            html_path = pathlib.Path(__file__).parent / "public" / "fallback_app.html"
            html_content = html_path.read_text(encoding="utf-8")
            return types.CallToolResult(
                content=[
                    types.EmbeddedResource(
                        type="resource",
                        resource=types.TextResourceContents(
                            uri="ui://counter/app",
                            mimeType=MCP_APPS_MIME_TYPE,
                            text=html_content,
                        ),
                    )
                ]
            )

        return create_a2ui_tool_result(
            get_counter_a2ui(COUNTER),
            text_fallback=f"Current count: {COUNTER}",
            resource_uri="a2ui://counter-view",
        )

Comment on lines +38 to +40
} else if (event.source === inner.contentWindow) {
window.parent.postMessage(event.data, '*');
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

Using wildcard * as the target origin in postMessage allows any origin to intercept the messages if the window is re-routed or hijacked. Since the proxy iframe is loaded from the same origin as the parent host, using window.location.origin is much more secure and prevents potential data leakage.

Suggested change
} else if (event.source === inner.contentWindow) {
window.parent.postMessage(event.data, '*');
}
} else if (event.source === inner.contentWindow) {
window.parent.postMessage(event.data, window.location.origin);
}

@liady

liady commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Hi @wrenj , I'm working on that from the MCP Apps side.
This direction looks good, are you familiar with this spec extension proposal?
modelcontextprotocol/ext-apps#699

@github-actions github-actions Bot added the status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs label Nov 20, 2026
@polina-c

polina-c commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

From triage bot, analysis:

For humans

TL;DR
Case: this is a team member's "first draft" PR, idle since August, with merge conflicts and an unanswered question.
Suggestion: add status: waiting-for-author-response and ask wrenj to update or close it.

Summary:
wrenj adds A2UI v1.0 over MCP: Python helpers for capability negotiation and tool responses, TypeScript helpers in web_core (an action dispatcher, a payload extractor and a sandbox host), a specification for the MCP Apps extension, guides, and a sample with a client and a server. The PR has no description.

Suggestion:
Add status: waiting-for-author-response and post the reply below, which asks wrenj to update or close the PR. The PR waits for its author:

  1. It has had no commits since August 18, and GitHub reports merge conflicts with main. It changes folders that no longer exist on main, agent_sdks/python/ and renderers/web_core/, which moved to python/ and typescript/core/web_core/.
  2. liady, who works on MCP Apps, asked whether wrenj knows the spec extension proposal modelcontextprotocol/ext-apps#699, and nobody answered. The question is for wrenj, so the reply passes it on.
  3. Newer open PRs by josemontespg overlap with it: #4297 adds @a2ui/embed with the MCP Apps contract, including an a2ui_action tool for user actions, and #4299 adds the runtime that renders A2UI inside the MCP Apps host iframe. Only wrenj can say whether this PR is still needed next to them.

No team member reviewed the PR (only gemini-code-assist did), and the author is a team member, so I suggest no assignee.

  1. Add labels: status: waiting-for-author-response
  2. Related items: feat(embed): add @a2ui/embed with the MCP Apps contract #4297, feat(embed): add the @a2ui/embed/mcp iframe runtime #4299

Reply:

wrenj, this PR has had no commits since August, and it now has merge conflicts with main. Is it still needed next to #4297 and #4299, which add A2UI in MCP Apps? If it is, could you rebase it and add a description? If not, could you close it?

Also, liady asked whether you know the spec extension proposal modelcontextprotocol/ext-apps#699.

To adjust the analysis and apply its suggestion, run in your a2ui checkout:

tools/internal/triage/triage_ui.sh https://github.com/a2ui-project/a2ui/pull/2320
For software
<a2ui>
root = TriageAnalysis(
  tldr="""Case: this is a team member's "first draft" PR, idle since August, with merge conflicts and an unanswered question.
Suggestion: add `status: waiting-for-author-response` and ask `wrenj` to update or close it.""",
  summary="""`wrenj` adds A2UI v1.0 over MCP: Python helpers for capability negotiation and tool responses, TypeScript helpers in `web_core` (an action dispatcher, a payload extractor and a sandbox host), a specification for the MCP Apps extension, guides, and a sample with a client and a server. The PR has no description.""",
  suggestion="""Add `status: waiting-for-author-response` and post the reply below, which asks `wrenj` to update or close the PR. The PR waits for its author:

1. It has had no commits since August 18, and GitHub reports merge conflicts with `main`. It changes folders that no longer exist on `main`, `agent_sdks/python/` and `renderers/web_core/`, which moved to `python/` and `typescript/core/web_core/`.
2. `liady`, who works on MCP Apps, [asked](https://github.com/a2ui-project/a2ui/pull/2320#issuecomment-5343545906) whether `wrenj` knows the spec extension proposal [modelcontextprotocol/ext-apps#699](https://github.com/modelcontextprotocol/ext-apps/pull/699), and nobody answered. The question is for `wrenj`, so the reply passes it on.
3. Newer open PRs by `josemontespg` overlap with it: [#4297](https://github.com/a2ui-project/a2ui/pull/4297) adds `@a2ui/embed` with the MCP Apps contract, including an `a2ui_action` tool for user actions, and [#4299](https://github.com/a2ui-project/a2ui/pull/4299) adds the runtime that renders A2UI inside the MCP Apps host iframe. Only `wrenj` can say whether this PR is still needed next to them.

No team member reviewed the PR (only `gemini-code-assist` did), and the author is a team member, so I suggest no assignee.""",
  reply="""`wrenj`, this PR has had no commits since August, and it now has merge conflicts with `main`. Is it still needed next to [#4297](https://github.com/a2ui-project/a2ui/pull/4297) and [#4299](https://github.com/a2ui-project/a2ui/pull/4299), which add A2UI in MCP Apps? If it is, could you rebase it and add a description? If not, could you close it?

Also, `liady` [asked](https://github.com/a2ui-project/a2ui/pull/2320#issuecomment-5343545906) whether you know the spec extension proposal [modelcontextprotocol/ext-apps#699](https://github.com/modelcontextprotocol/ext-apps/pull/699).""",
  added_labels=["status: waiting-for-author-response"],
  related_items=[4297, 4299]
)
</a2ui>

This analysis is auto-created to help humans to triage this item. Please, do not treat it as a team decision.

🤖 Agent-generated

@polina-c

polina-c commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

From triage bot, analysis:

For humans

TL;DR
Case: this is a team member's "first draft" PR, idle since August, with merge conflicts and an unanswered question.
Suggestion: add status: waiting-for-author-response and ask wrenj to update or close it.

Summary:
wrenj adds A2UI v1.0 over MCP: Python helpers for capability negotiation and tool responses, TypeScript helpers in web_core (an action dispatcher, a payload extractor and a sandbox host), a specification for the MCP Apps extension, guides, and a sample with a client and a server. The PR has no description.

Suggestion:
Add status: waiting-for-author-response and post the reply below, which asks wrenj to update or close the PR. The PR waits for its author:

  1. It has had no commits since August 18, and GitHub reports merge conflicts with main. It changes folders that no longer exist on main, agent_sdks/python/ and renderers/web_core/, which moved to python/ and typescript/core/web_core/.
  2. liady, who works on MCP Apps, asked whether wrenj knows the spec extension proposal modelcontextprotocol/ext-apps#699, and nobody answered. The question is for wrenj, so the reply passes it on.
  3. Newer open PRs by josemontespg overlap with it: #4297 adds @a2ui/embed with the MCP Apps contract, including an a2ui_action tool for user actions, and #4299 adds the runtime that renders A2UI inside the MCP Apps host iframe. Only wrenj can say whether this PR is still needed next to them.

Assign no one: no team member has submitted a review, only gemini-code-assist.

  1. Add labels: status: waiting-for-author-response
  2. Related items: feat(embed): add @a2ui/embed with the MCP Apps contract #4297, feat(embed): add the @a2ui/embed/mcp iframe runtime #4299

Reply:

wrenj, this PR has had no commits since August, and it now has merge conflicts with main. Is it still needed next to #4297 and #4299, which add A2UI in MCP Apps? If it is, could you rebase it and add a description? If not, could you close it? We are marking it as waiting for your response until then.

Also, liady asked whether you know the spec extension proposal modelcontextprotocol/ext-apps#699.

To adjust the analysis and apply its suggestion, run in your a2ui checkout:

tools/internal/triage/triage_ui.sh https://github.com/a2ui-project/a2ui/pull/2320
For software
<a2ui>
root = TriageAnalysis(
  tldr="""Case: this is a team member's "first draft" PR, idle since August, with merge conflicts and an unanswered question.
Suggestion: add `status: waiting-for-author-response` and ask `wrenj` to update or close it.""",
  summary="""`wrenj` adds A2UI v1.0 over MCP: Python helpers for capability negotiation and tool responses, TypeScript helpers in `web_core` (an action dispatcher, a payload extractor and a sandbox host), a specification for the MCP Apps extension, guides, and a sample with a client and a server. The PR has no description.""",
  suggestion="""Add `status: waiting-for-author-response` and post the reply below, which asks `wrenj` to update or close the PR. The PR waits for its author:

1. It has had no commits since August 18, and GitHub reports merge conflicts with `main`. It changes folders that no longer exist on `main`, `agent_sdks/python/` and `renderers/web_core/`, which moved to [`python/`](https://github.com/a2ui-project/a2ui/tree/172cf31e1acbce31c4e60d82b2edbd923b279dd8/python) and [`typescript/core/web_core/`](https://github.com/a2ui-project/a2ui/tree/172cf31e1acbce31c4e60d82b2edbd923b279dd8/typescript/core/web_core).
2. `liady`, who works on MCP Apps, [asked](https://github.com/a2ui-project/a2ui/pull/2320#issuecomment-5343545906) whether `wrenj` knows the spec extension proposal [modelcontextprotocol/ext-apps#699](https://github.com/modelcontextprotocol/ext-apps/pull/699), and nobody answered. The question is for `wrenj`, so the reply passes it on.
3. Newer open PRs by `josemontespg` overlap with it: [#4297](https://github.com/a2ui-project/a2ui/pull/4297) adds `@a2ui/embed` with the MCP Apps contract, including an `a2ui_action` tool for user actions, and [#4299](https://github.com/a2ui-project/a2ui/pull/4299) adds the runtime that renders A2UI inside the MCP Apps host iframe. Only `wrenj` can say whether this PR is still needed next to them.

Assign no one: no team member has submitted a review, only `gemini-code-assist`.""",
  reply="""`wrenj`, this PR has had no commits since August, and it now has merge conflicts with `main`. Is it still needed next to [#4297](https://github.com/a2ui-project/a2ui/pull/4297) and [#4299](https://github.com/a2ui-project/a2ui/pull/4299), which add A2UI in MCP Apps? If it is, could you rebase it and add a description? If not, could you close it? We are marking it as waiting for your response until then.

Also, `liady` [asked](https://github.com/a2ui-project/a2ui/pull/2320#issuecomment-5343545906) whether you know the spec extension proposal [modelcontextprotocol/ext-apps#699](https://github.com/modelcontextprotocol/ext-apps/pull/699).""",
  added_labels=["status: waiting-for-author-response"],
  related_items=[4297, 4299]
)
</a2ui>

This analysis is auto-created to help humans to triage this item. Please, do not treat it as a team decision.

🤖 Agent-generated

@polina-c
polina-c marked this pull request as draft November 20, 2026 22:28
@polina-c polina-c removed the status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs label Nov 20, 2026
@github-actions github-actions Bot added status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs and removed status: needs-triage auto-managed: https://github.com/a2ui-project/a2ui/blob/main/scripts/triage.mjs labels Nov 20, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants