Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -776,16 +776,20 @@ before treating these properties as available in production.
## Live URL instructions

`browserless_live_url` creates viewer links over REST for an existing browser.
On the full HTTP surface, `action: "create"` opens an inline live viewer for
clients that advertise MCP Apps support. The original JSON result, including
It returns JSON without opening a widget for any action, including handoff
preparation, status, and close. On the full HTTP surface, use
`browserless_create_live_url({ browserId, ...options })` to create an inline live
viewer for clients that advertise MCP Apps support. This dedicated tool accepts
the same creation options without an `action` parameter. The original JSON result, including
the viewer URL, remains in `content` for clients that advertise Apps support
but do not render widgets. The widget reads its viewer URL from `_meta`; IDs
and lifetime metadata are available in `structuredContent`. Direct viewers do
not use the shared snapshot store. If a successful create cannot be embedded,
its JSON result is still returned instead of failing the mutation or creating
another link.

Non-create actions render no widget content. The viewer's local disconnect timer
Only the dedicated creation tool advertises the direct viewer widget, so lifecycle
calls do not allocate empty app windows. The viewer's local disconnect timer
uses the server-reported remaining duration, not the client's wall clock. The
backend enforces the actual link lifetime, including for delayed or restored
results; the local timer is not an authorization check.
Expand Down
140 changes: 86 additions & 54 deletions src/tools/live-url.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FastMCP, UserError } from 'fastmcp';
import type { ContentResult } from 'fastmcp';
import { z } from 'zod';
import { defineTool } from '../lib/define-tool.js';
import { defineTool, type ToolRunContext } from '../lib/define-tool.js';
import { LIVE_URL_URI, liveURLView } from '../lib/live-url-view.js';
import { getActiveSessionByHandle } from '../lib/agent-client.js';
import { prepareHandoff, findHandoff, readHandoff } from '../lib/handoff.js';
Expand Down Expand Up @@ -106,6 +106,50 @@ export const LiveURLParamsSchema = z.object({
instructionsFormat: instructionsFormatSchema.optional(),
});

const CreateLiveURLParamsSchema = LiveURLParamsSchema.omit({
action: true,
sessionId: true,
viewRef: true,
liveURLId: true,
mint: true,
}).extend({ browserId: LiveURLParamsSchema.shape.browserId.unwrap() });

async function createLiveURL(
{
client,
params,
apiUrl,
uiEnabled,
}: ToolRunContext<z.infer<typeof CreateLiveURLParamsSchema>>,
config: McpConfig,
inline: boolean,
): Promise<LiveURLCreated | ContentResult> {
const { browserId, ...options } = CreateLiveURLParamsSchema.parse(params);
if (options.interactable === true && options.instructions === undefined) {
options.instructions = DEFAULT_LIVE_URL_INSTRUCTIONS;
}
if (
options.type === 'png' &&
options.quality !== undefined &&
options.quality !== 100
) {
throw new UserError('PNG only supports explicit quality 100.');
}
const started = Date.now();
const result = await client.createLiveURL(browserId, options);
return inline && uiEnabled
? liveURLView(
result,
browserId,
apiUrl,
started,
apiUrl === config.browserlessApiUrl
? config.publicBrowserlessUrl
: undefined,
)
: result;
}

