ext-apps icon indicating copy to clipboard operation
ext-apps copied to clipboard

tools that conditionally return ui resources

Open robertyates opened this issue 11 months ago • 6 comments

First off the spec looks great and we are hoping to use parts of it in place of elicitations (which are very cumbersome to use).

For many of our use cases we want the tool to sometimes return a ui resources and sometimes just return to the model. I may be reading it wrong but it doesn't look like conditional rendering of ui resources in a tool response is possible at the moment, can you confirm? it looks as though every response from a tool with a ui resources MUST render that ui resources.

A simple use case that exhibits this would be transferring money - transfer_money(from (checking / savings), to (checking/savings, amount).

The code will enforce rules on ensuring that the user picks a different from and to and that the amount being transferred is less than the balance. None of this requires a widget. However for the final stage we would like to return a widget for confirmation. When the user clicks accept it calls a different tool to confirm the transfer.

Is this possible today? i.e. this conditional return of a ui resource or is it assumed that every time a tool (with a ui resource) is called that the ui resources must be rendered.

Thanks in advance.

robertyates avatar Dec 22 '25 17:12 robertyates

having looked at what openai does, i think that this response

    if (transferDate < today) {
      return {
        content: [{
          type: "text",
          text: "Cannot schedule a transfer in the past. Please specify today or a future date."
        }],
        isError: true
      };
    }

will cause the UI resource NOT to render as it has no structuredContent and isError set to true, can you confirm that this is how it should work and maybe update the spec to reflect this ?

robertyates avatar Dec 22 '25 18:12 robertyates

Thanks @robertyates!

To optimize performance, the UI is rendered optimistically before the Tool responds. Hence, for the MVP, conditional rendering would mean optimistic rendering followed by termination as soon as the Tool responds. Currently, the MCP Apps spec doesn't include this mechanism, but we can add it if it's needed (potentially as part of the response's metadata).

As for Apps SDK, it has the openai/closeWidget functionality (see [docs]), but I'll defer to the folks from OpenAI for the best answer (@alexi-openai).

idosal avatar Dec 22 '25 21:12 idosal

Thanks, I assume others have these kinds of use cases, here's some sample code. How should something like this be best implemented ?

  // Check if date is in the past
    if (paymentDateObj < today) {
      // Note: No structuredContent is returned, so the UI widget will NOT be rendered.
      // This ensures validation errors are handled quickly without launching the widget.
      return {
        content: [
          {
            type: 'text',
            text: `We're unable to schedule a payment for ${paymentDate} as this date has already passed. Please select today's date or a date within the next 30 days.`,
            audience: ['user'],
          },
        ],
        isError: true,
      };
    }

    // Check if date is more than 30 days in the future
    if (paymentDateObj > thirtyDaysFromNow) {
      const latestDate = thirtyDaysFromNow.toISOString().split('T')[0];
      // Note: No structuredContent is returned, so the UI widget will NOT be rendered.
      // This ensures validation errors are handled quickly without launching the widget.
      return {
        content: [
          {
            type: 'text',
            text: `We can only schedule payments up to 30 days in advance. The date you selected (${paymentDate}) is beyond this window. Please choose a date on or before ${latestDate}.`,
            audience: ['user'],
          },
        ],
        isError: true,
      };
    }

    const loanNumber = `MTG-${customerId}-001`;
    const currentBalance = 287450.32;
    const transactionId = `TXN-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    const expiresAt = new Date(Date.now() + 5 * 60 * 1000).toISOString(); // 5 minutes from now

    // Structured confirmation dialog format
    const confirmationDialog = {
      confirmationText: `## Confirm Mortgage Payment\n\nPlease review the payment details below and confirm to proceed:\n\n**Payment Details:**\n- **Loan Number:** ${loanNumber}\n- **Amount:** $${amount.toFixed(2)}\n- **Payment Date:** ${paymentDate}\n- **Current Balance:** $${currentBalance.toLocaleString()}\n\n**Transaction ID:** ${transactionId}\n\n⚠️ This transaction will expire in 5 minutes at ${new Date(expiresAt).toLocaleString()}`,
      confirmAction: {
        tool: 'confirm_or_cancel_mortgage_payment',
        parameters: {
          transactionId,
          action: 'confirm',
        },
      },
      cancelAction: {
        tool: 'confirm_or_cancel_mortgage_payment',
        parameters: {
          transactionId,
          action: 'cancel',
        },
      },
    };

    return {
      content: [
        {
          type: 'text',
          text: `A mortgage payment has been prepared with transaction ID ${transactionId}. The user will be presented with a confirmation dialog to review and approve the payment.`,
          audience: ['assistant'],
        },
      ],
      structuredContent: confirmationDialog,
    };
  },

