diff --git a/CHANGELOG.md b/CHANGELOG.md index 24353ec..7252192 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ All notable changes to this project will be documented in this file. +## [Unreleased] + +### Fixed + +- **Registry and docs responses are read within a size limit and timeouts.** + - A body over 50 MB is cancelled, and the tool returns an error instead of parsing it. + - A request may wait 30 seconds for headers and 30 seconds between chunks of its body, and a call takes at most 2 minutes, its retries included. A server that sends headers and then stalls no longer hangs the call, and a slow download that keeps arriving still finishes. A body read that ignores the abort signal, as some fetch replacements' do, still ends at the timeout. + - Documentation pages and the docs index use the same limits; they had no timeout before. +- **Error responses keep their status.** A 401, 403 or 404 whose body breaks off, stalls or is too large is still reported as that status, without a retry. +- **JSON bodies that start with a byte-order mark parse again**, as they did with `response.json()`. +- **A long `Retry-After` is not waited on.** When a server asks to wait longer than the backoff allows (10 seconds), the call returns rate limited instead of sleeping. +- **`lpm_docs` reports failed pages.** A search where no matching page could be read returns an error instead of an empty answer, and one where some failed names them after the pages it read. +- **`lpm_browse_source` lists a long tree 2,000 paths at a time.** + - A larger tree comes with `treeTotal`, `treeOffset`, `treeTruncated`, and a `treeSummary` counting files by top-level entry; pass the new `treeOffset` argument for the next page, so every path can be reached. A summary of more than 100 entries says so. + - With `path`, a tree too large to list whole is scoped to that directory and names it in `treeScope`. A `path` with no paths under it lists the whole package and says so. + - Before, up to 20,000 paths went to the model at once. +- **The session cache holds at most 500 entries**, dropping the least recently used. Its size must be a positive integer. + ## [0.3.0] - 2026-11-08 ### Changed diff --git a/lib/__tests__/api.test.js b/lib/__tests__/api.test.js index a8dcd5d..0cbf583 100644 --- a/lib/__tests__/api.test.js +++ b/lib/__tests__/api.test.js @@ -1,5 +1,12 @@ +import { Readable } from "node:stream" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" -import { apiGet, registryGet } from "../api.js" +import { apiGet, registryGet, textGet } from "../api.js" +import { + MAX_RESPONSE_BYTES, + REQUEST_TIMEOUT_MS, + REQUEST_TOTAL_TIMEOUT_MS, + RETRY_MAX_DELAY_MS, +} from "../constants.js" const mockFetch = vi.fn() @@ -127,6 +134,333 @@ describe("api", () => { }) }) + describe("response bodies", () => { + const encoder = new TextEncoder() + const tooLarge = new RegExp( + `larger than ${MAX_RESPONSE_BYTES / (1024 * 1024)} MB`, + ) + + /** A body that never ends, and counts how often it was read and cancelled. */ + function endlessBody() { + const chunk = encoder.encode(`"${"x".repeat(256 * 1024)}",`) + const stats = { pulls: 0, cancels: 0 } + const body = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode("[")) + }, + pull(controller) { + stats.pulls++ + controller.enqueue(chunk) + }, + cancel() { + stats.cancels++ + }, + }) + return { body, stats } + } + + /** A body that sends `parts`, one every `everyMs`, then ends. */ + function slowBody(parts, everyMs, signal) { + return new ReadableStream({ + async start(controller) { + signal?.addEventListener("abort", () => + controller.error(signal.reason), + ) + for (const part of parts) { + await new Promise(resolve => setTimeout(resolve, everyMs)) + if (signal?.aborted) return + controller.enqueue(encoder.encode(part)) + } + controller.close() + }, + }) + } + + /** A body that sends `part` and then neither ends nor sends more. */ + function stalledBody(part, signal) { + return new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(part)) + signal.addEventListener("abort", () => + controller.error(signal.reason), + ) + }, + }) + } + + afterEach(() => { + vi.useRealTimers() + }) + + it("stops reading a body past the size limit and reports it without retrying", async () => { + const { body, stats } = endlessBody() + mockFetch.mockImplementation(async () => new Response(body)) + + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(mockFetch).toHaveBeenCalledTimes(1) + expect(stats.cancels).toBe(1) + expect(result.ok).toBe(false) + expect(result.data.error).toMatch(tooLarge) + }) + + it("doesn't read a body whose declared size is past the limit", async () => { + const { body, stats } = endlessBody() + mockFetch.mockImplementation( + async () => + new Response(body, { + headers: { "content-length": String(MAX_RESPONSE_BYTES + 1) }, + }), + ) + + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(stats.pulls).toBe(0) + expect(stats.cancels).toBe(1) + expect(result.data.error).toMatch(tooLarge) + }) + + it("bounds a body without a stream reader, as fetch replacements give", async () => { + function* endless() { + yield Buffer.from("[") + for (;;) yield Buffer.alloc(256 * 1024, 0x20) + } + const body = Readable.from(endless()) + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + body, + headers: { get: () => null }, + json: () => Promise.reject(new Error("must not parse unbounded")), + }) + + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(result.data.error).toMatch(tooLarge) + expect(body.destroyed).toBe(true) + }) + + it("times out a body that stalls after its headers, on each attempt", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + mockFetch.mockImplementation( + async (_url, init) => + new Response(stalledBody('{"versions":{', init.signal)), + ) + + const pending = apiGet("https://lpm.dev/api/test", null) + await vi.advanceTimersByTimeAsync((REQUEST_TIMEOUT_MS + 10_000) * 3) + const result = await pending + + expect(mockFetch).toHaveBeenCalledTimes(3) + expect(result).toEqual({ + ok: false, + status: 0, + data: { error: "Request timed out" }, + }) + }) + + it("lets a slow download finish while it keeps arriving", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + const gap = REQUEST_TIMEOUT_MS - 5_000 + mockFetch.mockImplementationOnce( + async (_url, init) => + new Response(slowBody(['{"a":', "1", "}"], gap, init.signal)), + ) + + const pending = apiGet("https://lpm.dev/api/test", null) + await vi.advanceTimersByTimeAsync(gap * 3 + 1_000) + + expect(gap * 3).toBeGreaterThan(REQUEST_TIMEOUT_MS) + expect(await pending).toEqual({ ok: true, status: 200, data: { a: 1 } }) + }) + + it("ends a download that trickles past the total timeout, which spans retries", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + const gap = REQUEST_TIMEOUT_MS - 5_000 + const parts = Array.from( + { length: Math.ceil(REQUEST_TOTAL_TIMEOUT_MS / gap) + 2 }, + () => " ", + ) + mockFetch.mockImplementation( + async (_url, init) => new Response(slowBody(parts, gap, init.signal)), + ) + + let settled = false + const pending = apiGet("https://lpm.dev/api/test", null).finally(() => { + settled = true + }) + await vi.advanceTimersByTimeAsync(REQUEST_TOTAL_TIMEOUT_MS - 1) + expect(settled).toBe(false) + await vi.advanceTimersByTimeAsync(2) + + expect(await pending).toEqual({ + ok: false, + status: 0, + data: { error: "Request timed out" }, + }) + expect(mockFetch).toHaveBeenCalledTimes(1) + }) + + it("doesn't wait out a retry past the total timeout", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + mockFetch.mockImplementation( + async (_url, init) => + new Response(stalledBody("{", init.signal), { status: 200 }), + ) + + const pending = apiGet("https://lpm.dev/api/test", null) + await vi.advanceTimersByTimeAsync(REQUEST_TOTAL_TIMEOUT_MS + 1) + + expect(await pending).toEqual({ + ok: false, + status: 0, + data: { error: "Request timed out" }, + }) + }) + + it("times out a body whose reader ignores the abort signal", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + let cancelled = 0 + const reader = { + read: () => new Promise(() => {}), + cancel: async () => { + cancelled++ + }, + } + mockFetch.mockResolvedValue({ + ok: true, + status: 200, + body: { getReader: () => reader }, + headers: { get: () => null }, + }) + + const pending = apiGet("https://lpm.dev/api/test", null) + await vi.advanceTimersByTimeAsync(REQUEST_TOTAL_TIMEOUT_MS + 1) + + expect(await pending).toEqual({ + ok: false, + status: 0, + data: { error: "Request timed out" }, + }) + expect(cancelled).toBeGreaterThan(0) + }) + + it("reads a JSON body that starts with a byte-order mark, as fetch does", async () => { + mockFetch.mockImplementationOnce( + async () => new Response('\uFEFF{"name":"valid"}'), + ) + + expect(await apiGet("https://lpm.dev/api/test", null)).toEqual({ + ok: true, + status: 200, + data: { name: "valid" }, + }) + }) + + it("keeps an auth failure's status when its body breaks off or is too large, without retrying", async () => { + const broken = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode('{"err')) + controller.error(new TypeError("terminated")) + }, + }) + mockFetch.mockImplementationOnce( + async () => new Response(broken, { status: 401 }), + ) + expect(await apiGet("https://lpm.dev/api/test", "t")).toEqual({ + ok: false, + status: 401, + data: {}, + }) + expect(mockFetch).toHaveBeenCalledTimes(1) + + mockFetch.mockImplementationOnce( + async () => new Response(endlessBody().body, { status: 403 }), + ) + expect(await apiGet("https://lpm.dev/api/test", "t")).toEqual({ + ok: false, + status: 403, + data: {}, + }) + }) + + it("keeps a not-found status when its body is too large", async () => { + mockFetch.mockImplementationOnce( + async () => new Response(endlessBody().body, { status: 404 }), + ) + + expect(await apiGet("https://lpm.dev/api/test", null)).toEqual({ + ok: false, + status: 404, + data: {}, + }) + }) + + it("cancels the body of a response it retries", async () => { + const { body, stats } = endlessBody() + mockFetch + .mockImplementationOnce(async () => new Response(body, { status: 503 })) + .mockImplementationOnce(async () => new Response('{"ok":true}')) + + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(result).toEqual({ ok: true, status: 200, data: { ok: true } }) + expect(stats.cancels).toBe(1) + }) + + it("answers rate limited at once when the server asks to wait longer than the backoff allows", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + const seconds = Math.ceil(RETRY_MAX_DELAY_MS / 1000) + 1 + mockFetch.mockImplementationOnce( + async () => + new Response("", { + status: 429, + headers: { "Retry-After": String(seconds) }, + }), + ) + + // Resolves without any timer advancing, so nothing waited. + const result = await apiGet("https://lpm.dev/api/test", null) + + expect(result).toEqual({ + ok: false, + status: 429, + data: { error: "Rate limited" }, + }) + expect(mockFetch).toHaveBeenCalledTimes(1) + }) + + it("reads text bodies within the same limit and timeouts", async () => { + mockFetch.mockImplementationOnce( + async () => new Response("\uFEFF# Docs\n", { status: 200 }), + ) + expect(await textGet("https://lpm.dev/api/docs")).toEqual({ + ok: true, + status: 200, + text: "# Docs\n", + }) + + mockFetch.mockImplementationOnce( + async () => new Response(endlessBody().body), + ) + const oversized = await textGet("https://lpm.dev/api/docs") + expect(oversized.ok).toBe(false) + expect(oversized.error).toMatch(tooLarge) + + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + mockFetch.mockImplementationOnce( + async (_url, init) => new Response(stalledBody("# Do", init.signal)), + ) + const pending = textGet("https://lpm.dev/api/docs") + await vi.advanceTimersByTimeAsync(REQUEST_TIMEOUT_MS + 1) + expect(await pending).toEqual({ + ok: false, + status: 0, + error: "Request timed out", + }) + }) + }) + describe("registryGet", () => { it("prepends /api/registry to the path", async () => { mockFetch.mockResolvedValueOnce(jsonResponse({ ok: true })) diff --git a/lib/__tests__/cache.test.js b/lib/__tests__/cache.test.js index 3e72e9c..d08d166 100644 --- a/lib/__tests__/cache.test.js +++ b/lib/__tests__/cache.test.js @@ -70,4 +70,28 @@ describe("MemoryCache", () => { afterEach(() => { vi.useRealTimers() }) + + it("keeps at most maxEntries, dropping the least recently used", () => { + const cache = new MemoryCache({ maxEntries: 2 }) + cache.set("a", 1, 60_000) + cache.set("b", 2, 60_000) + expect(cache.get("a")).toBe(1) + cache.set("c", 3, 60_000) + + expect(cache.get("b")).toBeUndefined() + expect(cache.get("a")).toBe(1) + expect(cache.get("c")).toBe(3) + expect(cache.size).toBe(2) + }) + + it.each([ + 0, + -1, + 1.5, + Number.POSITIVE_INFINITY, + ])("rejects %s as its size", maxEntries => { + expect(() => new MemoryCache({ maxEntries })).toThrow( + "maxEntries must be a positive integer", + ) + }) }) diff --git a/lib/__tests__/tools/browse-source.test.js b/lib/__tests__/tools/browse-source.test.js index 5a9458e..9939a93 100644 --- a/lib/__tests__/tools/browse-source.test.js +++ b/lib/__tests__/tools/browse-source.test.js @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest" import { MemoryCache } from "../../cache.js" +import { MAX_SOURCE_TREE_ENTRIES } from "../../constants.js" import { browseSource } from "../../tools/browse-source.js" vi.mock("../../api.js", () => ({ @@ -61,6 +62,137 @@ describe("browseSource tool", () => { expect(result.content[0].text).toContain("Authentication required") }) + async function browse(params, tree, base = MOCK_TREE_RESPONSE) { + registryGet.mockResolvedValueOnce({ + ok: true, + status: 200, + data: { ...base, tree }, + }) + const result = await browseSource( + { name: "alice.ui-kit", ...params }, + createContext(), + ) + return JSON.parse(result.content[0].text) + } + + const files = (count, make) => + Array.from({ length: count }, (_, index) => make(index)) + + it("lists a long tree a page at a time, with its total and a summary by top-level entry", async () => { + const tree = [ + "README.md", + ...files(2_500, index => `dist/chunk-${index}.js`), + "package.json", + "src/index.js", + "src/button.jsx", + ] + + const first = await browse({}, tree) + expect(first.tree).toEqual(tree.slice(0, MAX_SOURCE_TREE_ENTRIES)) + expect(first).toMatchObject({ + treeTotal: 2_504, + treeOffset: 0, + treeScope: null, + treeTruncated: true, + }) + expect(first.treeSummary).toEqual([ + { path: "dist/", files: 2_500 }, + { path: "src/", files: 2 }, + { path: "README.md", files: 1 }, + { path: "package.json", files: 1 }, + ]) + expect(first.warning).toMatch(/paths 1–2000 of 2504\. Pass treeOffset 2000/) + + const second = await browse({ treeOffset: 2_000 }, tree) + expect(second.tree).toEqual(tree.slice(2_000)) + expect(second.tree).toContain("src/button.jsx") + expect(second.treeTruncated).toBe(false) + expect(second.warning).toMatch(/paths 2001–2504 of 2504\./) + }) + + it("can list every path, so none hides behind the summary's limit", async () => { + const tree = [ + ...files( + 2_100, + index => + `d${String(Math.floor(index / 21)).padStart(3, "0")}/f${index}.js`, + ), + "z-hidden/index.js", + ] + + const first = await browse({}, tree) + expect(first.treeSummary).toHaveLength(100) + expect(first.treeSummaryTruncated).toBe(true) + expect(first.warning).toMatch( + /100 largest of its 101 entries; page through the tree/, + ) + + const second = await browse({ treeOffset: first.tree.length }, tree) + expect(second.tree).toContain("z-hidden/index.js") + }) + + it("scopes a long tree to the requested directory, and says so", async () => { + const tree = [ + ...files(2_500, index => `dist/chunk-${index}.js`), + "src/index.js", + "src/button.jsx", + ] + + const data = await browse({ path: "/src/" }, tree, MOCK_FILES_RESPONSE) + + expect(data.tree).toEqual(["src/index.js", "src/button.jsx"]) + expect(data).toMatchObject({ + treeScope: "src", + treeTotal: 2, + treeTruncated: false, + }) + expect(data.files).toHaveLength(2) + }) + + it("lists the whole tree when the requested directory has no paths", async () => { + const tree = files(2_500, index => `dist/chunk-${index}.js`) + + const data = await browse({ path: "./src" }, tree) + + expect(data.treeScope).toBeNull() + expect(data.treeTotal).toBe(2_500) + expect(data.warning).toMatch( + /No paths are under \.\/src; the tree lists the whole package/, + ) + }) + + it("summarizes the requested directory, counting files, not directory entries", async () => { + const tree = [ + "dist", + "dist/esm", + ...files( + 2_200, + index => `dist/${index % 2 ? "esm" : "cjs"}/chunk-${index}.js`, + ), + ] + + const data = await browse({ path: "dist" }, tree) + + expect(data.treeTotal).toBe(2_202) + expect(data.treeSummary).toEqual([ + { path: "dist/cjs/", files: 1_100 }, + { path: "dist/esm/", files: 1_100 }, + ]) + expect(data.warning).toMatch(/under dist/) + }) + + it("rejects a negative or fractional treeOffset", async () => { + for (const treeOffset of [-1, 1.5]) { + const result = await browseSource( + { name: "alice.ui-kit", treeOffset }, + createContext(), + ) + expect(result.isError).toBe(true) + expect(result.content[0].text).toContain("treeOffset") + } + expect(registryGet).not.toHaveBeenCalled() + }) + it("returns file tree when no path specified", async () => { registryGet.mockResolvedValueOnce({ ok: true, diff --git a/lib/__tests__/tools/docs.test.js b/lib/__tests__/tools/docs.test.js new file mode 100644 index 0000000..a0e1f76 --- /dev/null +++ b/lib/__tests__/tools/docs.test.js @@ -0,0 +1,127 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" +import { MemoryCache } from "../../cache.js" +import { docs } from "../../tools/docs.js" + +vi.mock("../../api.js", () => ({ + textGet: vi.fn(), +})) + +import { textGet } from "../../api.js" + +const INDEX = [ + "# LPM docs", + "getting-started — Getting started with LPM", + "cli/install — Installing packages", + "cli/publish — Publishing packages", +].join("\n") + +const ok = text => ({ ok: true, status: 200, text }) + +function context() { + return { cache: new MemoryCache() } +} + +describe("docs tool", () => { + beforeEach(() => { + textGet.mockReset() + }) + + it("returns a page and caches it", async () => { + textGet.mockResolvedValueOnce(ok("# Installing")) + const ctx = context() + + const first = await docs({ page: "/cli/install/" }, ctx) + const second = await docs({ page: "cli/install" }, ctx) + + expect(first.content[0].text).toBe("# Installing") + expect(second).toBe(first) + expect(textGet).toHaveBeenCalledTimes(1) + expect(textGet).toHaveBeenCalledWith("https://lpm.dev/api/docs/cli/install") + }) + + it("says a missing page wasn't found, and why another page couldn't be read", async () => { + textGet.mockResolvedValueOnce({ ok: false, status: 404 }) + const missing = await docs({ page: "nope" }, context()) + expect(missing.isError).toBe(true) + expect(missing.content[0].text).toContain('"nope" not found') + + textGet.mockResolvedValueOnce({ + ok: false, + status: 0, + error: "Request timed out", + }) + const timedOut = await docs({ page: "cli/install" }, context()) + expect(timedOut.isError).toBe(true) + expect(timedOut.content[0].text).toContain("Request timed out") + }) + + it("returns the index without a page or query", async () => { + textGet.mockResolvedValueOnce(ok(INDEX)) + + const result = await docs({}, context()) + + expect(result.content[0].text).toBe(INDEX) + }) + + it("returns the pages whose index lines match a query", async () => { + textGet + .mockResolvedValueOnce(ok(INDEX)) + .mockResolvedValueOnce(ok("# Installing")) + .mockResolvedValueOnce(ok("# Publishing")) + + const result = await docs({ query: "packages" }, context()) + + expect(result.content[0].text).toBe( + "--- cli/install ---\n# Installing\n\n--- cli/publish ---\n# Publishing", + ) + }) + + it("keeps the pages it could read, and names the ones it couldn't", async () => { + textGet + .mockResolvedValueOnce(ok(INDEX)) + .mockResolvedValueOnce({ + ok: false, + status: 0, + error: "Request timed out", + }) + .mockResolvedValueOnce(ok("# Publishing")) + + const result = await docs({ query: "packages" }, context()) + + expect(result.isError).toBeUndefined() + expect(result.content[0].text).toBe( + "--- cli/publish ---\n# Publishing\n\n(Could not read: cli/install: Request timed out)", + ) + }) + + it("reports an error, not an empty answer, when no matching page could be read", async () => { + textGet + .mockResolvedValueOnce(ok(INDEX)) + .mockResolvedValueOnce({ + ok: false, + status: 0, + error: "Request timed out", + }) + .mockResolvedValueOnce({ ok: false, status: 503 }) + + const result = await docs({ query: "packages" }, context()) + + expect(result.isError).toBe(true) + expect(result.content[0].text).toContain( + "cli/install: Request timed out, cli/publish: 503", + ) + }) + + it("reports when the index can't be read", async () => { + textGet.mockResolvedValueOnce({ + ok: false, + status: 0, + error: "Response was larger than 50 MB", + }) + + const result = await docs({ query: "x" }, context()) + + expect(result.isError).toBe(true) + expect(result.content[0].text).toContain("larger than 50 MB") + }) +}) diff --git a/lib/api.js b/lib/api.js index a70b724..761b0fa 100644 --- a/lib/api.js +++ b/lib/api.js @@ -1,16 +1,56 @@ // CRITICAL: Never use console.log() — it corrupts the MCP stdio transport import { + MAX_RESPONSE_BYTES, MAX_RETRIES, REQUEST_TIMEOUT_MS, + REQUEST_TOTAL_TIMEOUT_MS, RETRY_BACKOFF_MULTIPLIER, RETRY_BASE_DELAY_MS, RETRY_MAX_DELAY_MS, RETRYABLE_STATUS_CODES, } from "./constants.js" -function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)) +/** Waits `ms`, or until `signal` aborts. */ +function sleep(ms, signal) { + return new Promise(resolve => { + if (signal?.aborted) return resolve() + const done = () => { + clearTimeout(timer) + signal?.removeEventListener("abort", done) + resolve() + } + const timer = setTimeout(done, ms) + signal?.addEventListener("abort", done, { once: true }) + }) +} + +function abortError() { + return new DOMException("The request was aborted", "AbortError") +} + +/** + * `promise`, or a rejection once `signal` aborts. Built-in fetch ends a body + * read when its signal aborts, but a replacement may not, and the read would + * then hang past every timeout. + */ +function untilAborted(promise, signal) { + if (!signal) return promise + if (signal.aborted) return Promise.reject(abortError()) + return new Promise((resolve, reject) => { + const onAbort = () => reject(abortError()) + signal.addEventListener("abort", onAbort, { once: true }) + promise.then( + value => { + signal.removeEventListener("abort", onAbort) + resolve(value) + }, + error => { + signal.removeEventListener("abort", onAbort) + reject(error) + }, + ) + }) } function getBackoffDelay(attempt) { @@ -23,7 +63,7 @@ function parseRetryAfter(retryAfter) { if (!retryAfter) return RETRY_BASE_DELAY_MS const seconds = parseInt(retryAfter, 10) - if (!Number.isNaN(seconds)) return seconds * 1000 + if (!Number.isNaN(seconds)) return Math.max(0, seconds * 1000) const date = new Date(retryAfter) if (!Number.isNaN(date.getTime())) { @@ -33,6 +73,148 @@ function parseRetryAfter(retryAfter) { return RETRY_BASE_DELAY_MS } +class ResponseTooLargeError extends Error { + constructor() { + super(`Response was larger than ${MAX_RESPONSE_BYTES / (1024 * 1024)} MB`) + this.name = "ResponseTooLargeError" + } +} + +/** + * Reads a body's bytes up to MAX_RESPONSE_BYTES and decodes them as UTF-8, + * dropping a byte-order mark as `response.text()` does. `progress` is called + * for each chunk, so a download that keeps arriving isn't timed out as idle. + */ +async function readBodyWithin(body, { progress, signal }) { + const chunks = [] + let length = 0 + const add = chunk => { + progress() + length += chunk.byteLength + if (length > MAX_RESPONSE_BYTES) throw new ResponseTooLargeError() + chunks.push(chunk) + } + // A web stream, as fetch gives, or a Node stream, as replacements such as + // node-fetch give. Either is cancelled when the read stops early. + const reader = + typeof body.getReader === "function" + ? body.getReader() + : body[Symbol.asyncIterator]() + const next = () => + untilAborted( + typeof reader.read === "function" ? reader.read() : reader.next(), + signal, + ) + try { + for (;;) { + const { done, value } = await next() + if (done) break + add(value) + } + } catch (error) { + if (typeof reader.cancel === "function") { + await reader.cancel().catch(() => {}) + } else { + await reader.return?.().catch(() => {}) + body.destroy?.() + } + throw error + } + return new TextDecoder().decode(Buffer.concat(chunks, length)) +} + +/** + * Reads a body as text, up to MAX_RESPONSE_BYTES. A body past the limit is + * cancelled and rejects with ResponseTooLargeError. + */ +async function readTextWithin(response, reading) { + const declared = Number(response.headers?.get?.("content-length")) + if (declared > MAX_RESPONSE_BYTES) { + discardBody(response) + throw new ResponseTooLargeError() + } + if (response.body == null) { + return typeof response.text === "function" ? response.text() : "" + } + return readBodyWithin(response.body, reading) +} + +/** Parses a JSON body within the size limit; a malformed body reads as `{}`. */ +async function readJsonWithin(response, reading) { + // Without a body there is nothing to bound: fetch gives one for every + // response with content, so this is an empty response or a test double. + if (response.body == null && typeof response.json === "function") { + return response.json().catch(() => ({})) + } + const text = await readTextWithin(response, reading) + try { + return JSON.parse(text) + } catch { + return {} + } +} + +/** + * The JSON body of an error response, or `{}` when it can't be read: the + * status is what callers act on, and it must not be lost to a body that is + * too large, breaks off or stalls. + */ +async function readErrorBody(response, reading) { + try { + return await readJsonWithin(response, reading) + } catch { + return {} + } +} + +function discardBody(response) { + const body = response.body + if (typeof body?.cancel === "function") body.cancel().catch(() => {}) + else body?.destroy?.() +} + +/** + * Runs `read` on a GET response. The request and its body have an idle + * timeout, restarted by each chunk, so a server that sends headers and then + * stalls still times out. `deadline` aborts it too: it is the call's total + * timeout, which spans its retries. + * + * @template T + * @param {string} url + * @param {RequestInit} init + * @param {AbortSignal} deadline + * @param {(response: Response, reading: { progress: () => void, signal: AbortSignal }) => Promise} read + * @returns {Promise} + */ +async function fetchWithin(url, init, deadline, read) { + const controller = new AbortController() + const abort = () => controller.abort() + let idle = setTimeout(abort, REQUEST_TIMEOUT_MS) + deadline.addEventListener("abort", abort, { once: true }) + const progress = () => { + clearTimeout(idle) + idle = setTimeout(abort, REQUEST_TIMEOUT_MS) + } + try { + if (deadline.aborted) throw abortError() + const response = await fetch(url, { ...init, signal: controller.signal }) + progress() + return await read(response, { progress, signal: controller.signal }) + } finally { + clearTimeout(idle) + deadline.removeEventListener("abort", abort) + } +} + +/** A signal that aborts after REQUEST_TOTAL_TIMEOUT_MS, and its cleanup. */ +function totalDeadline() { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), REQUEST_TOTAL_TIMEOUT_MS) + return { signal: controller.signal, clear: () => clearTimeout(timer) } +} + +const TIMED_OUT = { error: "Request timed out" } + /** * Make a GET request with retry, timeout, and rate limit handling. * @@ -46,63 +228,94 @@ export async function apiGet(url, token) { headers.Authorization = `Bearer ${token}` } + const deadline = totalDeadline() + try { + return await apiGetWithin(url, headers, deadline.signal) + } finally { + deadline.clear() + } +} + +async function apiGetWithin(url, headers, deadline) { let lastError = null for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { - const controller = new AbortController() - const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) - try { - const response = await fetch(url, { - method: "GET", - headers, - signal: controller.signal, - }) - - clearTimeout(timeoutId) - - // No retry on auth errors - if (response.status === 401 || response.status === 403) { - const data = await response.json().catch(() => ({})) - return { ok: false, status: response.status, data } - } - - // Rate limiting - if (response.status === 429) { - const retryAfter = response.headers.get("Retry-After") - const delayMs = parseRetryAfter(retryAfter) + const outcome = await fetchWithin( + url, + { method: "GET", headers }, + deadline, + async (response, reading) => { + // No retry on auth errors + if (response.status === 401 || response.status === 403) { + return { + result: { + ok: false, + status: response.status, + data: await readErrorBody(response, reading), + }, + } + } - if (attempt < MAX_RETRIES) { - await sleep(delayMs) - continue - } + // Rate limiting. A server that asks for a longer wait than the + // backoff allows is answered as rate limited rather than waited on. + if (response.status === 429) { + discardBody(response) + const delay = parseRetryAfter(response.headers.get("Retry-After")) + if (attempt < MAX_RETRIES && delay <= RETRY_MAX_DELAY_MS) { + return { retryAfterMs: delay } + } + return { + result: { + ok: false, + status: 429, + data: { error: "Rate limited" }, + }, + } + } - return { ok: false, status: 429, data: { error: "Rate limited" } } - } + // Retryable server errors + if ( + RETRYABLE_STATUS_CODES.includes(response.status) && + attempt < MAX_RETRIES + ) { + discardBody(response) + return { retryAfterMs: getBackoffDelay(attempt) } + } - // Retryable server errors - if ( - RETRYABLE_STATUS_CODES.includes(response.status) && - attempt < MAX_RETRIES - ) { - await sleep(getBackoffDelay(attempt)) - continue - } + return { + result: { + ok: response.ok, + status: response.status, + data: response.ok + ? await readJsonWithin(response, reading) + : await readErrorBody(response, reading), + }, + } + }, + ) - const data = await response.json().catch(() => ({})) - return { ok: response.ok, status: response.status, data } + if (outcome.result) return outcome.result + await sleep(outcome.retryAfterMs, deadline) + if (deadline.aborted) return { ok: false, status: 0, data: TIMED_OUT } } catch (error) { - clearTimeout(timeoutId) + // The same body would be too large again. + if (error instanceof ResponseTooLargeError) { + return { ok: false, status: 0, data: { error: error.message } } + } + // The call's total timeout spans its retries. + if (deadline.aborted) return { ok: false, status: 0, data: TIMED_OUT } lastError = error if (attempt < MAX_RETRIES) { - await sleep(getBackoffDelay(attempt)) + await sleep(getBackoffDelay(attempt), deadline) + if (deadline.aborted) return { ok: false, status: 0, data: TIMED_OUT } continue } if (error.name === "AbortError") { - return { ok: false, status: 0, data: { error: "Request timed out" } } + return { ok: false, status: 0, data: TIMED_OUT } } return { @@ -120,6 +333,42 @@ export async function apiGet(url, token) { } } +/** + * GET a text body once, within the request timeouts and size limit. + * + * @param {string} url + * @param {Record} [headers] + * @returns {Promise<{ok: true, status: number, text: string} | {ok: false, status: number, text?: string, error?: string}>} + */ +export async function textGet(url, headers = { Accept: "text/plain" }) { + const deadline = totalDeadline() + try { + return await fetchWithin( + url, + { method: "GET", headers }, + deadline.signal, + async (response, reading) => { + if (!response.ok) { + discardBody(response) + return { ok: false, status: response.status } + } + return { + ok: true, + status: response.status, + text: await readTextWithin(response, reading), + } + }, + ) + } catch (error) { + if (error.name === "AbortError") { + return { ok: false, status: 0, error: "Request timed out" } + } + return { ok: false, status: 0, error: error.message || "Network error" } + } finally { + deadline.clear() + } +} + /** * GET from the registry API (/api/registry prefix). * diff --git a/lib/cache.js b/lib/cache.js index f7cf540..b86b31b 100644 --- a/lib/cache.js +++ b/lib/cache.js @@ -1,10 +1,16 @@ /** * Simple in-memory cache with TTL support. * Used to reduce API calls for repeated queries within an MCP session. + * It holds at most `maxEntries`, dropping the least recently used, since a + * long session can ask about any number of packages and paths. */ export class MemoryCache { - constructor() { + constructor({ maxEntries = 500 } = {}) { + if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) { + throw new TypeError("maxEntries must be a positive integer") + } this._store = new Map() + this._maxEntries = maxEntries } /** @@ -21,6 +27,8 @@ export class MemoryCache { return undefined } + this._store.delete(key) + this._store.set(key, entry) return entry.value } @@ -33,6 +41,10 @@ export class MemoryCache { set(key, value, ttlMs) { if (!ttlMs) return + this._store.delete(key) + while (this._store.size >= this._maxEntries) { + this._store.delete(this._store.keys().next().value) + } this._store.set(key, { value, expiresAt: Date.now() + ttlMs, diff --git a/lib/constants.js b/lib/constants.js index c32959e..91e3400 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -5,7 +5,16 @@ export const DEFAULT_REGISTRY_URL = "https://lpm.dev" export const KEYTAR_SERVICE_NAME = "lpm-cli" export const KEYTAR_ACCOUNT_PREFIX = "auth-token" +// How long a request may wait for headers, or between chunks of its body. export const REQUEST_TIMEOUT_MS = 30_000 +// How long a request may take in all, its body included. +export const REQUEST_TOTAL_TIMEOUT_MS = 120_000 +// A registry response is parsed whole on the server's only thread, so its +// size is bounded. Package documents grow with every version, and each +// version's lpmConfig can be 128 KB, so the limit leaves room for large +// packages: parsing 50 MB takes about 80 ms. +export const MAX_RESPONSE_BYTES = 50 * 1024 * 1024 +export const MAX_SOURCE_TREE_ENTRIES = 2_000 export const MAX_RETRIES = 2 export const RETRY_BASE_DELAY_MS = 1_000 export const RETRY_MAX_DELAY_MS = 10_000 diff --git a/lib/server.js b/lib/server.js index 20d9801..56c7dbb 100644 --- a/lib/server.js +++ b/lib/server.js @@ -286,6 +286,14 @@ If you must use this tool: fetch directory paths (e.g., "src") to get multiple f .describe( 'File or directory path to browse (e.g., "src/index.js" or "src"). Omit to get file tree only. Pass empty string "" to get ALL source files at once.', ), + treeOffset: z + .number() + .int() + .min(0) + .optional() + .describe( + "Index of the first tree path to list. A tree longer than 2,000 paths is listed 2,000 at a time; the response gives the offset of the next page.", + ), }, params => browseSource(params, context), ) diff --git a/lib/tools/browse-source.js b/lib/tools/browse-source.js index 55a6ba0..7330deb 100644 --- a/lib/tools/browse-source.js +++ b/lib/tools/browse-source.js @@ -1,5 +1,5 @@ import { registryGet } from "../api.js" -import { CACHE_TTL } from "../constants.js" +import { CACHE_TTL, MAX_SOURCE_TREE_ENTRIES } from "../constants.js" import { errorResponse, parseName, textResponse } from "../format.js" /** @@ -10,11 +10,15 @@ import { errorResponse, parseName, textResponse } from "../format.js" * * - Without `path`: returns file tree only (use this first to explore structure) * - With `path`: returns file tree + source contents for matching files/directory + * - With `treeOffset`: lists a long tree from that path onwards * - * @param {{ name: string, version?: string, path?: string }} params + * @param {{ name: string, version?: string, path?: string, treeOffset?: number }} params * @param {{ cache: import('../cache.js').MemoryCache, getToken: () => Promise, getBaseUrl: () => string }} ctx */ -export async function browseSource({ name, version, path }, ctx) { +export async function browseSource( + { name, version, path, treeOffset = 0 }, + ctx, +) { let owner, pkgName try { const parsed = parseName(name) @@ -31,8 +35,12 @@ export async function browseSource({ name, version, path }, ctx) { ) } + if (!Number.isSafeInteger(treeOffset) || treeOffset < 0) { + return errorResponse("treeOffset must be a non-negative integer.") + } + // Build cache key (includes path for content requests) - const cacheKey = `browse-source:${owner}.${pkgName}:${version || "latest"}:${path || ""}` + const cacheKey = `browse-source:${owner}.${pkgName}:${version || "latest"}:${path || ""}:${treeOffset}` const cached = ctx.cache.get(cacheKey) if (cached) return cached @@ -85,20 +93,22 @@ export async function browseSource({ name, version, path }, ctx) { ecosystem: data.ecosystem, } - // Always include tree - response.tree = data.tree || [] + Object.assign(response, treeListing(data.tree, path, treeOffset)) // Include files if present (only when path was requested) if (data.files && data.files.length > 0) { response.files = data.files } - // Include truncation warning + const warnings = response.treeNote ? [response.treeNote] : [] + delete response.treeNote if (data.truncated) { response.truncated = true - response.warning = - "Response was truncated due to size limits. Use the `path` parameter to request specific files or directories." + warnings.push( + "Response was truncated due to size limits. Use the `path` parameter to request specific files or directories.", + ) } + if (warnings.length) response.warning = warnings.join(" ") // Include package config if present (helps AI understand package structure) if (data.lpmConfig) { @@ -109,3 +119,125 @@ export async function browseSource({ name, version, path }, ctx) { ctx.cache.set(cacheKey, mcpResponse, CACHE_TTL.SHORT) return mcpResponse } + +const MAX_SUMMARY_ENTRIES = 100 + +/** + * The tree, or one page of it. A tree that fits is listed whole, as the + * registry sends it. A tarball can hold 20,000 paths, so a longer one is + * listed MAX_SOURCE_TREE_ENTRIES at a time from `offset`, scoped to `path` + * when that names a directory with paths in it, with its total and a count + * of paths by entry. Every path can be reached by paging, so none can hide + * behind the limit. + * + * @param {unknown} tree + * @param {string | undefined} path + * @param {number} offset + */ +function treeListing(tree, path, offset) { + const fullTree = Array.isArray(tree) ? tree : [] + if (fullTree.length <= MAX_SOURCE_TREE_ENTRIES && offset === 0) { + return { tree: fullTree } + } + + const directory = path ? trimSlashes(path, { leading: true }) : "" + const scoped = directory + ? fullTree.filter( + entry => entry === directory || entry.startsWith(`${directory}/`), + ) + : fullTree + const scope = directory && scoped.length > 0 ? directory : null + const listed = scope ? scoped : fullTree + const page = listed.slice(offset, offset + MAX_SOURCE_TREE_ENTRIES) + const next = offset + page.length + const summary = summarizeTree(listed, scope ?? "") + + const where = scope ? ` under ${scope}` : "" + const notes = [] + if (directory && !scope) { + notes.push( + `No paths are under ${directory}; the tree lists the whole package.`, + ) + } + notes.push( + page.length + ? `The tree lists paths ${offset + 1}–${next} of ${listed.length}${where}.` + : `treeOffset ${offset} is past the ${listed.length} paths${where}.`, + ) + if (next < listed.length) { + notes.push(`Pass treeOffset ${next} for the next paths.`) + } + notes.push( + summary.truncated + ? `treeSummary counts the ${MAX_SUMMARY_ENTRIES} largest of its ${summary.total} entries; page through the tree for the rest.` + : "treeSummary counts its paths by entry.", + ) + + return { + tree: page, + treeTotal: listed.length, + treeOffset: offset, + treeScope: scope, + treeTruncated: next < listed.length, + treeSummary: summary.entries, + ...(summary.truncated ? { treeSummaryTruncated: true } : {}), + treeNote: notes.join(" "), + } +} + +/** + * The number of files under each entry directly below `directory` (the root + * when empty), most first, at most MAX_SUMMARY_ENTRIES of them. A tree can + * list directories as paths of their own; those aren't counted as files. + * + * @param {string[]} tree + * @param {string} directory + * @returns {{ entries: Array<{ path: string, files: number }>, total: number, truncated: boolean }} + */ +function summarizeTree(tree, directory) { + const prefix = directory ? `${directory}/` : "" + const rests = [] + const directories = new Set() + for (const entry of tree) { + if (prefix && !entry.startsWith(prefix)) continue + const rest = trimSlashes(entry.slice(prefix.length)) + if (!rest) continue + const slash = rest.indexOf("/") + if (slash !== -1) directories.add(rest.slice(0, slash)) + rests.push(rest) + } + const counts = new Map() + for (const rest of rests) { + const slash = rest.indexOf("/") + if (slash === -1 && directories.has(rest)) continue + const key = prefix + (slash === -1 ? rest : rest.slice(0, slash + 1)) + counts.set(key, (counts.get(key) ?? 0) + 1) + } + const entries = [...counts] + .sort( + ([a, countA], [b, countB]) => + countB - countA || (a < b ? -1 : a > b ? 1 : 0), + ) + .map(([path, files]) => ({ path, files })) + return { + entries: entries.slice(0, MAX_SUMMARY_ENTRIES), + total: entries.length, + truncated: entries.length > MAX_SUMMARY_ENTRIES, + } +} + +/** + * `text` without its trailing slashes, and its leading ones too with + * `leading`. A loop, not /\/+$/: that pattern retries a run of slashes from + * every offset when another character follows, and paths reach 32 KiB. + * + * @param {string} text + * @param {{ leading?: boolean }} [options] + */ +function trimSlashes(text, { leading = false } = {}) { + let start = 0 + let end = text.length + if (leading) while (start < end && text[start] === "/") start++ + while (end > start && text[end - 1] === "/") end-- + return text.slice(start, end) +} diff --git a/lib/tools/docs.js b/lib/tools/docs.js index ca7628d..e3fc7bc 100644 --- a/lib/tools/docs.js +++ b/lib/tools/docs.js @@ -1,3 +1,4 @@ +import { textGet } from "../api.js" import { CACHE_TTL } from "../constants.js" import { errorResponse, textResponse } from "../format.js" @@ -22,18 +23,19 @@ export async function docs({ page, query }, ctx) { const cached = ctx.cache.get(cacheKey) if (cached) return cached - const response = await fetchText(`${DOCS_BASE_URL}/${slug}`) + const response = await textGet(`${DOCS_BASE_URL}/${slug}`) if (!response.ok) { if (response.status === 404) { return errorResponse( `Documentation page "${slug}" not found. Use this tool without a page parameter to see all available pages.`, ) } - return errorResponse(`Failed to fetch docs (${response.status})`) + return errorResponse( + `Failed to fetch docs (${response.error ?? response.status})`, + ) } - const content = await response.text() - const result = textResponse(content) + const result = textResponse(response.text) ctx.cache.set(cacheKey, result, CACHE_TTL.LONG) return result } @@ -43,11 +45,13 @@ export async function docs({ page, query }, ctx) { let indexText = ctx.cache.get(cacheKey) if (!indexText) { - const response = await fetchText(DOCS_BASE_URL) + const response = await textGet(DOCS_BASE_URL) if (!response.ok) { - return errorResponse(`Failed to fetch docs index (${response.status})`) + return errorResponse( + `Failed to fetch docs index (${response.error ?? response.status})`, + ) } - indexText = await response.text() + indexText = response.text ctx.cache.set(cacheKey, indexText, CACHE_TTL.LONG) } else { // Cache stores the textResponse wrapper, extract the text @@ -76,15 +80,25 @@ export async function docs({ page, query }, ctx) { // Fetch content of matching pages (up to 3) const results = [] + const failures = [] for (const match of matches.slice(0, 3)) { const slug = match.split(" — ")[0].trim() - const response = await fetchText(`${DOCS_BASE_URL}/${slug}`) + const response = await textGet(`${DOCS_BASE_URL}/${slug}`) if (response.ok) { - const content = await response.text() - results.push(`--- ${slug} ---\n${content}`) + results.push(`--- ${slug} ---\n${response.text}`) + } else { + failures.push(`${slug}: ${response.error ?? response.status}`) } } + if (results.length === 0) { + return errorResponse( + `Failed to fetch the matching docs pages (${failures.join(", ")})`, + ) + } + if (failures.length) { + results.push(`(Could not read: ${failures.join(", ")})`) + } return textResponse(results.join("\n\n")) } @@ -93,9 +107,3 @@ export async function docs({ page, query }, ctx) { typeof indexText === "string" ? indexText : String(indexText), ) } - -async function fetchText(url) { - return fetch(url, { - headers: { Accept: "text/plain" }, - }) -}