Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(chat): send MCP image results to the model as images, not base64 text

Mads Dorup37b126194539
diff --git a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
index 5193d60aa..0c01c9af4 100644
--- a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
+++ b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
@@ -397,3 +397,36 @@ it('keeps a Cowork run on its chosen model when the viewed model changes between
await drain(await send(transport, [user('next', 'Next step')]))
expect(vi.mocked(ModelFactory.createModel).mock.calls.map(([id]) => id)).toEqual(['gpt', 'gpt'])
})
+
+// The filesystem server's `read_media_file` result, stored as its MCP content
+// array. Sent as-is, the SDK stringifies it and the model gets the base64 as
+// text; the transport must turn it into a tool image sentinel first.
+it('sends an MCP image result as a tool image, not as base64 text', async () => {
+ streamTextCalls.length = 0
+ provider.provider = 'openai'
+ h.providerId = 'openai'
+ selectedModel.id = 'gpt'
+ selectedModel.capabilities = ['tools', 'vision']
+ const transport = new CustomChatTransport('you are jan', 'thread-1')
+ await drain(
+ await send(transport, [
+ user('u1', 'look at the frame'),
+ {
+ id: 'a1',
+ role: 'assistant',
+ parts: [
+ {
+ type: 'tool-read_media_file',
+ toolCallId: 'c1',
+ state: 'output-available',
+ input: { path: '/frames/a.png' },
+ output: [{ type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }],
+ },
+ ],
+ } as unknown as UIMessage,
+ ])
+ )
+ const sent = JSON.stringify(streamTextCalls[0].messages)
+ expect(sent).toContain('__JAN_TOOL_IMAGE__data:image/png;base64,iVBORw0KGgo=')
+ expect(sent).not.toContain('mimeType')
+})
diff --git a/web-app/src/lib/__tests__/tool-image-sentinel.test.ts b/web-app/src/lib/__tests__/tool-image-sentinel.test.ts
index adb330282..68afa9ebb 100644
--- a/web-app/src/lib/__tests__/tool-image-sentinel.test.ts
+++ b/web-app/src/lib/__tests__/tool-image-sentinel.test.ts
@@ -1,11 +1,14 @@
import { describe, it, expect } from 'vitest'
+import type { UIMessage } from '@ai-sdk/react'
import {
+ encodeMcpToolImages,
encodeToolImageSentinel,
hasToolImageSentinel,
splitToolImageSentinels,
stripToolImageSentinels,
} from '../tool-image-sentinel'
import { decodeToolImageSentinelsInBody } from '../model-factory'
+import { stripUnsupportedImageParts } from '../custom-chat-transport'
const png = 'data:image/png;base64,iVBORw0KGgo='
@@ -75,3 +78,88 @@ describe('decodeToolImageSentinelsInBody', () => {
expect(body.messages[1].content).toBe('plain result')
})
})
+
+describe('encodeMcpToolImages', () => {
+ const b64 = 'iVBORw0KGgo='
+ const mcpTool = (output: unknown): UIMessage =>
+ ({
+ id: 'a1',
+ role: 'assistant',
+ parts: [
+ {
+ type: 'tool-read_media_file',
+ toolCallId: 'c1',
+ state: 'output-available',
+ input: { path: '/tmp/a.png' },
+ output,
+ },
+ ],
+ }) as unknown as UIMessage
+ const outputOf = (messages: UIMessage[]) =>
+ (messages[0].parts[0] as { output: unknown }).output
+
+ // What the filesystem server's `read_media_file` returns: the image alone.
+ it('turns an image-only MCP result into a caption plus a sentinel', () => {
+ const out = encodeMcpToolImages([
+ mcpTool([{ type: 'image', data: b64, mimeType: 'image/png' }]),
+ ])
+ const body = {
+ messages: [{ role: 'tool', tool_call_id: 'c1', content: outputOf(out) }],
+ }
+ decodeToolImageSentinelsInBody(body)
+ expect(body.messages[0].content).toEqual([
+ { type: 'text', text: 'The tool returned 1 image.' },
+ { type: 'image_url', image_url: { url: png, detail: 'auto' } },
+ ])
+ })
+
+ it('keeps the text items ahead of the images', () => {
+ const out = encodeMcpToolImages([
+ mcpTool({
+ content: [
+ { type: 'text', text: 'Rendered frame' },
+ { type: 'image', data: b64, mimeType: 'image/png' },
+ ],
+ }),
+ ])
+ expect(splitToolImageSentinels(outputOf(out) as string)).toEqual([
+ { type: 'text', text: 'Rendered frame' },
+ { type: 'image_url', image_url: { url: png, detail: 'auto' } },
+ ])
+ })
+
+ // The sentinel regex wants a lowercase type and unbroken base64.
+ it('normalises wrapped base64 and an upper-case media type', () => {
+ const out = encodeMcpToolImages([
+ mcpTool([{ type: 'image', data: 'iVBORw0K\nGgo=', mimeType: 'IMAGE/PNG' }]),
+ ])
+ expect(splitToolImageSentinels(outputOf(out) as string)).toContainEqual({
+ type: 'image_url',
+ image_url: { url: png, detail: 'auto' },
+ })
+ })
+
+ it('leaves text-only results and other messages untouched', () => {
+ const textOnly = mcpTool([{ type: 'text', text: 'file contents' }])
+ const user = {
+ id: 'u1',
+ role: 'user',
+ parts: [{ type: 'text', text: 'hi' }],
+ } as UIMessage
+ const out = encodeMcpToolImages([textOnly, user])
+ expect(out[0]).toBe(textOnly)
+ expect(out[1]).toBe(user)
+ })
+
+ it('keeps no base64 once a model without vision strips the sentinel', () => {
+ const out = stripUnsupportedImageParts(
+ encodeMcpToolImages([
+ mcpTool([{ type: 'image', data: b64, mimeType: 'image/png' }]),
+ ]),
+ false
+ )
+ expect(outputOf(out)).toBe(
+ 'The tool returned 1 image. (image omitted: the model has no vision)'
+ )
+ })
+})
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 8d72a84b9..6aaa1a4a2 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -13,6 +13,7 @@ import {
} from 'ai'
import { repairToolArgs } from './toolCallRepair'
import {
+ encodeMcpToolImages,
hasToolImageSentinel,
stripToolImageSentinels,
} from './tool-image-sentinel'
@@ -1532,7 +1533,9 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
this.encodeVideoAttachments(
this.encodeAudioAttachments(
stripUnsupportedImageParts(
- this.mapUserInlineAttachments(effectiveMessages),
+ encodeMcpToolImages(
+ this.mapUserInlineAttachments(effectiveMessages)
+ ),
modelSupportsVision
)
)
diff --git a/web-app/src/lib/tool-image-sentinel.ts b/web-app/src/lib/tool-image-sentinel.ts
index 9c86c4940..c763d6d9b 100644
--- a/web-app/src/lib/tool-image-sentinel.ts
+++ b/web-app/src/lib/tool-image-sentinel.ts
@@ -6,6 +6,8 @@
// rides inside the tool part's output text as a sentinel and the request fetch
// decodes it back into content parts.
+import type { UIMessage } from '@ai-sdk/react'
+
const PREFIX = ' __JAN_TOOL_IMAGE__'
const SUFFIX = ' '
@@ -63,3 +65,83 @@ export function stripToolImageSentinels(
SENTINEL_REGEX.lastIndex = 0
return text.replace(SENTINEL_REGEX, replacement)
}
+
+type McpContentItem = {
+ type?: string
+ text?: string
+ data?: string
+ mimeType?: string
+}
+
+/** The content array of an MCP result, stored bare or as `{ content }`. */
+function mcpContentItems(output: unknown): McpContentItem[] | null {
+ if (Array.isArray(output)) return output
+ if (output && typeof output === 'object') {
+ const content = (output as { content?: unknown }).content
+ if (Array.isArray(content)) return content
+ }
+ return null
+}
+
+function isMcpImage(
+ item: McpContentItem | null | undefined
+): item is McpContentItem & { data: string } {
+ return item?.type === 'image' && typeof item.data === 'string' && !!item.data
+}
+
+function mcpImageDataUrl(item: McpContentItem & { data: string }): string {
+ // The sentinel regex takes a lowercase media type and an unbroken base64
+ // run, so normalise both: some servers wrap long base64 across lines.
+ const data = item.data.replace(/\s+/g, '')
+ if (data.startsWith('data:')) return data
+ const mime = item.mimeType?.toLowerCase().startsWith('image/')
+ ? item.mimeType.toLowerCase()
+ : 'image/png'
+ return `data:${mime};base64,${data}`
+}
+
+function mcpOutputWithSentinels(items: McpContentItem[]): string {
+ const text: string[] = []
+ const images: string[] = []
+ for (const item of items) {
+ if (isMcpImage(item)) images.push(mcpImageDataUrl(item))
+ else if (item?.type === 'text' && typeof item.text === 'string')
+ text.push(item.text)
+ else text.push(JSON.stringify(item))
+ }
+ const head =
+ text.join('\n') ||
+ `The tool returned ${images.length} image${images.length === 1 ? '' : 's'}.`
+ return head + images.map(encodeToolImageSentinel).join('')
+}
+
+/**
+ * Re-encodes MCP tool results that carry images (e.g. the filesystem server's
+ * `read_media_file`) so the model sees the image, not its base64.
+ *
+ * Chat stores an MCP result as its raw content array, which keeps the tool
+ * card's image preview working. But the AI SDK stringifies structured tool
+ * output, so sent as-is an image item reaches the model as megabytes of base64
+ * text: useless to the model, and enough to blow a provider's input limit. An
+ * output with at least one image item becomes its text plus one sentinel per
+ * image instead, the same form Cowork's tool images take, so the request fetch
+ * decodes it into `image_url` parts and `stripUnsupportedImageParts` drops it
+ * for a model without vision. Text-only results are left as they are.
+ */
+export function encodeMcpToolImages(messages: UIMessage[]): UIMessage[] {
+ return messages.map((message) => {
+ if (message.role !== 'assistant' || !Array.isArray(message.parts)) {
+ return message
+ }
+ let touched = false
+ const parts = message.parts.map((part) => {
+ const type = (part as { type?: string }).type
+ if (type !== 'dynamic-tool' && !type?.startsWith('tool-')) return part
+ const items = mcpContentItems((part as { output?: unknown }).output)
+ if (!items?.some(isMcpImage)) return part
+ touched = true
+ return { ...part, output: mcpOutputWithSentinels(items) } as typeof part
+ })
+ return touched ? ({ ...message, parts } as UIMessage) : message
+ })
+}