UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

50 lines (49 loc) • 2.62 kB
import { isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse } from "@modelcontextprotocol/client"; export const MCP_STDIO_READ_BOUND = 10 * 1024 * 1024; export class McpReplyOverReadBound extends Error { bound; constructor(bound, cause) { super(`a reply from the server was larger than the ${bound}-byte read bound`, cause === undefined ? undefined : { cause }); this.name = "McpReplyOverReadBound"; this.bound = bound; } } export function overReadBoundSentence(what, serverLabel, bound, writeWarning) { return (`${what} on MCP server "${serverLabel}" got a reply that was too large to read: the server answered, but its reply was larger than the ${bound}-byte limit for one message from a stdio server, so the client did not read it and closed the connection. ` + `The call may already have been executed on the server.${writeWarning} Repeating the same call would probably meet the same limit — ask for less if the tool allows it, otherwise tell the user.`); } export function readBoundWhy(bound) { return ` (the client closed it because a reply from the server was larger than the ${bound}-byte limit for one message — it may have been the reply to this call)`; } const BREACHES = new WeakMap(); function isReadBufferOverflow(report, bound) { return report instanceof Error && report.name === "Error" && !("code" in report) && !("cause" in report) && report.message === `ReadBuffer exceeded maximum size of ${bound} bytes`; } export function watchReadBound(client, transport, bound) { const unanswered = new Set(); const send = transport.send.bind(transport); transport.send = (message, options) => { const added = []; for (const m of Array.isArray(message) ? message : [message]) { if (isJSONRPCRequest(m) && m.id !== undefined && !unanswered.has(m.id)) { unanswered.add(m.id); added.push(m.id); } } const sending = send(message, options); sending.catch(() => void added.forEach((id) => unanswered.delete(id))); return sending; }; transport.onmessage = (message) => { if ((isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) && message.id !== undefined) unanswered.delete(message.id); }; transport.onerror = (report) => { if (BREACHES.has(client) || !isReadBufferOverflow(report, bound)) return; BREACHES.set(client, { bound, sole: unanswered.size <= 1 }); }; } export function readBoundBreachOf(client) { return BREACHES.get(client); }