feat: implement ui/notifications/tool-cancelled + add missing App.onteardown (#120)

* feat: implement ui/notifications/tool-cancelled throughout SDK

Wire the tool-cancelled notification that hosts MUST send when tool
execution is cancelled (user action, timeout, classifier intervention, etc.):

- Add McpUiToolCancelledNotification type in spec.types.ts
- Generate Zod schema via ts-to-zod
- Add AppBridge.sendToolCancelled() method for hosts
- Add App.ontoolcancelled setter for guest UIs
- Export type and schema from types.ts
- Add tests for notification with/without reason

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: add App.onteardown handler for graceful shutdown

Wire the guest UI side of ui/resource-teardown request:

- Add onteardown setter in App class for guest UIs to handle teardown
- Allow ui/resource-teardown in assertRequestHandlerCapability
- Import McpUiResourceTeardownRequest/Result types
- Add tests for sync and async cleanup handlers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(example): wire tool-cancelled and teardown in basic-host

Update basic-host example to properly use the new notifications:

- Send sendToolCancelled when tool call promise rejects
- Send sendResourceTeardown when React component unmounts
- Store appBridge ref for cleanup access

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(example): implement graceful teardown per spec recommendation

Address review feedback: the host now waits for guest's teardown
response before unmounting, following the spec: "Host SHOULD wait
for a response before tearing down the resource (to prevent data loss)."

Changes:
- Add close button to tool call panels
- Two-phase unmount: isDestroying state dims panel and disables events
- sendResourceTeardown() completes before component removal
- Non-app tool results close immediately

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(examples): add onteardown handlers to demo apps

Demonstrate graceful shutdown with simulated 500ms cleanup work.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Olivier Chafik 2025-12-11 20:31:17 +01:00 • committed by GitHub
commit 70b393a7e6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 379 additions and 15 deletions

View file

@ -140,6 +140,36 @@ describe("App <-> AppBridge integration", () => {
});
});
it("sendToolCancelled triggers app.ontoolcancelled", async () => {
const receivedCancellations: unknown[] = [];
app.ontoolcancelled = (params) => {
receivedCancellations.push(params);
};
await app.connect(appTransport);
await bridge.sendToolCancelled({
reason: "User cancelled the operation",
});
expect(receivedCancellations).toHaveLength(1);
expect(receivedCancellations[0]).toEqual({
reason: "User cancelled the operation",
});
});
it("sendToolCancelled works without reason", async () => {
const receivedCancellations: unknown[] = [];
app.ontoolcancelled = (params) => {
receivedCancellations.push(params);
};
await app.connect(appTransport);
await bridge.sendToolCancelled({});
expect(receivedCancellations).toHaveLength(1);
expect(receivedCancellations[0]).toEqual({});
});
it("setHostContext triggers app.onhostcontextchanged", async () => {
const receivedContexts: unknown[] = [];
app.onhostcontextchanged = (params) => {
@ -173,6 +203,34 @@ describe("App <-> AppBridge integration", () => {
{ theme: "light" },
]);
});
it("sendResourceTeardown triggers app.onteardown", async () => {
let teardownCalled = false;
app.onteardown = async () => {
teardownCalled = true;
return {};
};
await app.connect(appTransport);
await bridge.sendResourceTeardown({});
expect(teardownCalled).toBe(true);
});
it("sendResourceTeardown waits for async cleanup", async () => {
const cleanupSteps: string[] = [];
app.onteardown = async () => {
cleanupSteps.push("start");
await new Promise((resolve) => setTimeout(resolve, 10));
cleanupSteps.push("done");
return {};
};
await app.connect(appTransport);
await bridge.sendResourceTeardown({});
expect(cleanupSteps).toEqual(["start", "done"]);
});
});
describe("App -> Host notifications", () => {

View file

@ -34,6 +34,7 @@ import {
import {
type McpUiSandboxResourceReadyNotification,
type McpUiSizeChangedNotification,
type McpUiToolCancelledNotification,
type McpUiToolInputNotification,
type McpUiToolInputPartialNotification,
type McpUiToolResultNotification,
@ -737,6 +738,43 @@ export class AppBridge extends Protocol<Request, Notification, Result> {
});
}
/**
* Notify the Guest UI that tool execution was cancelled.
*
* The host MUST send this notification if tool execution was cancelled for any
* reason, including user action, sampling error, classifier intervention, or
* any other interruption. This allows the Guest UI to update its state and
* display appropriate feedback to the user.
*
* @param params - Optional cancellation details:
* - `reason`: Human-readable explanation for why the tool was cancelled
*
* @example User-initiated cancellation
* ```typescript
* // User clicked "Cancel" button
* bridge.sendToolCancelled({ reason: "User cancelled the operation" });
* ```
*
* @example System-level cancellation
* ```typescript
* // Sampling error or timeout
* bridge.sendToolCancelled({ reason: "Request timeout after 30 seconds" });
*
* // Classifier intervention
* bridge.sendToolCancelled({ reason: "Content policy violation detected" });
* ```
*
* @see {@link McpUiToolCancelledNotification} for the notification type
* @see {@link sendToolResult} for sending successful results
* @see {@link sendToolInput} for sending tool arguments
*/
sendToolCancelled(params: McpUiToolCancelledNotification["params"]) {
return this.notification(<McpUiToolCancelledNotification>{
method: "ui/notifications/tool-cancelled",
params,
});
}
/**
* Send HTML resource to the sandbox proxy for secure loading.
*

View file

@ -31,7 +31,12 @@ import {
McpUiMessageResultSchema,
McpUiOpenLinkRequest,
McpUiOpenLinkResultSchema,
McpUiResourceTeardownRequest,
McpUiResourceTeardownRequestSchema,
McpUiResourceTeardownResult,
McpUiSizeChangedNotification,
McpUiToolCancelledNotification,
McpUiToolCancelledNotificationSchema,
McpUiToolInputNotification,
McpUiToolInputNotificationSchema,
McpUiToolInputPartialNotification,
@ -388,6 +393,41 @@ export class App extends Protocol<Request, Notification, Result> {
);
}
/**
* Convenience handler for receiving tool cancellation notifications from the host.
*
* Set this property to register a handler that will be called when the host
* notifies that tool execution was cancelled. This can occur for various reasons
* including user action, sampling error, classifier intervention, or other
* interruptions. Apps should update their state and display appropriate feedback.
*
* This setter is a convenience wrapper around `setNotificationHandler()` that
* automatically handles the notification schema and extracts the params for you.
*
* Register handlers before calling {@link connect} to avoid missing notifications.
*
* @param callback - Function called when tool execution is cancelled
*
* @example Handle tool cancellation
* ```typescript
* app.ontoolcancelled = (params) => {
* console.log("Tool cancelled:", params.reason);
* showCancelledMessage(params.reason ?? "Operation was cancelled");
* };
* ```
*
* @see {@link setNotificationHandler} for the underlying method
* @see {@link McpUiToolCancelledNotification} for the notification structure
* @see {@link ontoolresult} for successful tool completion
*/
set ontoolcancelled(
callback: (params: McpUiToolCancelledNotification["params"]) => void,
) {
this.setNotificationHandler(McpUiToolCancelledNotificationSchema, (n) =>
callback(n.params),
);
}
/**
* Convenience handler for host context changes (theme, viewport, locale, etc.).
*
@ -427,6 +467,48 @@ export class App extends Protocol<Request, Notification, Result> {
);
}
/**
* Convenience handler for graceful shutdown requests from the host.
*
* Set this property to register a handler that will be called when the host
* requests the app to prepare for teardown. This allows the app to perform
* cleanup operations (save state, close connections, etc.) before being unmounted.
*
* The handler can be sync or async. The host will wait for the returned promise
* to resolve before proceeding with teardown.
*
* This setter is a convenience wrapper around `setRequestHandler()` that
* automatically handles the request schema.
*
* Register handlers before calling {@link connect} to avoid missing requests.
*
* @param callback - Function called when teardown is requested.
* Can return void or a Promise that resolves when cleanup is complete.
*
* @example Perform cleanup before teardown
* ```typescript
* app.onteardown = async () => {
* await saveState();
* closeConnections();
* console.log("App ready for teardown");
* };
* ```
*
* @see {@link setRequestHandler} for the underlying method
* @see {@link McpUiResourceTeardownRequest} for the request structure
*/
set onteardown(
callback: (
params: McpUiResourceTeardownRequest["params"],
extra: RequestHandlerExtra,
) => McpUiResourceTeardownResult | Promise<McpUiResourceTeardownResult>,
) {
this.setRequestHandler(
McpUiResourceTeardownRequestSchema,
(request, extra) => callback(request.params, extra),
);
}
/**
* Convenience handler for tool call requests from the host.
*
@ -533,6 +615,7 @@ export class App extends Protocol<Request, Notification, Result> {
}
return;
case "ping":
case "ui/resource-teardown":
return;
default:
throw new Error(`No handler for method ${method} registered`);

View file

@ -1732,6 +1732,28 @@
}
]
},
"McpUiToolCancelledNotification": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"method": {
"type": "string",
"const": "ui/notifications/tool-cancelled"
},
"params": {
"type": "object",
"properties": {
"reason": {
"description": "Optional reason for the cancellation (e.g., \"user action\", \"timeout\").",
"type": "string"
}
},
"additionalProperties": false
}
},
"required": ["method", "params"],
"additionalProperties": false
},
"McpUiToolInputNotification": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",

View file

@ -51,6 +51,10 @@ export type McpUiToolInputPartialNotificationSchemaInferredType = z.infer<
typeof generated.McpUiToolInputPartialNotificationSchema
>;
export type McpUiToolCancelledNotificationSchemaInferredType = z.infer<
typeof generated.McpUiToolCancelledNotificationSchema
>;
export type McpUiResourceTeardownRequestSchemaInferredType = z.infer<
typeof generated.McpUiResourceTeardownRequestSchema
>;
@ -151,6 +155,12 @@ expectType<spec.McpUiToolInputPartialNotification>(
expectType<McpUiToolInputPartialNotificationSchemaInferredType>(
{} as spec.McpUiToolInputPartialNotification,
);
expectType<spec.McpUiToolCancelledNotification>(
{} as McpUiToolCancelledNotificationSchemaInferredType,
);
expectType<McpUiToolCancelledNotificationSchemaInferredType>(
{} as spec.McpUiToolCancelledNotification,
);
expectType<spec.McpUiResourceTeardownRequest>(
{} as McpUiResourceTeardownRequestSchemaInferredType,
);

View file

@ -160,6 +160,24 @@ export const McpUiToolInputPartialNotificationSchema = z.object({
}),
});
/**
* @description Notification that tool execution was cancelled (Host -> Guest UI).
* Host MUST send this if tool execution was cancelled for any reason (user action,
* sampling error, classifier intervention, etc.).
*/
export const McpUiToolCancelledNotificationSchema = z.object({
method: z.literal("ui/notifications/tool-cancelled"),
params: z.object({
/** @description Optional reason for the cancellation (e.g., "user action", "timeout"). */
reason: z
.string()
.optional()
.describe(
'Optional reason for the cancellation (e.g., "user action", "timeout").',
),
}),
});
/**
* @description Request for graceful shutdown of the Guest UI (Host -> Guest UI).
* @see {@link app-bridge.AppBridge.sendResourceTeardown} for the host method that sends this

View file

@ -167,6 +167,19 @@ export interface McpUiToolResultNotification {
params: CallToolResult;
}
/**
* @description Notification that tool execution was cancelled (Host -> Guest UI).
* Host MUST send this if tool execution was cancelled for any reason (user action,
* sampling error, classifier intervention, etc.).
*/
export interface McpUiToolCancelledNotification {
method: "ui/notifications/tool-cancelled";
params: {
/** @description Optional reason for the cancellation (e.g., "user action", "timeout"). */
reason?: string;
};
}
/**
* @description Rich context about the host environment provided to Guest UIs.
*/

View file

@ -24,6 +24,7 @@ export {
type McpUiToolInputNotification,
type McpUiToolInputPartialNotification,
type McpUiToolResultNotification,
type McpUiToolCancelledNotification,
type McpUiHostContext,
type McpUiHostContextChangedNotification,
type McpUiResourceTeardownRequest,
@ -51,6 +52,7 @@ export {
McpUiToolInputNotificationSchema,
McpUiToolInputPartialNotificationSchema,
McpUiToolResultNotificationSchema,
McpUiToolCancelledNotificationSchema,
McpUiHostContextSchema,
McpUiHostContextChangedNotificationSchema,
McpUiResourceTeardownRequestSchema,