We are looking to implement a host and so we can have a lazy load of the widget based on whether the structuredContent is present or not. We just want to make sure it's consistent with the spec.

robertyates avatar Dec 23 '25 13:12 robertyates

here's a concrete proposal, let me know if you'd be willing to accept a PR on this

MCP Apps Specification Proposal: Multiple Widget Support Per Tool

Overview

This document proposes an extension to the MCP Apps specification to support multiple UI widgets from a single tool.

Motivation

Problem Statement

The current MCP Apps specification allows tools to declare a single resourceUri for UI rendering. However, real-world business logic often requires different UI widgets at different stages of tool execution.

Use Case: Date Selection with Business Rules

Consider a money transfer tool that needs to:

  1. Present a date picker with business-rule-constrained dates (e.g., "future dates only, but not more than 30 days out")
  2. Show a confirmation screen with transfer details
  3. Display a success message after completion

Why This Matters:

  • Business rules for valid selections are often complex and context-dependent
  • These rules are best enforced in the tool's business logic, not in generic UI components
  • The tool needs to dynamically select which widget to display based on the current state

Current Limitation

With the current spec, a tool can only declare one UI resource:

{
  name: "visualize_data",
  _meta: {
    ui: {
      resourceUri: "ui://charts/bar-chart"  // ← Single URI only
    }
  }
}

This forces developers to either:

  • Create overly complex, multi-purpose widgets
  • Use multiple separate tools for what should be a single logical operation
  • Implement business logic in the UI layer (violating separation of concerns)

Proposed Solution

1. Tool Registration Enhancement

Add a new resourceUris array to declare all possible widgets a tool may use:

{
  name: "transfer_money",
  _meta: {
    ui: {
      resourceUri: "ui://widgets/confirmation",  // ← Default/fallback
      resourceUris: [  // ← NEW: Array of possible widgets
        "ui://widgets/date-picker",
        "ui://widgets/confirmation",
        "ui://widgets/success"
      ]
    }
  }
}

Key Points:

  • resourceUri remains as the default/fallback widget
  • resourceUris declares all widgets the tool may use
  • Backward compatible: existing tools without resourceUris continue to work

2. Dynamic Widget Selection in Tool Response

Tools can override the widget in their response:

// Tool response dynamically selects widget
{
  content: [...],
  structuredContent: {...},
  _meta: {
    ui: {
      resourceUri: "ui://widgets/date-picker"  // ← Override
    }
  }
}

3. Type Definitions

interface McpUiToolMeta {
  /** Default/fallback URI */
  resourceUri?: string;
  
  /** NEW: Array of possible UI resources this tool may use */
  resourceUris?: string[];
  
  visibility?: Array<"model" | "app">;
}

4. Validation Rules

  1. Response Validation: If a tool response includes _meta.ui.resourceUri, it MUST be present in the declared resourceUris[] array
  2. Fallback Behavior: If resourceUris is present but the response doesn't specify resourceUri, use the default resourceUri
  3. Prefetching: Host applications SHOULD prefetch ALL URIs in resourceUris[] at connection time for optimal performance

Example Implementation

Complete Tool Registration

