diff --git a/hub/src/index.ts b/hub/src/index.ts index 0a16ecb..8d5c97f 100644 --- a/hub/src/index.ts +++ b/hub/src/index.ts @@ -114,9 +114,11 @@ import { MAX_CONCURRENT_EXTRACTS_PER_USER, MAX_CONCURRENT_MAPS_PER_USER, previewCrawlParams, + SMALL_CRAWL_SYNC_LIMIT, startOrExecuteBatchScrape, tryAcquireUserExtractSlots, tryAcquireUserMapSlot, + waitForSmallCrawl, type MapRequestPayload, } from './map-crawl'; import { handleMcpRequest, isMcpRootRequest } from './mcp'; @@ -2568,6 +2570,19 @@ export default { await jobPromise; } } + // Small crawls (the tool's documented contract): wait for the pages instead of returning a crawlId, + // unless the caller asked for `async: true`. Past the wait, fall through to the usual queued response. + if (crawlArgs.async !== true && created.options.limit <= SMALL_CRAWL_SYNC_LIMIT) { + const done = await waitForSmallCrawl({ + crawlId: created.crawlId, + metaDb: env.META, + bucket: env.ARTIFACTS, + userId: effectiveUserId, + }); + if (done) { + return { status: 200, body: done }; + } + } return { status: 202, body: { diff --git a/hub/src/map-crawl.ts b/hub/src/map-crawl.ts index 66a3245..95c8dfc 100644 --- a/hub/src/map-crawl.ts +++ b/hub/src/map-crawl.ts @@ -2435,6 +2435,46 @@ export async function executeCrawlJob(params: { return activeTracer ? activeTracer.run(runCrawl) : runCrawl(); } +/** Crawls with at most this many pages return their pages inline unless the caller sets `async: true`. */ +export const SMALL_CRAWL_SYNC_LIMIT = 5; +/** How long a small crawl call waits for the crawl to finish before falling back to `{ status: 'queued', crawlId }`. */ +export const SMALL_CRAWL_SYNC_WAIT_MS = 25_000; +const SMALL_CRAWL_TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled']); + +/** + * Polls a just-dispatched crawl until it reaches a terminal status or `waitMs` elapses. Returns the same body a + * `{ crawlId }` poll returns (pages included) once the crawl is done, or `null` if it is still running, so the caller + * can answer with the usual queued response. + */ +export async function waitForSmallCrawl(params: { + crawlId: string; + metaDb?: D1Database; + bucket?: R2Bucket; + userId?: string; + waitMs?: number; + now?: () => number; + sleep?: (ms: number) => Promise; +}): Promise | null> { + const now = params.now ?? Date.now; + const sleep = params.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))); + const deadline = now() + (params.waitMs ?? SMALL_CRAWL_SYNC_WAIT_MS); + let delayMs = 250; + for (;;) { + const st = await getCrawlJobStatus({ + crawlId: params.crawlId, + metaDb: params.metaDb, + bucket: params.bucket, + userId: params.userId, + }); + if (!st.ok) return null; + if (SMALL_CRAWL_TERMINAL_STATUSES.has(String(st.crawl.status))) return st.crawl; + const remaining = deadline - now(); + if (remaining <= 0) return null; + await sleep(Math.min(delayMs, remaining)); + delayMs = Math.min(delayMs * 2, 2_000); + } +} + export async function getCrawlJobStatus(params: { crawlId: string; metaDb?: D1Database; diff --git a/hub/test/live-mcp-audit.test.ts b/hub/test/live-mcp-audit.test.ts index 0d36e0a..816a7e1 100644 --- a/hub/test/live-mcp-audit.test.ts +++ b/hub/test/live-mcp-audit.test.ts @@ -690,7 +690,8 @@ test('A.5: wrangler.toml binds CRAWL CrawlWorkflow in production, and MCP crawl method: 'tools/call', params: { name: 'crawl', - arguments: { url: 'https://iana.example.org/', limit, maxDepth: 1 }, + // Small crawls wait for their pages unless async: true; this test covers the queued dispatch path. + arguments: { url: 'https://iana.example.org/', limit, maxDepth: 1, ...(limit <= 5 ? { async: true } : {}) }, }, }), }); @@ -706,6 +707,53 @@ test('A.5: wrangler.toml binds CRAWL CrawlWorkflow in production, and MCP crawl } }); +test('A.5b: MCP crawl with limit <= 5 waits for the crawl and returns its pages instead of a queued crawlId', async () => { + const pending: Promise[] = []; + const env = { + AGENT_HUB: new LocalAgentHubCoordinator(':memory:').asNamespace() as never, + CALLER_TOKEN: 'owner-secret-token-for-small-crawl-test-1234', + META: createSqliteD1(META_SQL), + SEARCH: createSqliteD1(SEARCH_SQL), + ARTIFACTS: createMemoryR2Bucket(), + SAFE_PUBLIC_FETCH: (async (u: RequestInfo | URL) => { + const s = String(u); + if (s.endsWith('/robots.txt')) return new Response('User-agent: *\nAllow: /\n', { status: 200 }); + if (s.endsWith('/sitemap.xml')) return new Response('not found', { status: 404 }); + return new Response('Small Crawl

Small Crawl

One page of documentation.

', { + status: 200, + headers: { 'content-type': 'text/html; charset=utf-8' }, + }); + }) as typeof fetch, + }; + const ctx = { waitUntil(p: Promise) { pending.push(p); }, passThroughOnException() {} }; + + const mcpRes = await hubWorker.fetch( + new Request('https://hub.example.com/mcp', { + method: 'POST', + headers: { authorization: `Bearer ${env.CALLER_TOKEN}`, 'content-type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'crawl', arguments: { url: 'https://small.example.org/', limit: 2, maxDepth: 1 } }, + }), + }), + env as never, + ctx as never, + ); + await Promise.allSettled(pending); + assert.equal(mcpRes.status, 200); + const rpc = (await mcpRes.json()) as { result: { content: Array<{ text: string }> } }; + const crawlBody = JSON.parse(rpc.result.content[0]!.text) as Record; + assert.notEqual(crawlBody.status, 'queued', `small crawl should return its result, got ${JSON.stringify(crawlBody)}`); + assert.match(String(crawlBody.id), /^crw_/); + assert.equal(crawlBody.status, 'completed'); + const pages = crawlBody.data as Array<{ url: string; outcome: string; markdown?: string }>; + assert.ok(Array.isArray(pages) && pages.length >= 1, `expected crawled pages inline, got ${JSON.stringify(crawlBody)}`); + assert.equal(pages[0]!.outcome, 'ok'); + assert.equal(new URL(pages[0]!.url).hostname, 'small.example.org'); +}); + test('B.1 & B.2: scriptless static HTML never triggers browser-auto, preserves primary

, and strips Wikipedia edit chrome & RFC pilcrows', async () => { // B.1: example.com pure static HTML (zero