diff --git a/packages/mcp/mcp-client/README.i18n.yaml b/packages/mcp/mcp-client/README.i18n.yaml index b4d1c4a46f..0a144f1e24 100644 --- a/packages/mcp/mcp-client/README.i18n.yaml +++ b/packages/mcp/mcp-client/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/mcp/mcp-client/README.md -README.md: d9f81a79b8c54b1437d051f46a72196fd84742c9 -README.zh.md: d6f3e9337c80e5535bb1239dfb7752f3485dbde3 +README.md: b324fafdc5873e3595c8b1beff72c5643f0be0ee +README.zh.md: 2559e7edccb244528229c5e64f8a800a5ba87700 diff --git a/packages/mcp/mcp-client/README.md b/packages/mcp/mcp-client/README.md index d9f81a79b8..b324fafdc5 100644 --- a/packages/mcp/mcp-client/README.md +++ b/packages/mcp/mcp-client/README.md @@ -131,7 +131,7 @@ The SDK receives tool-list changes through legacy notifications or a modern subs ### Tool execution internals -A tool call uses the SDK with the raw name, complete tool definition, JSON arguments, abort signal, and configured timeout. The SDK owns protocol validation, advertised output-schema validation, and modern request headers. Canonical success is `{ content: JsonValue[], structuredContent? }`, preserving valid MCP JSON blocks for programmatic and PTC mode callers. An MCP `isError` result throws before image persistence. The bridge validates each image batch before saving it; a refusal projects every image as diagnostic text. +A tool call uses the SDK with the raw name, complete tool definition, JSON arguments, abort signal, and configured timeout. The SDK owns protocol validation, advertised output-schema validation, and modern request headers. Canonical success is `{ content: JsonValue[], structuredContent? }`, preserving valid MCP JSON blocks for programmatic and PTC mode callers. An MCP `isError` result throws before image persistence. Image inputs must use canonical base64; decoded bytes must re-encode to the exact input. The bridge validates each image batch before saving it; a refusal projects every image as diagnostic text. ### Environment scrubbing (stdio) diff --git a/packages/mcp/mcp-client/README.zh.md b/packages/mcp/mcp-client/README.zh.md index d6f3e9337c..2559e7edcc 100644 --- a/packages/mcp/mcp-client/README.zh.md +++ b/packages/mcp/mcp-client/README.zh.md @@ -131,7 +131,7 @@ SDK 通过旧版通知或现代协议订阅接收工具列表变化。监督器 ### 工具执行内部细节 -工具调用向 SDK 提供原始名称、完整工具定义、JSON 参数、取消信号及配置的超时。SDK 负责协议校验、已声明输出 schema 的校验和现代协议请求 header。成功结果规范值为 `{ content: JsonValue[], structuredContent? }`,为编程调用方及 PTC 模式保留有效的 MCP JSON 块。MCP `isError` 结果会在图片持久化前抛出。桥接器在保存前校验整批图片;拒绝时将每张图片投影为诊断文本。 +工具调用向 SDK 提供原始名称、完整工具定义、JSON 参数、取消信号及配置的超时。SDK 负责协议校验、已声明输出 schema 的校验和现代协议请求 header。成功结果规范值为 `{ content: JsonValue[], structuredContent? }`,为编程调用方及 PTC 模式保留有效的 MCP JSON 块。MCP `isError` 结果会在图片持久化前抛出。图片数据必须使用规范 base64,解码后重新编码的结果必须与输入完全一致。桥接器在保存前校验整批图片;拒绝时将每张图片投影为诊断文本。 ### 环境清洗(stdio) diff --git a/packages/mcp/mcp-client/src/tools.ts b/packages/mcp/mcp-client/src/tools.ts index 9e7b5c0ab5..1dfb9ca55b 100644 --- a/packages/mcp/mcp-client/src/tools.ts +++ b/packages/mcp/mcp-client/src/tools.ts @@ -61,9 +61,6 @@ const IMAGE_MEDIA_TYPES: readonly ImageMediaType[] = [ 'image/gif', ] -/** Canonical RFC 4648 base64, excluding whitespace and URL-safe aliases. */ -const CANONICAL_BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/ - /** * Derive the model-facing public name for one MCP tool. * @@ -333,9 +330,6 @@ function decodeImage(block: ImageContent): SaveImageAttachment { if (!isImageMediaType(block.mimeType)) { throw new Error('the declared media type is not PNG, JPEG, WebP, or GIF') } - if (!CANONICAL_BASE64.test(block.data)) { - throw new Error('the image data is not canonical base64') - } const data = Buffer.from(block.data, 'base64') if (data.toString('base64') !== block.data) { throw new Error('the image data is not canonical base64') diff --git a/packages/mcp/mcp-client/tests/mcp-client.spec.ts b/packages/mcp/mcp-client/tests/mcp-client.spec.ts index 4a330850b8..2c4eed8168 100644 --- a/packages/mcp/mcp-client/tests/mcp-client.spec.ts +++ b/packages/mcp/mcp-client/tests/mcp-client.spec.ts @@ -10,7 +10,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { PostToolDecision } from '@deepseek-ai/dsh-tools' -import { publicToolName, syncTools, type ToolBridgeOptions } from '@deepseek-ai/dsh-mcp-client/src/tools.ts' +import { createMcpToolDefinition, publicToolName, syncTools, type ToolBridgeOptions } from '@deepseek-ai/dsh-mcp-client/src/tools.ts' import { createTransport } from '@deepseek-ai/dsh-mcp-client/src/transport.ts' import type { Config } from '@deepseek-ai/dsh-mcp-client' @@ -70,9 +70,14 @@ const IMAGE_LIMITS: ImageAttachmentLimits = { /** Attachment fake that records exact decoded batches while using the real batch contract. */ class RecordingAttachmentStore extends AttachmentStore { - readonly imageLimits = IMAGE_LIMITS + readonly imageLimits: ImageAttachmentLimits readonly saved: SaveImageAttachment[] = [] + constructor(ctx: Context, limits: Partial = {}) { + super(ctx) + this.imageLimits = { ...IMAGE_LIMITS, ...limits } + } + validateImage(_input: SaveImageAttachment): Promise { return Promise.resolve() } @@ -111,9 +116,11 @@ class ImageCatalogAdapter extends LlmAdapter { } } -async function mountRichRegistry(): Promise<{ ctx: Context; attachments: RecordingAttachmentStore }> { +async function mountRichRegistry( + limits: Partial = {}, +): Promise<{ ctx: Context; attachments: RecordingAttachmentStore }> { const ctx = await mountRegistry() - await ctx.plugin(RecordingAttachmentStore) + await ctx.plugin(RecordingAttachmentStore, limits) await ctx.plugin(LlmRuntime) ctx.llm.registerAdapter(['visual'], new ImageCatalogAdapter()) return { ctx, attachments: ctx.attachments as RecordingAttachmentStore } @@ -483,6 +490,40 @@ describe('tool execution', () => { expect(result.value).toEqual({ content: blocks }) }) + it('decodes a 4 MiB canonical base64 payload for attachment admission', async () => { + // The recording store isolates base64 decoding; the attachment provider owns raster validation. + const bytes = Buffer.alloc(4 * 1024 * 1024, 0x41) + const rich = await mountRichRegistry({ maxImageBytes: bytes.length, maxMessageImageBytes: bytes.length }) + try { + const blocks = [ + { type: 'text', text: 'Captured window.' }, + { type: 'image', mimeType: 'image/png', data: bytes.toString('base64') }, + ] satisfies JsonValue[] + rich.ctx.effect(() => rich.ctx.tools.register(createMcpToolDefinition(rich.ctx, { + name: 'large_image', rawName: 'large_image', description: 'Return a generated image payload.', + inputSchema: { type: 'object' }, call: async () => ({ content: blocks }), + }))) + const result = await rich.ctx.tools.execute({ + signal: testToolSignal, callId: ToolCallId('large-image'), + name: 'large_image', arguments: {}, agent: agentOn() as never, + }) + + expect(result.isError).toBe(false) + expect(rich.attachments.saved).toHaveLength(1) + expect(Buffer.from(rich.attachments.saved[0]!.data).equals(bytes)).toBe(true) + expect(result.content).toMatchObject([ + { type: 'text', text: 'Captured window.' }, + { type: 'image', attachment: { + mediaType: 'image/png', bytes: bytes.length, + } }, + ]) + if (result.isError) throw new Error('expected a canonical image result') + expect(result.value).toEqual({ content: blocks }) + } finally { + await rich.ctx.fiber.dispose() + } + }) + it('rejects a malformed image batch before storing any member', async () => { const rich = await mountRichRegistry() const blocks = [ @@ -511,12 +552,12 @@ describe('tool execution', () => { it('rejects unsupported media and base64 aliases as one atomic batch', async () => { const rich = await mountRichRegistry() + const invalidBase64 = ['AB==', 'AQ', 'AQ=', 'AQ===', 'AQ==AA==', 'AQ==\n', 'A Q==', '_w==', '-w==', 'A?Q=='] const client = createMockClient( [{ name: 'img', inputSchema: { type: 'object' } }], { content: [ { type: 'image', mimeType: 'image/tiff', data: 'AQ==' }, - { type: 'image', mimeType: 'image/png', data: 'AB==' }, - { type: 'image', mimeType: 'image/png', data: 'AQ' }, + ...invalidBase64.map(data => ({ type: 'image', mimeType: 'image/png', data })), ] }, ) @@ -530,10 +571,11 @@ describe('tool execution', () => { }) expect(rich.attachments.saved).toEqual([]) - expect(result.content).toHaveLength(3) + expect(result.content).toHaveLength(1 + invalidBase64.length) expect(textAt(result.content, 0)).toContain('not PNG, JPEG, WebP, or GIF') - expect(textAt(result.content, 1)).toContain('not canonical base64') - expect(textAt(result.content, 2)).toContain('not canonical base64') + for (let index = 0; index < invalidBase64.length; index++) { + expect(textAt(result.content, index + 1)).toContain('not canonical base64') + } }) it('does not admit images for a route without declared image input', async () => {