Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions hub/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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: {
Expand Down
40 changes: 40 additions & 0 deletions hub/src/map-crawl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
}): Promise<Record<string, unknown> | null> {
const now = params.now ?? Date.now;
const sleep = params.sleep ?? ((ms: number) => new Promise<void>((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;
Expand Down
50 changes: 49 additions & 1 deletion hub/test/live-mcp-audit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } : {}) },
},
}),
});
Expand All @@ -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<unknown>[] = [];
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('<html><head><title>Small Crawl</title></head><body><h1>Small Crawl</h1><p>One page of documentation.</p></body></html>', {
status: 200,
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}) as typeof fetch,
};
const ctx = { waitUntil(p: Promise<unknown>) { 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<string, unknown>;
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 <h1>, and strips Wikipedia edit chrome & RFC pilcrows', async () => {
// B.1: example.com pure static HTML (zero <script> tags) + <header><h1>Example Domain</h1></header>
const exampleHtml =
Expand Down