All files / packages/design-system-2-site/src/lib/zeroheight mcp-client.js

89.58% Statements 43/48
63.33% Branches 19/30
88.23% Functions 15/17
92.3% Lines 36/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134                                    2x   6x 2x 2x                   2x 2x 2x 3x 3x   2x 1x                               5x 5x   5x 5x 7x 1x 1x   7x 8x 5x 1x   4x 4x 6x 6x 5x 5x                       1x               2x 2x 2x                   2x                     2x     1x         2x                
/**
 * Minimal Zeroheight MCP client: JSON-RPC `tools/call` over plain HTTP.
 *
 * The server needs no session or OAuth handshake; the URL itself is the
 * credential, so it must never appear in logs or error messages.
 */
 
import { HttpError, createRateLimiter, retryAfterMs, withRetry } from './http.js';
 
export class McpToolError extends Error {}
 
/**
 * Pull the JSON-RPC message out of a response body. The server answers with
 * SSE (`data: {...}` lines) or plain JSON.
 * @param {string} raw
 * @returns {any}
 */
export function parseRpcBody(raw) {
  const data = raw
    .split('\n')
    .filter((line) => line.startsWith('data:'))
    .map((line) => line.slice(5).trim());
  return JSON.parse(data.length ? data[data.length - 1] : raw);
}
 
/**
 * Join the text items of a tool result, throwing on tool or RPC errors.
 * @param {any} message
 * @param {string} name
 * @returns {string}
 */
export function toolText(message, name) {
  Iif (message.error) throw new McpToolError(`${name}: ${message.error.message ?? 'RPC error'}`);
  const result = message.result ?? {};
  const text = (result.content ?? [])
    .filter((/** @type {any} */ c) => c.type === 'text')
    .map((/** @type {any} */ c) => c.text)
    .join('');
  if (result.isError) throw new McpToolError(`${name}: ${text}`);
  return text;
}
 
/**
 * @typedef {{ uri: string, mimeType: string, data: Buffer } | { uri: string, error: string }} AssetResult
 */
 
/**
 * Match `get-page-asset` content items back to the requested URIs. Each
 * failed URI comes back as a `<uri>: <message>` text item; the image items
 * follow the order of the URIs that succeeded.
 * @param {any} message
 * @param {string[]} uris
 * @returns {AssetResult[]}
 */
export function toolAssets(message, uris) {
  Iif (message.error) throw new McpToolError(`get-page-asset: ${message.error.message ?? 'RPC error'}`);
  const content = message.result?.content ?? [];
  /** @type {Map<string, string>} */
  const errors = new Map();
  for (const c of content) {
    if (c.type !== 'text') continue;
    const m = String(c.text).match(/^(zeroheight:\/\/\S+?): (.*)$/s);
    Eif (m) errors.set(m[1], m[2]);
  }
  const blobs = content.filter((/** @type {any} */ c) => c.type === 'image');
  const ok = uris.filter((u) => !errors.has(u));
  if (blobs.length !== ok.length) {
    throw new McpToolError(`get-page-asset: got ${blobs.length} asset(s) for ${ok.length} URI(s)`);
  }
  let i = 0;
  return uris.map((uri) => {
    const error = errors.get(uri);
    if (error !== undefined) return { uri, error };
    const blob = blobs[i++];
    return { uri, mimeType: blob.mimeType, data: Buffer.from(blob.data, 'base64') };
  });
}
 
/**
 * @param {{ url: string, fetchImpl?: typeof fetch, limiter?: { acquire(): Promise<void> } }} opts
 */
export function createMcpClient({
  url,
  fetchImpl = fetch,
  limiter = createRateLimiter({ limit: 28, windowMs: 30_000 }),
}) {
  let id = 0;
 
  /**
   * @param {string} name
   * @param {Record<string, unknown>} args
   * @returns {Promise<any>} the JSON-RPC message
   */
  async function rpc(name, args) {
    return withRetry(async () => {
      await limiter.acquire();
      const res = await fetchImpl(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: ++id,
          method: 'tools/call',
          params: { name, arguments: args },
        }),
      });
      Eif (!res.ok) throw new HttpError(`MCP ${name}: HTTP ${res.status}`, res.status, retryAfterMs(res));
      return parseRpcBody(await res.text());
    });
  }
 
  /**
   * @param {string} name
   * @param {Record<string, unknown>} args
   * @returns {Promise<string>}
   */
  async function callTool(name, args) {
    return toolText(await rpc(name, args), name);
  }
 
  return {
    callTool,
    /** @returns {Promise<any>} parsed `list-pages` payload */
    listPages: async () => JSON.parse(await callTool('list-pages', {})),
    /** @param {number} pageId */
    getPage: (pageId) => callTool('get-page', { pageId }),
    /**
     * @param {string[]} assetUris `zeroheight://image/<pageId>/<hash>` URIs from `get-page`
     * @returns {Promise<AssetResult[]>}
     */
    getPageAssets: async (assetUris) => toolAssets(await rpc('get-page-asset', { assetUris }), assetUris),
  };
}