mcp-image-payload-test-server.mjs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #!/usr/bin/env node
  2. import { Buffer } from "node:buffer";
  3. import { deflateSync } from "node:zlib";
  4. import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
  5. import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
  6. import { z } from "zod";
  7. const SERVER_NAME = "zcode-image-payload-test";
  8. const SERVER_VERSION = "0.1.0";
  9. const DEFAULT_PRESET = "below_limit";
  10. const PRESETS = {
  11. tiny: 32 * 1024,
  12. below_limit: 180 * 1024,
  13. just_over_limit: 210 * 1024,
  14. large: 1024 * 1024,
  15. huge: 2 * 1024 * 1024,
  16. };
  17. const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  18. const CRC_TABLE = buildCrcTable();
  19. const server = new McpServer({
  20. name: SERVER_NAME,
  21. version: SERVER_VERSION,
  22. });
  23. server.registerTool(
  24. "emit_image",
  25. {
  26. title: "Emit image with configurable base64 size",
  27. description:
  28. "Return a valid PNG image block whose base64 payload is near the requested size. Use this to test ZCode MCP image output budgeting.",
  29. inputSchema: {
  30. preset: z
  31. .enum(["tiny", "below_limit", "just_over_limit", "large", "huge"])
  32. .optional()
  33. .describe(
  34. "Convenience size preset. below_limit is under 200 KiB; just_over_limit is over 200 KiB.",
  35. ),
  36. base64Bytes: z
  37. .number()
  38. .int()
  39. .min(1024)
  40. .max(8 * 1024 * 1024)
  41. .optional()
  42. .describe("Target base64 payload bytes. Overrides preset when provided."),
  43. label: z
  44. .string()
  45. .max(80)
  46. .optional()
  47. .describe("Optional label included in the text summary."),
  48. dataUrl: z
  49. .boolean()
  50. .optional()
  51. .describe("When true, put a data URL in the image data field instead of raw base64."),
  52. },
  53. annotations: {
  54. readOnlyHint: true,
  55. destructiveHint: false,
  56. idempotentHint: true,
  57. },
  58. },
  59. async ({ preset, base64Bytes, label, dataUrl }) => {
  60. const selectedPreset = preset ?? DEFAULT_PRESET;
  61. const targetBase64Bytes = base64Bytes ?? PRESETS[selectedPreset];
  62. const png = createPngNearBase64Size(targetBase64Bytes);
  63. const base64 = png.toString("base64");
  64. const actualBase64Bytes = Buffer.byteLength(base64, "utf8");
  65. const actualBinaryBytes = png.byteLength;
  66. const imageData = dataUrl === true ? `data:image/png;base64,${base64}` : base64;
  67. return {
  68. content: [
  69. {
  70. type: "text",
  71. text: [
  72. "ZCode MCP image payload test",
  73. `label=${label?.trim() || selectedPreset}`,
  74. `preset=${selectedPreset}`,
  75. `targetBase64Bytes=${targetBase64Bytes}`,
  76. `actualBase64Bytes=${actualBase64Bytes}`,
  77. `actualBinaryBytes=${actualBinaryBytes}`,
  78. `dataFormat=${dataUrl === true ? "data-url" : "raw-base64"}`,
  79. ].join("\n"),
  80. },
  81. {
  82. type: "image",
  83. mimeType: "image/png",
  84. data: imageData,
  85. },
  86. ],
  87. };
  88. },
  89. );
  90. await server.connect(new StdioServerTransport());
  91. function createPngNearBase64Size(targetBase64Bytes) {
  92. const basePng = createPngWithTextPayload("");
  93. if (base64Length(basePng.byteLength) >= targetBase64Bytes) {
  94. return basePng;
  95. }
  96. let low = 0;
  97. let high = Math.max(1, Math.ceil((targetBase64Bytes * 3) / 4));
  98. while (base64Length(createPngWithTextPayloadLength(high).byteLength) < targetBase64Bytes) {
  99. high *= 2;
  100. }
  101. while (low < high) {
  102. const mid = Math.floor((low + high) / 2);
  103. const candidate = createPngWithTextPayloadLength(mid);
  104. if (base64Length(candidate.byteLength) >= targetBase64Bytes) {
  105. high = mid;
  106. } else {
  107. low = mid + 1;
  108. }
  109. }
  110. return createPngWithTextPayloadLength(low);
  111. }
  112. function createPngWithTextPayloadLength(length) {
  113. return createPngWithTextPayload("z".repeat(length));
  114. }
  115. function createPngWithTextPayload(textPayload) {
  116. const width = 1;
  117. const height = 1;
  118. const ihdr = Buffer.alloc(13);
  119. ihdr.writeUInt32BE(width, 0);
  120. ihdr.writeUInt32BE(height, 4);
  121. ihdr[8] = 8;
  122. ihdr[9] = 6;
  123. ihdr[10] = 0;
  124. ihdr[11] = 0;
  125. ihdr[12] = 0;
  126. const scanline = Buffer.from([0x00, 0x2f, 0x80, 0xff, 0xff]);
  127. const idat = deflateSync(scanline, { level: 9 });
  128. const text = Buffer.from(`zcode-mcp-payload\0${textPayload}`, "latin1");
  129. return Buffer.concat([
  130. PNG_SIGNATURE,
  131. pngChunk("IHDR", ihdr),
  132. pngChunk("tEXt", text),
  133. pngChunk("IDAT", idat),
  134. pngChunk("IEND", Buffer.alloc(0)),
  135. ]);
  136. }
  137. function pngChunk(type, data) {
  138. const typeBuffer = Buffer.from(type, "ascii");
  139. const length = Buffer.alloc(4);
  140. length.writeUInt32BE(data.byteLength, 0);
  141. const crc = Buffer.alloc(4);
  142. crc.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])), 0);
  143. return Buffer.concat([length, typeBuffer, data, crc]);
  144. }
  145. function base64Length(byteLength) {
  146. return Math.ceil(byteLength / 3) * 4;
  147. }
  148. function buildCrcTable() {
  149. const table = new Uint32Array(256);
  150. for (let i = 0; i < table.length; i += 1) {
  151. let crc = i;
  152. for (let bit = 0; bit < 8; bit += 1) {
  153. crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
  154. }
  155. table[i] = crc >>> 0;
  156. }
  157. return table;
  158. }
  159. function crc32(buffer) {
  160. let crc = 0xffffffff;
  161. for (const byte of buffer) {
  162. crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
  163. }
  164. return (crc ^ 0xffffffff) >>> 0;
  165. }