export function registerLiveURLTool(
server: FastMCP,
config: McpConfig,
Expand All @@ -124,7 +168,10 @@ export function registerLiveURLTool(
name: 'browserless_live_url',
description:
'Create, inspect, or close a live viewer link for an existing browser through REST, without an agent connection. ' +
'In MCP Apps clients, create displays the viewer inline; other clients receive the viewer URL as JSON. Direct create does not pause automation. ' +
'Returns JSON without opening a widget. Direct create does not pause automation. ' +
(inline
? 'To create a direct inline viewer in MCP Apps clients, use browserless_create_live_url instead. '
: '') +
'Use pages to list browser tabs; mint=true adds per-tab live links. Reused links may be interactive, while new bulk links are view-only and pinned to their tabs. ' +
'Pages returns targetId, url, title, active, and browserContextId. Create accepts targetId to stream a specific tab; mode follow jumps to new tabs, while tab stays on one tab. ' +
'Create options default on the server: view-only, jpeg, quality 70, not resizable, browser interface shown (hidden with targetId). ' +
Expand All @@ -140,30 +187,16 @@ export function registerLiveURLTool(
? 'Action handoff is the inline human handoff and works only when your client renders MCP Apps widgets (inline viewers in the conversation); in any other client it returns an error. If your client does not render MCP Apps widgets, or you cannot tell, do not call handoff: run the browserless_agent liveURL command with interactable: true and instructions as the last command of its call, keep that session open, give the person the returned link, and wait for them. In MCP Apps clients, call handoff with the existing agent sessionId and plain-text instructions. Keep the browser open first. This pauses automation and returns a viewRef: display it with browserless_show. Wait for the person, then use handoff_status with that viewRef; continue with a fresh snapshot in the same session only when reason is userDone. Never open a replacement browser.'
: ''),
parameters: LiveURLParamsSchema,
...(inline
? {
_meta: {
ui: { resourceUri: LIVE_URL_URI },
'openai/outputTemplate': LIVE_URL_URI,
},
}
: {}),
annotations: {
title: 'Browserless Live URL',
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true,
},
run: async ({
client,
params,
token,
apiUrl,
userId,
viewOwner,
uiEnabled,
}) => {
run: async (ctx) => {
const { client, params, token, apiUrl, userId, viewOwner, uiEnabled } =
ctx;
if (params.action === 'handoff') {
const instructions =
params.instructions ?? DEFAULT_LIVE_URL_INSTRUCTIONS;
Expand Down Expand Up @@ -207,47 +240,19 @@ export function registerLiveURLTool(
if (!view) throw new UserError(VIEW_UNAVAILABLE);
return readHandoff(view, client);
}
const {
action,
browserId,
liveURLId,
mint,
sessionId: _sessionId,
viewRef: _viewRef,
...options
} = LiveURLParamsSchema.parse(params);
const { action, browserId, liveURLId, mint } =
LiveURLParamsSchema.parse(params);
if (!browserId)
throw new UserError(
'browserId is required for create, status, close, and pages.',
);
if (action === 'pages') return client.listPages(browserId, mint);
if (action === 'create') {
if (
options.interactable === true &&
options.instructions === undefined
) {
options.instructions = DEFAULT_LIVE_URL_INSTRUCTIONS;
}
if (
options.type === 'png' &&
options.quality !== undefined &&
options.quality !== 100
) {
throw new UserError('PNG only supports explicit quality 100.');
}
const started = Date.now();
const result = await client.createLiveURL(browserId, options);
return inline && uiEnabled
? liveURLView(
result,
browserId,
apiUrl,
started,
apiUrl === config.browserlessApiUrl
? config.publicBrowserlessUrl
: undefined,
)
: result;
return createLiveURL(
{ ...ctx, params: { ...params, browserId } },
config,
false,
);
}
if (!liveURLId)
throw new UserError('liveURLId is required for status and close.');
Expand All @@ -273,4 +278,31 @@ export function registerLiveURLTool(
: content;
},
});
if (inline)
defineTool(server, config, analytics, {
name: 'browserless_create_live_url',
description:
'Create a live viewer for an existing browser and display it inline in MCP Apps clients. Other clients receive the viewer URL as JSON. ' +
'Use a running browserId, not an agent sessionId. Defaults: view-only, jpeg, quality 70, not resizable, browser interface shown (hidden with targetId). ' +
'Use browserless_live_url action pages to find targetId; mode tab stays on that tab and follow jumps to new tabs. ' +
'Creating a viewer does not keep the browser alive or pause automation. For a human handoff, use browserless_live_url action handoff, then browserless_show with its viewRef instead. ' +
'Use browserless_live_url for status and close. Do not also call its create action or browserless_show for this direct viewer.',
parameters: CreateLiveURLParamsSchema,
_meta: {
ui: { resourceUri: LIVE_URL_URI },
'openai/outputTemplate': LIVE_URL_URI,
},
annotations: {
title: 'Create Browserless Live Viewer',
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true,
},
run: (ctx) => createLiveURL(ctx, config, true),
format: (result) =>
'content' in result
? result
: [{ type: 'text' as const, text: JSON.stringify(result) }],
});
}
11 changes: 11 additions & 0 deletions test/integration/handoff-widget.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,17 @@ describe('direct agent human handoff over MCP', () => {
httpStream: { host: '127.0.0.1', port },
});
const alice = await connect();
const { tools } = await alice.listTools();
const lifecycle = tools.find(
(tool) => tool.name === 'browserless_live_url',
)!;
const show = tools.find((tool) => tool.name === 'browserless_show')!;
// The host allocates app containers from tool metadata before rendering.
// Hiding the producer's DOM cannot prevent an extra empty container.
assert.equal(lifecycle._meta?.ui, undefined);
assert.equal(lifecycle._meta?.['openai/outputTemplate'], undefined);
assert.ok((show._meta?.ui as any)?.resourceUri);
assert.ok(show._meta?.['openai/outputTemplate']);
const opened = await alice.callTool({
name: 'browserless_agent',
arguments: {
Expand Down
39 changes: 36 additions & 3 deletions test/integration/live-url-widget.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,14 @@ describe('direct live viewer over MCP HTTP', () => {
});
const ui = await connect(true);
const tool = (await ui.listTools()).tools.find(
(tool) => tool.name === 'browserless_live_url',
(tool) => tool.name === 'browserless_create_live_url',
)!;
assert.equal(tool.inputSchema.properties?.action, undefined);
assert.ok(tool.inputSchema.required?.includes('browserId'));
assert.equal(
tool._meta?.['openai/outputTemplate'],
'ui://browserless/live-url/v1.html',
);
assert.equal(
(tool._meta?.ui as any)?.resourceUri,
'ui://browserless/live-url/v1.html',
Expand Down Expand Up @@ -173,9 +179,12 @@ describe('direct live viewer over MCP HTTP', () => {
);
const call = (action: string) =>
ui.callTool({
name: 'browserless_live_url',
name:
action === 'create'
? 'browserless_create_live_url'
: 'browserless_live_url',
arguments: {
action,
...(action === 'create' ? {} : { action }),
browserId: 'browser-1',
...(action !== 'create' ? { liveURLId: 'live-1' } : {}),
},
Expand Down Expand Up @@ -220,6 +229,30 @@ describe('direct live viewer over MCP HTTP', () => {
JSON.parse((plain.content as any)[0].text).liveURL,
`${base}/e/abcdef/live/index.html?i=live-1`,
);
const plainUi = await ui.callTool({
name: 'browserless_live_url',
arguments: { action: 'create', browserId: 'browser-1' },
});
assert.equal(plainUi._meta?.payload, undefined);
assert.equal(
JSON.parse((plainUi.content as any)[0].text).liveURL,
`${base}/e/abcdef/live/index.html?i=live-1`,
);
const fallback = await legacy.callTool({
name: 'browserless_create_live_url',
arguments: { browserId: 'browser-1' },
});
assert.equal(fallback.structuredContent, undefined);
assert.equal(
JSON.parse((fallback.content as any)[0].text).liveURL,
`${base}/e/abcdef/live/index.html?i=live-1`,
);
const beforeInvalid = creates;
await assert.rejects(
ui.callTool({ name: 'browserless_create_live_url', arguments: {} }),
/browserId/,
);
assert.equal(creates, beforeInvalid);
invalid = true;
const rejected = await call('create');
assert.ok(
Expand Down
2 changes: 1 addition & 1 deletion test/integration/replay-widget.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ describe('production replay tools over real MCP HTTP', () => {
).to.deep.equal([
'browserless_show',
'browserless_performance',
'browserless_live_url',
'browserless_create_live_url',
]);
expect(
tools.find((tool) => tool.name === 'browserless_sessions')!._meta,
Expand Down
3 changes: 2 additions & 1 deletion test/integration/server.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,14 @@ describe('MCP Server Integration', () => {
if (compliant) {
expect(names).to.deep.equal(connectorNames);
} else {
expect(names).to.have.length(24);
expect(names).to.have.length(25);
expect(names).not.to.include('browserless_read_page');
expect(names).to.include.members([
...connectorNames.filter(
(name) => name !== 'browserless_read_page',
),
'browserless_agent_runs',
'browserless_create_live_url',
'browserless_stage_file',
'browserless_show',
'browserless_view_data',
Expand Down
2 changes: 1 addition & 1 deletion test/tools/annotations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ describe('tool annotations', () => {

registerSurface(server, { ...mockConfig, complianceMode });

expect(addToolSpy.callCount).to.equal(complianceMode ? 7 : 24);
expect(addToolSpy.callCount).to.equal(complianceMode ? 7 : 25);

addToolSpy.getCalls().forEach((call) => {
const tool = call.args[0];
Expand Down
11 changes: 8 additions & 3 deletions test/tools/compliance-mode.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,12 +318,17 @@ describe('compliance mode — compliant tool surface', () => {
expect(full.has('browserless_link_checkout')).to.be.true;
});

it('full HTTP adds stage_file and the handoff reader for exactly 24 tools', () => {
it('full HTTP adds file staging, handoff reader, and direct viewer for exactly 25 tools', () => {
const stdio = captureTools(false).names;
const http = captureTools(false, 'httpStream').names;
expect(http).to.have.length(24);
expect(http).to.have.length(25);
expect(http).to.deep.equal(
[...stdio, 'browserless_stage_file', 'browserless_handoff_state'].sort(),
[
...stdio,
'browserless_stage_file',
'browserless_handoff_state',
'browserless_create_live_url',
].sort(),
);
});

Expand Down