server.registerTool("transfer_money", {
  inputSchema: {
    from_account: z.string(),
    to_account: z.string(),
    amount: z.number(),
    transfer_date: z.string().optional()
  },
  _meta: {
    ui: {
      resourceUri: "ui://widgets/confirmation",  // Default
      resourceUris: [
        "ui://widgets/date-picker",
        "ui://widgets/confirmation", 
        "ui://widgets/success"
      ]
    }
  }
}, async ({ from_account, to_account, amount, transfer_date }) => {
  // Stage 1: Date selection with business rules
  if (!transfer_date) {
    return {
      content: [{ type: "text", text: "Select transfer date" }],
      structuredContent: { 
        validDateRange: { 
          min: today(), 
          max: thirtyDaysOut() 
        }
      },
      _meta: {
        ui: {
          resourceUri: "ui://widgets/date-picker"
        }
      }
    };
  }
  
  // Stage 2: Confirmation
  return {
    content: [{ type: "text", text: "Confirm transfer" }],
    structuredContent: { 
      from_account, 
      to_account, 
      amount, 
      transfer_date 
    },
    _meta: {
      ui: {
        resourceUri: "ui://widgets/confirmation"
      }
    }
  };
});

Flow Diagram

User Request → Tool Invoked (no date)
                ↓
            Returns date-picker widget
            with business rules (min/max dates)
                ↓
User Selects Date → Tool Invoked (with date)
                ↓
            Returns confirmation widget
            with transfer details
                ↓
User Confirms → Tool Executes Transfer
                ↓
            Returns success widget

Benefits

  1. Separation of Concerns: Business logic stays in the tool, UI stays in widgets
  2. Reusable Widgets: Generic widgets (date-picker, confirmation) can be reused across tools
  3. Dynamic UX: Tools can adapt their UI based on state and business rules
  4. Backward Compatible: Existing tools continue to work without changes
  5. Performance: Hosts can prefetch all possible widgets at connection time

Migration Path

For Existing Tools

No changes required. Tools with only resourceUri continue to work as before.

For New Tools

  1. Declare all possible widgets in resourceUris[]
  2. Set a sensible default in resourceUri
  3. Return appropriate resourceUri in tool responses based on state

For Host Applications

  1. Support both resourceUri (existing) and resourceUris[] (new)
  2. Implement validation: response URIs must be in declared array
  3. Consider prefetching all declared URIs for better performance

robertyates avatar Dec 23 '25 20:12 robertyates

This thread already covers what we ran into from two directions - @robertyates's conditional-render case and the maintainer note that response metadata is the likely mechanism. After working through the design space (including a server-initiated notification approach we tried and rejected - details below), here's a concrete shape.

The two symptoms are one primitive

"Sometimes don't render the registered app" and "sometimes render a different app" both reduce to: the tool's UI binding needs to be resolved at result time, not only at tools/list time. Same root cause as this issue and the same one SEP-1865's Future Considerations flags as "support multiple UI resources in a tool response."

Proposed shape

1. Feature negotiation (nested under the existing extensions["io.modelcontextprotocol/ui"] block, alongside the reserved features array):

"extensions": {
  "io.modelcontextprotocol/ui": {
    "mimeTypes": ["text/html;profile=mcp-app"],
    "features": ["result-resource-selection"]
  }
}

2. Tool-level opt-in - a tool must declare it may override its binding per-result:

interface McpUiToolMeta {
  resourceUri?: string;
  visibility?: Array<"model" | "app">;
  resourceUriSelection?: "result";  // NEW - opts this tool into per-result selection
}

3. Result-level selector - required on every completed result from an opted-in tool:

// CallToolResult._meta.ui.resourceUri, once resourceUriSelection: "result" is declared:
//   omitted        -> NOT ALLOWED for this tool (would be ambiguous with the static-binding default)
//   string (ui://…) -> render this same-server resource instead of the registered default
//   null            -> suppress: don't present an app for this result

Required rather than optional on purpose - an opted-in tool that forgets to set it is a server bug, not a fallback to the old default.

