Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions packages/worker/src/mcp/capabilities/apps/domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { uiGetAppCapability } from './ui-get-app.ts'
import { uiListAppsCapability } from './ui-list-apps.ts'
import { uiLoadAppSourceCapability } from './ui-load-app-source.ts'
import { uiSaveAppCapability } from './ui-save-app.ts'
import { uiUpdateAppCapability } from './ui-update-app.ts'

export const appsDomain = defineDomain({
name: capabilityDomainNames.apps,
Expand All @@ -16,6 +17,7 @@ export const appsDomain = defineDomain({
uiGetAppCapability,
uiListAppsCapability,
uiLoadAppSourceCapability,
uiUpdateAppCapability,
uiDeleteAppCapability,
],
})
1 change: 1 addition & 0 deletions packages/worker/src/mcp/capabilities/apps/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ export { uiGetAppCapability } from './ui-get-app.ts'
export { uiListAppsCapability } from './ui-list-apps.ts'
export { uiLoadAppSourceCapability } from './ui-load-app-source.ts'
export { uiSaveAppCapability } from './ui-save-app.ts'
export { uiUpdateAppCapability } from './ui-update-app.ts'

export const appsCapabilities = appsDomain.capabilities
153 changes: 153 additions & 0 deletions packages/worker/src/mcp/capabilities/apps/ui-update-app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { z } from 'zod'
import { buildSavedUiUrl } from '#worker/ui-artifact-urls.ts'
import { defineDomainCapability } from '#mcp/capabilities/define-domain-capability.ts'
import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts'
import { type CapabilityContext } from '#mcp/capabilities/types.ts'
import { requireMcpUser } from '#mcp/capabilities/meta/require-user.ts'
import { buildUiArtifactEmbedText } from '#mcp/ui-artifacts-embed.ts'
import { getUiArtifactById, updateUiArtifact } from '#mcp/ui-artifacts-repo.ts'
import { upsertUiArtifactVector } from '#mcp/ui-artifacts-vectorize.ts'

function parseStringArray(raw: string): Array<string> {
try {
const value = JSON.parse(raw) as unknown
if (!Array.isArray(value)) return []
return value.filter((entry): entry is string => typeof entry === 'string')
} catch {
return []
}
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

const inputSchema = z
.object({
app_id: z
.string()
.min(1)
.describe('Saved UI artifact id returned by ui_save_app.'),
title: z
.string()
.min(1)
.optional()
.describe('Short title for the saved UI artifact.'),
description: z
.string()
.min(1)
.optional()
.describe('What the saved app does and when it is useful.'),
keywords: z
.array(z.string())
.optional()
.describe('Extra search keywords for discovery in the search tool.'),
code: z
.string()
.min(1)
.optional()
.describe(
'App source for the generic MCP UI shell. Prefer a self-contained HTML document or fragment so the generated app owns the visible UI. Legacy `javascript` source is still supported for previously saved apps.',
),
runtime: z
.enum(['html', 'javascript'])
.optional()
.describe(
'Source format accepted by the generic UI shell. Prefer `html`; `javascript` is kept for legacy saved apps.',
),
search_text: z
.string()
.optional()
.describe(
Comment on lines +48 to +51

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Allow explicit search_text clearing in update input.

Line 54 currently accepts only string | undefined, so callers cannot clear search_text to NULL via ui_update_app, despite repo support for null updates.

Suggested patch
-		search_text: z
-			.string()
-			.optional()
+		search_text: z
+			.string()
+			.nullable()
+			.optional()
 			.describe(
 				'Optional retrieval-only text that improves search recall without being part of the visible app description.',
 			),

Also applies to: 111-113

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/capabilities/apps/ui-update-app.ts` around lines 54 -
57, The schema for the update input in ui-update-app.ts currently defines
search_text as z.string().optional(), preventing callers from explicitly
clearing it to null; update the schema for the search_text field (both
occurrences around the search_text lines) to accept null as well by changing the
Zod type to include nullable (e.g., z.string().nullable().optional()) so the
ui_update_app input allows string | null | undefined.

'Optional retrieval-only text that improves search recall without being part of the visible app description.',
),
})
.refine(
(value) =>
value.title !== undefined ||
value.description !== undefined ||
value.keywords !== undefined ||
value.code !== undefined ||
value.runtime !== undefined ||
value.search_text !== undefined,
{
message: 'Provide at least one field to update.',
},
)

const outputSchema = z.object({
app_id: z.string(),
runtime: z.enum(['html', 'javascript']),
hosted_url: z.string().url(),
})

export const uiUpdateAppCapability = defineDomainCapability(
capabilityDomainNames.apps,
{
name: 'ui_update_app',
description:
'Update an existing saved UI artifact owned by the signed-in user. Only the fields provided will be changed.',
keywords: ['ui', 'app', 'artifact', 'update', 'edit', 'modify'],
readOnly: false,
idempotent: false,
destructive: false,
inputSchema,
outputSchema,
async handler(args, ctx: CapabilityContext) {
const user = requireMcpUser(ctx.callerContext)
const updates: Parameters<typeof updateUiArtifact>[3] = {}

if (args.title !== undefined) {
updates.title = args.title
}
if (args.description !== undefined) {
updates.description = args.description
}
if (args.keywords !== undefined) {
updates.keywords = JSON.stringify(args.keywords)
}
if (args.code !== undefined) {
updates.code = args.code
}
if (args.runtime !== undefined) {
updates.runtime = args.runtime
}
if (args.search_text !== undefined) {
updates.search_text = args.search_text
}

const updated = await updateUiArtifact(
ctx.env.APP_DB,
user.userId,
args.app_id,
updates,
)
if (!updated) {
throw new Error('Saved UI artifact not found for this user.')
}

const refreshed = await getUiArtifactById(
ctx.env.APP_DB,
user.userId,
args.app_id,
)
if (!refreshed) {
throw new Error('Saved UI artifact not found after update.')
}

await upsertUiArtifactVector(ctx.env, {
appId: refreshed.id,
userId: user.userId,
embedText: buildUiArtifactEmbedText({
title: refreshed.title,
description: refreshed.description,
keywords: parseStringArray(refreshed.keywords),
searchText: refreshed.search_text,
runtime: refreshed.runtime,
}),
})
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

return {
app_id: refreshed.id,
runtime: refreshed.runtime,
hosted_url: buildSavedUiUrl(ctx.callerContext.baseUrl, refreshed.id),
}
},
},
)
76 changes: 76 additions & 0 deletions packages/worker/src/mcp/mcp-server-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1445,3 +1445,79 @@ test('mcp server deletes saved ui app artifacts', async () => {
const apps = listPayload?.apps as Array<{ app_id?: string }> | undefined
expect(apps?.some((app) => app.app_id === appId)).toBe(false)
})

test('mcp server updates saved ui app artifacts', async () => {
await using database = await createTestDatabase()
await using server = await startDevServer(database.persistDir)
await using mcpClient = await createMcpClient(server.origin, database.user)

const saveResult = await mcpClient.client.callTool({
name: 'execute',
arguments: {
code: `async () =>
await codemode.ui_save_app({
title: 'Original App',
description: 'Original app description.',
keywords: ['original', 'ui'],
code: '<main><h1>Original</h1></main>',
})`,
},
})
const saveStructured = (saveResult as CallToolResult).structuredContent as
| {
result?: Record<string, unknown>
}
| undefined
const savedApp = saveStructured?.result as Record<string, unknown> | undefined
const appId = typeof savedApp?.app_id === 'string' ? savedApp.app_id : null
expect(appId).not.toBeNull()

const updateResult = await mcpClient.client.callTool({
name: 'execute',
arguments: {
code: `async () =>
await codemode.ui_update_app({
app_id: ${JSON.stringify(appId)},
title: 'Updated App',
description: 'Updated description.',
keywords: ['updated', 'ui'],
code: '<main><h1>Updated</h1></main>',
runtime: 'javascript',
search_text: 'updated searchable text',
})`,
},
})
const updateStructured = (updateResult as CallToolResult).structuredContent as
| {
result?: Record<string, unknown>
}
| undefined
const updatePayload = updateStructured?.result as
| Record<string, unknown>
| undefined
expect(updatePayload?.app_id).toBe(appId)
expect(updatePayload?.runtime).toBe('javascript')
expect(updatePayload?.hosted_url).toBe(`${server.origin}/ui/${appId}`)

const getResult = await mcpClient.client.callTool({
name: 'execute',
arguments: {
code: `async () =>
await codemode.ui_get_app({ app_id: ${JSON.stringify(appId)} })`,
},
})
const getStructured = (getResult as CallToolResult).structuredContent as
| {
result?: Record<string, unknown>
}
| undefined
const getPayload = getStructured?.result as
| Record<string, unknown>
| undefined
expect(getPayload?.title).toBe('Updated App')
expect(getPayload?.description).toBe('Updated description.')
expect(getPayload?.keywords).toEqual(['updated', 'ui'])
expect(getPayload?.code).toBe('<main><h1>Updated</h1></main>')
expect(getPayload?.runtime).toBe('javascript')
expect(getPayload?.search_text).toBe('updated searchable text')
})
48 changes: 48 additions & 0 deletions packages/worker/src/mcp/ui-artifacts-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,54 @@ export async function deleteUiArtifact(
return (out.meta.changes ?? 0) > 0
}

export async function updateUiArtifact(
db: D1Database,
userId: string,
artifactId: string,
updates: Partial<
Pick<
UiArtifactRow,
'title' | 'description' | 'keywords' | 'code' | 'runtime' | 'search_text'
>
>,
): Promise<boolean> {
const assignments: Array<string> = []
const values: Array<unknown> = []
const addAssignment = (column: string, value: unknown) => {
assignments.push(`${column} = ?`)
values.push(value)
}

if (updates.title !== undefined) {
addAssignment('title', updates.title)
}
if (updates.description !== undefined) {
addAssignment('description', updates.description)
}
if (updates.keywords !== undefined) {
addAssignment('keywords', updates.keywords)
}
if (updates.code !== undefined) {
addAssignment('source_code', updates.code)
}
if (updates.runtime !== undefined) {
addAssignment('source_type', updates.runtime)
}
if (updates.search_text !== undefined) {
addAssignment('search_text', updates.search_text ?? null)
}

addAssignment('updated_at', new Date().toISOString())

const out = await db
.prepare(
`UPDATE ui_artifacts SET ${assignments.join(', ')} WHERE id = ? AND user_id = ?`,
)
.bind(...values, artifactId, userId)
.run()
return (out.meta.changes ?? 0) > 0
}

export async function listUiArtifactsByUserId(
db: D1Database,
userId: string,
Expand Down
Loading