sampling.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import { z } from "zod";
  2. import { MCP_APPS_IMAGE_MAX_BYTES, MCP_APPS_IMAGE_MIME_TYPES } from "./contract.js";
  3. export const MCP_APPS_SAMPLING_TIMEOUT_MS = 60_000;
  4. export const MCP_APPS_SAMPLING_TRANSPORT_TIMEOUT_MS = 65_000;
  5. export const MCP_APPS_SAMPLING_MAX_BYTES = 8 * 1024 * 1024;
  6. export const MCP_APPS_SAMPLING_MAX_BLOCKS = 64;
  7. export const MCP_APPS_SAMPLING_MAX_PER_SESSION = 4;
  8. export const MCP_APPS_SAMPLING_MAX_PER_AGENT = 8;
  9. export const MCP_APPS_SAMPLING_MAX_OPERATIONS = 4096;
  10. const utf8Bytes = (text: string) => new TextEncoder().encode(text).byteLength;
  11. const annotations = z
  12. .object({
  13. audience: z.array(z.enum(["user", "assistant"])).optional(),
  14. priority: z.number().min(0).max(1).optional(),
  15. lastModified: z.string().optional(),
  16. })
  17. .strict()
  18. .optional();
  19. const samplingBlockSchema = z.discriminatedUnion("type", [
  20. z
  21. .object({
  22. type: z.literal("text"),
  23. text: z.string().max(MCP_APPS_SAMPLING_MAX_BYTES),
  24. annotations,
  25. _meta: z.record(z.string(), z.unknown()).optional(),
  26. })
  27. .strict(),
  28. z
  29. .object({
  30. type: z.literal("image"),
  31. mimeType: z.enum(MCP_APPS_IMAGE_MIME_TYPES),
  32. data: z
  33. .string()
  34. .min(1)
  35. .max(Math.ceil(MCP_APPS_IMAGE_MAX_BYTES / 3) * 4)
  36. // 重复四字符分组会在 MiB 级图片上耗尽 V8 正则栈;平坦字符检查保持线性。
  37. .refine((data) => data.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(data))
  38. .refine((data) => decodedBytes(data) <= MCP_APPS_IMAGE_MAX_BYTES),
  39. annotations,
  40. _meta: z.record(z.string(), z.unknown()).optional(),
  41. })
  42. .strict(),
  43. ]);
  44. const priority = z.number().min(0).max(1).optional();
  45. /** 只开放宿主确实实现的官方子集;不静默剥除 tools/audio/模型配置等字段。 */
  46. export const mcpAppsSamplingParamsSchema = z
  47. .object({
  48. messages: z
  49. .array(
  50. z
  51. .object({
  52. role: z.enum(["user", "assistant"]),
  53. content: z.union([
  54. samplingBlockSchema,
  55. z.array(samplingBlockSchema).min(1).max(MCP_APPS_SAMPLING_MAX_BLOCKS),
  56. ]),
  57. })
  58. .strict(),
  59. )
  60. .min(1)
  61. .max(MCP_APPS_SAMPLING_MAX_BLOCKS),
  62. systemPrompt: z.string().max(MCP_APPS_SAMPLING_MAX_BYTES).optional(),
  63. maxTokens: z.number().int().positive().safe(),
  64. includeContext: z.literal("none").optional(),
  65. modelPreferences: z
  66. .object({
  67. hints: z
  68. .array(z.object({ name: z.string().max(256).optional() }).strict())
  69. .max(16)
  70. .optional(),
  71. costPriority: priority,
  72. speedPriority: priority,
  73. intelligencePriority: priority,
  74. })
  75. .strict()
  76. .optional(),
  77. metadata: z.record(z.string(), z.unknown()).optional(),
  78. _meta: z.record(z.string(), z.unknown()).optional(),
  79. })
  80. .strict()
  81. .superRefine((params, ctx) => {
  82. const blocks = params.messages.flatMap((message) =>
  83. Array.isArray(message.content) ? message.content : [message.content],
  84. );
  85. let bytes = utf8Bytes(params.systemPrompt ?? "");
  86. for (const block of blocks)
  87. bytes += block.type === "image" ? decodedBytes(block.data) : utf8Bytes(block.text);
  88. // metadata 不转发给 provider,但仍计入边界预算,避免任意扩展字段绕过载荷限制。
  89. const metadataBytes = utf8Bytes(
  90. JSON.stringify({
  91. metadata: params.metadata,
  92. _meta: params._meta,
  93. blockMetadata: blocks.map((b) => ({ _meta: b._meta, annotations: b.annotations })),
  94. }),
  95. );
  96. if (
  97. blocks.length > MCP_APPS_SAMPLING_MAX_BLOCKS ||
  98. bytes + metadataBytes > MCP_APPS_SAMPLING_MAX_BYTES
  99. )
  100. ctx.addIssue({ code: "custom", message: "Sampling content exceeds host limits" });
  101. });
  102. function decodedBytes(data: string): number {
  103. return (data.length * 3) / 4 - (data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0);
  104. }
  105. export const mcpAppsSamplingResultSchema = z
  106. .object({
  107. role: z.literal("assistant"),
  108. model: z.string().min(1),
  109. content: z
  110. .object({ type: z.literal("text"), text: z.string().max(MCP_APPS_SAMPLING_MAX_BYTES) })
  111. .strict(),
  112. stopReason: z.string().min(1),
  113. })
  114. .strict();
  115. export type McpAppsSamplingParams = z.infer<typeof mcpAppsSamplingParamsSchema>;
  116. export type McpAppsSamplingResult = z.infer<typeof mcpAppsSamplingResultSchema>;