diff --git a/packages/worker/src/mcp/capabilities/apps/domain.ts b/packages/worker/src/mcp/capabilities/apps/domain.ts index da9c7865d1..f0b1978adc 100644 --- a/packages/worker/src/mcp/capabilities/apps/domain.ts +++ b/packages/worker/src/mcp/capabilities/apps/domain.ts @@ -5,7 +5,6 @@ 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, @@ -17,7 +16,6 @@ export const appsDomain = defineDomain({ uiGetAppCapability, uiListAppsCapability, uiLoadAppSourceCapability, - uiUpdateAppCapability, uiDeleteAppCapability, ], }) diff --git a/packages/worker/src/mcp/capabilities/apps/index.ts b/packages/worker/src/mcp/capabilities/apps/index.ts index ed5e585cdd..d319de10eb 100644 --- a/packages/worker/src/mcp/capabilities/apps/index.ts +++ b/packages/worker/src/mcp/capabilities/apps/index.ts @@ -6,6 +6,5 @@ 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 diff --git a/packages/worker/src/mcp/capabilities/apps/ui-save-app.ts b/packages/worker/src/mcp/capabilities/apps/ui-save-app.ts index 5e50099b5b..f9b1ee9fc8 100644 --- a/packages/worker/src/mcp/capabilities/apps/ui-save-app.ts +++ b/packages/worker/src/mcp/capabilities/apps/ui-save-app.ts @@ -3,7 +3,12 @@ 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 { deleteUiArtifact, insertUiArtifact } from '#mcp/ui-artifacts-repo.ts' +import { errorFields, logMcpEvent } from '#mcp/observability.ts' +import { + deleteUiArtifact, + insertUiArtifact, + updateUiArtifact, +} from '#mcp/ui-artifacts-repo.ts' import { buildUiArtifactEmbedText } from '#mcp/ui-artifacts-embed.ts' import { upsertUiArtifactVector } from '#mcp/ui-artifacts-vectorize.ts' import { requireMcpUser } from '#mcp/capabilities/meta/require-user.ts' @@ -13,6 +18,13 @@ import { } from '#mcp/ui-artifact-parameters.ts' const inputSchema = z.object({ + app_id: z + .string() + .min(1) + .optional() + .describe( + 'Optional saved UI artifact id to update in place. Omit to create a new saved app.', + ), title: z.string().min(1).describe('Short title for the saved UI artifact.'), description: z .string() @@ -50,8 +62,8 @@ export const uiSaveAppCapability = defineDomainCapability( { name: 'ui_save_app', description: - 'Save a generated UI artifact for the signed-in user so it can be reopened later by app_id without sending the source back through the model context.', - keywords: ['ui', 'app', 'artifact', 'save', 'persist', 'mcp app'], + 'Create or replace a saved UI artifact for the signed-in user so it can be reopened later by app_id without sending the source back through the model context.', + keywords: ['ui', 'app', 'artifact', 'save', 'persist', 'update', 'mcp app'], readOnly: false, idempotent: false, destructive: false, @@ -59,20 +71,43 @@ export const uiSaveAppCapability = defineDomainCapability( outputSchema, async handler(args, ctx: CapabilityContext) { const user = requireMcpUser(ctx.callerContext) - const appId = crypto.randomUUID() - const now = new Date().toISOString() + const isUpdate = args.app_id !== undefined + const appId = args.app_id ?? crypto.randomUUID() const parameters = normalizeUiArtifactParameters(args.parameters) - await insertUiArtifact(ctx.env.APP_DB, { - id: appId, - user_id: user.userId, - title: args.title, - description: args.description, - code: args.code, - runtime: args.runtime, - parameters: parameters ? JSON.stringify(parameters) : null, - created_at: now, - updated_at: now, - }) + const serializedParameters = parameters + ? JSON.stringify(parameters) + : null + + if (isUpdate) { + const updated = await updateUiArtifact( + ctx.env.APP_DB, + user.userId, + appId, + { + title: args.title, + description: args.description, + code: args.code, + runtime: args.runtime, + parameters: serializedParameters, + }, + ) + if (!updated) { + throw new Error('Saved UI artifact not found for this user.') + } + } else { + const now = new Date().toISOString() + await insertUiArtifact(ctx.env.APP_DB, { + id: appId, + user_id: user.userId, + title: args.title, + description: args.description, + code: args.code, + runtime: args.runtime, + parameters: serializedParameters, + created_at: now, + updated_at: now, + }) + } try { await upsertUiArtifactVector(ctx.env, { @@ -87,8 +122,33 @@ export const uiSaveAppCapability = defineDomainCapability( }), }) } catch (cause) { - await deleteUiArtifact(ctx.env.APP_DB, user.userId, appId) - throw cause + if (!isUpdate) { + await deleteUiArtifact(ctx.env.APP_DB, user.userId, appId) + throw cause + } + + const { errorName, errorMessage } = errorFields(cause) + logMcpEvent({ + category: 'mcp', + tool: 'capability', + capabilityName: 'ui_save_app', + domain: capabilityDomainNames.apps, + outcome: 'failure', + durationMs: 0, + baseUrl: ctx.callerContext.baseUrl, + hasUser: true, + failurePhase: 'handler', + message: + 'Failed to refresh saved app vector index after in-place update.', + errorName, + errorMessage, + cause, + context: { + userId: user.userId, + appId, + isUpdate, + }, + }) } return { diff --git a/packages/worker/src/mcp/capabilities/apps/ui-update-app.ts b/packages/worker/src/mcp/capabilities/apps/ui-update-app.ts deleted file mode 100644 index caad3ae8ae..0000000000 --- a/packages/worker/src/mcp/capabilities/apps/ui-update-app.ts +++ /dev/null @@ -1,147 +0,0 @@ -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' -import { - normalizeUiArtifactParameters, - parseUiArtifactParameters, - uiArtifactParameterSchema, -} from '#mcp/ui-artifact-parameters.ts' - -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.'), - 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.', - ), - parameters: z - .array(uiArtifactParameterSchema) - .optional() - .describe( - 'Optional parameter definitions for reusable saved apps. Resolved values are exposed at runtime on the imported `kodyWidget.params` API from `@kody/ui-utils`.', - ), - }) - .refine( - (value) => - value.title !== undefined || - value.description !== undefined || - value.code !== undefined || - value.runtime !== undefined || - value.parameters !== 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(), - parameters: z.array(uiArtifactParameterSchema).nullable(), -}) - -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[3] = {} - - if (args.title !== undefined) { - updates.title = args.title - } - if (args.description !== undefined) { - updates.description = args.description - } - if (args.code !== undefined) { - updates.code = args.code - } - if (args.runtime !== undefined) { - updates.runtime = args.runtime - } - if (args.parameters !== undefined) { - const parameters = normalizeUiArtifactParameters(args.parameters) - updates.parameters = parameters ? JSON.stringify(parameters) : null - } - - 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.') - } - - try { - await upsertUiArtifactVector(ctx.env, { - appId: refreshed.id, - userId: user.userId, - embedText: buildUiArtifactEmbedText({ - title: refreshed.title, - description: refreshed.description, - code: refreshed.code, - runtime: refreshed.runtime, - parameters: parseUiArtifactParameters(refreshed.parameters), - }), - }) - } catch { - // Vector refresh should not fail the primary update. - } - - return { - app_id: refreshed.id, - runtime: refreshed.runtime, - hosted_url: buildSavedUiUrl(ctx.callerContext.baseUrl, refreshed.id), - parameters: parseUiArtifactParameters(refreshed.parameters), - } - }, - }, -) diff --git a/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts b/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts index 1c8a31d9fb..5a98252979 100644 --- a/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts +++ b/packages/worker/src/mcp/mcp-server.mcp-e2e.test.ts @@ -589,7 +589,6 @@ test('mcp server searches capabilities', async () => { 'code', ]) expect(saveApp?.readOnly).toBeUndefined() - expect(saveApp?.inputFields).toBeUndefined() const textOutput = (result as CallToolResult).content.find( @@ -1840,7 +1839,7 @@ test('mcp server deletes saved ui app artifacts', async () => { expect(apps?.some((app) => app.app_id === appId)).toBe(false) }) -test('mcp server updates saved ui app artifacts', async () => { +test('mcp server upserts saved ui app artifacts through ui_save_app', async () => { await using database = await createTestDatabase() await using server = await startDevServer(database.persistDir) await using mcpClient = await createMcpClient(server.origin, database.user) @@ -1869,7 +1868,7 @@ test('mcp server updates saved ui app artifacts', async () => { name: 'execute', arguments: { code: `async () => - await codemode.ui_update_app({ + await codemode.ui_save_app({ app_id: ${JSON.stringify(appId)}, title: 'Updated App', description: 'Updated description.', @@ -1909,4 +1908,25 @@ test('mcp server updates saved ui app artifacts', async () => { expect(getPayload?.description).toBe('Updated description.') expect(getPayload?.code).toBe('

Updated

') expect(getPayload?.runtime).toBe('javascript') + + const listResult = await mcpClient.client.callTool({ + name: 'execute', + arguments: { + code: `async () => await codemode.ui_list_apps({})`, + }, + }) + const listStructured = (listResult as CallToolResult).structuredContent as + | { + result?: Record + } + | undefined + const listPayload = listStructured?.result as + | Record + | undefined + const apps = listPayload?.apps as + | Array<{ app_id?: string; title?: string }> + | undefined + expect(apps).toHaveLength(1) + expect(apps?.[0]?.app_id).toBe(appId) + expect(apps?.[0]?.title).toBe('Updated App') }) diff --git a/packages/worker/src/mcp/observability.ts b/packages/worker/src/mcp/observability.ts index 68817ad905..d4f23fa9ba 100644 --- a/packages/worker/src/mcp/observability.ts +++ b/packages/worker/src/mcp/observability.ts @@ -20,6 +20,8 @@ export type McpObservabilityPayload = { registeredCapabilityCount?: number errorName?: string errorMessage?: string + message?: string + context?: Record timestamp: string } diff --git a/packages/worker/src/mcp/observability.workers.test.ts b/packages/worker/src/mcp/observability.workers.test.ts index 746e9c0d9a..b6a432f17b 100644 --- a/packages/worker/src/mcp/observability.workers.test.ts +++ b/packages/worker/src/mcp/observability.workers.test.ts @@ -184,3 +184,82 @@ test('ui_save_app capability logs success for valid invocation', async () => { expect(event.outcome).toBe('success') expect(event.failurePhase).toBeUndefined() }) + +test('ui_save_app logs vector refresh failure for in-place updates and still succeeds', async () => { + const originalInfo = console.info + const payloads: Array = [] + console.info = ((tag: unknown, json?: unknown) => { + if (tag === 'mcp-event' && typeof json === 'string') { + payloads.push(json) + } + }) as typeof console.info + try { + const handler = capabilityMap['ui_save_app'].handler + const result = await handler( + { + app_id: 'app-1', + title: 'Observed app', + description: 'Observation test app.', + code: '

Observed app

', + }, + { + env: { + APP_DB: { + prepare() { + return { + bind() { + return { + run: async () => ({ + meta: { changes: 1 }, + }), + } + }, + } + }, + }, + CAPABILITY_VECTOR_INDEX: { + upsert: async () => { + throw new Error('vector refresh failed') + }, + }, + AI: { + run: async () => ({ + data: [Array.from({ length: 384 }, () => 0)], + }), + }, + } as unknown as Env, + callerContext: createMcpCallerContext({ + baseUrl: 'https://example.com', + user: { + userId: 'user-1', + email: 'user@example.com', + }, + }), + }, + ) + expect((result as { app_id: string }).app_id).toBe('app-1') + } finally { + console.info = originalInfo + } + + expect(payloads.length).toBe(2) + const driftEvent = JSON.parse(payloads[0]!) as Record + const driftContext = driftEvent.context as Record | undefined + expect(driftEvent.outcome).toBe('failure') + expect(driftEvent.failurePhase).toBe('handler') + expect(driftEvent.errorName).toBe('Error') + expect(driftEvent.errorMessage).toBe('vector refresh failed') + expect(driftEvent.message).toBe( + 'Failed to refresh saved app vector index after in-place update.', + ) + expect(driftEvent.capabilityName).toBe('ui_save_app') + expect(driftContext).toEqual({ + userId: 'user-1', + appId: 'app-1', + isUpdate: true, + }) + + const successEvent = JSON.parse(payloads[1]!) as Record + expect(successEvent.outcome).toBe('success') + expect(successEvent.capabilityName).toBe('ui_save_app') +})