Host behavior this implies

  • Applies only when the host has advertised both base MCP Apps support and result-resource-selection. Otherwise the server must not rely on it and falls back to the existing single resourceUri binding or a plain tool.
  • No new prefetch-able allowlist. The selected URI is any same-server ui:// resource resolvable at result time, not a resourceUris[] array declared at registration. That's a deliberate tradeoff: the alternate path can't be prefetched, so it should stay the outlier branch (list/detail-style redirects), not the primary load path. The registered default stays fully prefetchable as today.
  • Because the alternate can't be prefetched, and to avoid a flash of the wrong app: if a host optimistically mounts the registered default before the result arrives, it MUST NOT make that mount visible until selection resolves. It can still preload/initialize it offscreen - only visibility is gated, not the existing preload optimization.
  • On a string selector: host validates the resource same as any resources/read (exists, CSP/permissions). Anything requesting broader permissions than the registered default goes through the normal host consent flow - a result can't silently escalate what the app is allowed to touch. Once validated, the host tears down the non-visible optimistic mount and initializes the selected view, replaying the standard ui/notifications/tool-input → ui/notifications/tool-result sequence so it looks identical to a statically-bound app from the view's side.
  • On validation failure: fall back to standard content/structuredContent presentation. No app. Never silently substitute the registered default - it wasn't built for this result's shape.
  • On null: host SHOULD suppress, MAY override (user preference, accessibility, a11y inspection, debugging). null means "the registered default is valid but low-value for this result," never "no app can render this" - if a user overrides and reveals it, it must still work correctly.
  • Scoped to completed (resultType: "complete") results only. Doesn't touch input_required / the MRTR path SEP-3118 is already extending.

Concrete case (not overfit to one product)

A search_records-shaped tool: 0 results → null (no app for an empty result), 1 result → select the existing single-record detail app, 2+ → registered list app. The reason this needs dynamic selection rather than one polymorphic app: the detail app is a canonical, independently reusable UI resource with its own result contract. Duplicating its rendering logic inside every list app that might collapse to one result creates divergent behavior for what should be one canonical view. structuredContent doesn't change shape either way - the detail app explicitly supports the list tool's stable output shape.

We also checked the obvious workaround - split into search_records + get_record, let the model call the second when there's one result - and don't think it holds up: it's an extra model round-trip for a decision that's deterministic from the result the server already has, adds latency/cost, risks the model not following up, and would sequentially mount two apps instead of the one that's actually correct.

Explicitly not proposing

We looked hard at a notifications/app/open / notifications/app/close pair (server → client notifications for redirect and suppression) before landing here, and rejected it: notifications are fire-and-forget with no response and no natural correlation to a specific view instance, they'd cross from the server↔client channel into iframe lifecycle the host owns, and a server-initiated close/open inverts the host's control over what the user sees. Everything both notifications would have done is expressible at the result boundary above, correlated to the exact invocation, for free.

Relationship to adjacent issues

  • #694 (error-result rendering): the same required-selector rule extends cleanly to isError: true results, and would resolve the current ChatGPT/Claude/Goose divergence there - null = standard error presentation, a string = an app built to handle that specific error. Flagging rather than folding in, since #694 may want to settle the default behavior for tools that haven't opted into this at all.
  • #731 (collapsible apps): different mechanism, worth keeping distinct. Collapse keeps the app as a user-reachable artifact the user can expand; null here means the host defaults to ordinary tool-result presentation and doesn't expose an app at all for that result.

Open questions for maintainers

  • Field/capability naming - resourceUriSelection / result-resource-selection are placeholders.
  • Whether error-result coverage ships here or waits on #694 to settle the no-opt-in default first.
  • Whether null should be spelled differently to avoid any ambiguity with "omitted" (we want omitted to remain a hard error for opted-in tools, not silently equivalent to null).

Happy to prototype this in ext-apps - schema/type changes, a basic-host implementation, an example server exercising all three selector states, and conformance tests - once the shape looks right to folks here. Wanted to get the design in front of the thread before opening a PR against a moving draft.

dleblondMSFT avatar Aug 07 '26 18:08 dleblondMSFT

same desire for conditional-render.

szhero avatar Oct 16 '26 12:10 szhero