Skip to content

Commit c7887c0

Browse files
authored
Add more robust base64 check (#786)
1 parent 0d54517 commit c7887c0

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

src/types.ts

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -458,11 +458,31 @@ export const TextResourceContentsSchema = ResourceContentsSchema.extend({
458458
text: z.string(),
459459
});
460460

461+
462+
/**
463+
* A Zod schema for validating Base64 strings that is more performant and
464+
* robust for very large inputs than the default regex-based check. It avoids
465+
* stack overflows by using the native `atob` function for validation.
466+
*/
467+
const Base64Schema = z.string().refine(
468+
(val) => {
469+
try {
470+
// atob throws a DOMException if the string contains characters
471+
// that are not part of the Base64 character set.
472+
atob(val);
473+
return true;
474+
} catch {
475+
return false;
476+
}
477+
},
478+
{ message: "Invalid Base64 string" },
479+
);
480+
461481
export const BlobResourceContentsSchema = ResourceContentsSchema.extend({
462482
/**
463483
* A base64-encoded string representing the binary data of the item.
464484
*/
465-
blob: z.string().base64(),
485+
blob: Base64Schema,
466486
});
467487

468488
/**
@@ -718,7 +738,7 @@ export const ImageContentSchema = z
718738
/**
719739
* The base64-encoded image data.
720740
*/
721-
data: z.string().base64(),
741+
data: Base64Schema,
722742
/**
723743
* The MIME type of the image. Different providers may support different image types.
724744
*/
@@ -741,7 +761,7 @@ export const AudioContentSchema = z
741761
/**
742762
* The base64-encoded audio data.
743763
*/
744-
data: z.string().base64(),
764+
data: Base64Schema,
745765
/**
746766
* The MIME type of the audio. Different providers may support different audio types.
747767
*/
@@ -894,7 +914,7 @@ export const ToolSchema = BaseMetadataSchema.extend({
894914
})
895915
.passthrough(),
896916
/**
897-
* An optional JSON Schema object defining the structure of the tool's output returned in
917+
* An optional JSON Schema object defining the structure of the tool's output returned in
898918
* the structuredContent field of a CallToolResult.
899919
*/
900920
outputSchema: z.optional(

0 commit comments

Comments
 (0)