8000 feat(tools): add web_fetch to read public pages and APIs by geminixiang · Pull Request #176 · geminixiang/mikan · GitHub
[go: up one dir, main page]

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
9 changes: 9 additions & 0 deletions CHANGELOG.md
10000
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ change in a minor release.

## [Unreleased]

### Added

- `web_fetch` reads a public web page or API from the host so the agent can check versions,
releases, and dates against the official source instead of answering from memory. HTML is
returned as Markdown without navigation; long results are bounded like MCP results, with the
full text saved in the workspace. It needs no key and refuses private, loopback, and link-local
addresses, including through redirects. It does not go through an HTTP proxy configured for
the daemon.

## [1.3.0] - 2026-10-10

### Added
Expand Down
38 changes: 38 additions & 0 deletions docs/adr/0023-web-fetch-as-a-host-tool.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
status: accepted
---

# Read the web through a built-in host tool

mikan offers `web_fetch`, a built-in tool that reads a public web page or API on the host and returns its text. A model without it answers current-fact questions from memory or a stale search snippet.

## Context

Ten questions about current facts (package, language, and release versions, today's weather, this week's news), asked through mikan with the same model and graded against the official sources:

| Setup | Correct | Confidently wrong | Mean seconds |
| ---------------------------------------------- | ------- | ----------------- | ------------ |
| No web tool (only `jev_browser` and `bash`) | 2 | 1 | 33 |
| Brave Search MCP | 7 | 2 | 25 |
| Brave Search MCP and a reader (3 rounds, mean) | 8.0 | 0.7 | 19 |
| `web_fetch` prototype as an MCP server | 10 | 0 | 15 |
| Built-in `web_fetch` | 10 | 0 | 7 |

Search snippets alone produced confident wrong versions, because the snippet was older than the page. The answers became right once the model could read the official page, registry, or API. `jev_browser` timed out or failed on most of those pages. Without a search key the model still found this week's news by reading a news feed.

Pi offers web tools only as coding-agent extensions (for example `pi-web-access`, `pi-web-search`, and `rpiv-web-tools`). They register through the coding agent's `ExtensionAPI` and import `pi-coding-agent` and `pi-tui` at runtime; pi-durable has no loader for them, and Pi's own durable frontend lists extensions as unsupported.

## Decision

- `web_fetch` is a mikan tool, offered in every conversation and needing no key. HTML becomes Markdown through `@mdream/js` with its minimal preset, which drops navigation and other page chrome; JSON and plain text are returned as they are. The result is bounded and spilled to the workspace like an MCP result.
- It refuses non-HTTP URLs, and its connections refuse private, loopback, and link-local remote addresses, so redirects and DNS answers are covered by the same check.
- Web search is not part of this decision.

`@mdream/js` was compared on seven real pages (release pages, GitHub, a weather service, Wikipedia) with `html-to-text`, `turndown`, `node-html-markdown`, and Readability with Turndown. It kept the answer on every page, produced the smallest output, and installs in 0.6 MB with two dependencies. Readability dropped the version table on one page, and `node-html-markdown` took 29 seconds on a 3 MB page.

## Consequences

- Each request carries the tool description and one system prompt line.
- The host makes requests the model chooses. The address checks keep them off the host's own network, but the host's public IP is visible to the sites it reads.
- A deployment that reaches the web only through an HTTP proxy cannot use `web_fetch`.
- When pi-durable can load Pi extensions, a community extension can replace this tool.
24 changes: 23 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"@earendil-works/pi-durable": "^1.1.0",
"@earendil-works/pi-env": "^1.1.0",
"@earendil-works/pi-mcp": "^1.1.0",
"@mdream/js": "^2.0.1",
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/exporter-metrics-otlp-proto": "^0.221.0",
"@opentelemetry/exporter-trace-otlp-proto": "^0.221.0",
Expand Down
1 change: 1 addition & 0 deletions src/harness/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,7 @@ grep '"userName":"mario"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text
- sandbox: Inspect or temporarily adjust sandbox limits
- attach: Share files to the platform
- jev: Ask Jev (a fast calibrated decision model) boolean / choice / score questions about a state you supply; returns probabilities and confidence, never text. Use it whenever you need to classify, detect, score, rank, route, pick among known candidates, or verify.
- web_fetch: Read a public web page or API as text. For versions, releases, prices, and dates, read the official page, registry, or API instead of answering from memory, and cite the URL.
- react: Add an emoji reaction to the triggering message. mikan already acknowledges work on its own when your first tool starts, so do not react before starting work. Use a short name without colons (e.g. eyes, white_check_mark, +1); GitHub only accepts +1, -1, laugh, confused, heart, hooray, rocket, eyes and rejects anything else.

Each tool requires a "label" parameter (shown to user).
Expand Down
2 changes: 2 additions & 0 deletions src/harness/tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ tools depend on the connected server's `listTools()` response.
| `react` | ✓ | ✓ | — | ◇ | — | Emoji and reaction confirmation. |
| `jev` | ✓ | ✓ | — | — | — | State/questions in arguments; answers, model and usage in result. |
| `jev_browser` | ✓ | ✓ | — | — | — | URL/commands in arguments; status, history, snapshot and raw command results. |
| `web_fetch` | ✓ | ✓ | — | — | — | URL in arguments; page Markdown or API text, bounded like MCP text (full result spilled). |
| `history` | ✓ | ✓ | — | — | — | Action/query/session/paging; bounded entries from this office's sessions (incl. tool output) or chat log. |
| `start_task` | ✓ | ✓ | — | — | — | Task target and admission confirmation. |
| `task_status` | ✓ | ✓ | — | — | Session key and task status JSON. |
Expand Down Expand Up @@ -197,4 +198,5 @@ most one evidence-based correction rather than retrying an unchanged goal.
- `j 8000 ev` reports a Jev with no provider key as a tool error, never a silent fallback.
- `jev_browser` asks Jev which step to take, but Jev only chooses and scores, so the text it types or the option it selects is written by the conversation's own chat model (the office's resolved `settings.json` model), through pi-ai, which the runner injects. A field that needs text without that injection blocks with a reason instead of guessing.
- Each runner's `jev_browser` owns one browser, named by the tool rather than the model, that stays open until `close: true`; a later `url` opens a new tab, and opening past three tabs first closes the oldest inactive ones. Model-named sessions each started another Chrome, and a few of them exhausted a 1 GB sandbox until every page load timed out. Every command, including cleanup, runs as an argv through the actor-resolved sandbox `ExecutionEnv`, and a missing `agent-browser` (`spawn_error`) is a provisioning error, never an automatic install or a host fallback.
- `web_fetch` runs on the host, so it refuses private, loopback, and link-local targets (ADR 0023). Its own undici `Agent` checks the remote address of every connection, which covers IP literals, DNS answers, redirects, and a name that resolves differently between requests. That `Agent` bypasses the daemon's global `EnvHttpProxyAgent`, because a proxy would make the connection and hide the target address, so a deployment that reaches the web only through a proxy cannot use `web_fetch`. Its result goes through `guardMcpToolResult`, the same bound and workspace spill as MCP results.
- `subagent.ts` owns the progress protocol that the presenter renders: snapshot bounds, parsing, merging, settling, and the Markdown dashboard.
2 changes: 2 additions & 0 deletions src/harness/tools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { createJevTool } from "./jev.js";
import { createJevBrowserTool, type FieldTextGenerator } from "./jev-browser.js";
import { createReactTool } from "./react.js";
import { createSandboxTool } from "./sandbox.js";
import { createWebFetchTool } from "./web-fetch.js";
import type { MikanToolRunContext, PlatformToolPack } from "./types.js";

export function createMikanTools(
Expand Down Expand Up @@ -52,6 +53,7 @@ export function createMikanTools(
adaptAgentTool(reactTool),
adaptAgentTool(jevTool),
adaptAgentTool(jevBrowserTool),
createWebFetchTool(),
...taskTools.map(adaptAgentTool),
...packTools.map(adaptAgentTool),
].map(withSecretRedaction),
Expand Down
5 changes: 5 additions & 0 deletions src/harness/tools/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { BlockList } from "node:net";
import type { AgentTool } from "@earendil-works/pi-agent-core";
import type { TSchema } from "typebox";
import type { ConversationMessage, ConversationResponder } from "../../types.js";
Expand All @@ -22,3 +23,7 @@ export interface MikanToolRunContext {
platformName: string;
runtimeWorkspaceRoot: string;
}

export interface WebFetchToolOptions {
blocked?: BlockList;
}
147 changes: 147 additions & 0 deletions src/harness/tools/web-fetch.ts
10000
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { lookup } from "node:dns";
import { BlockList, isIP, type LookupFunction } from "node:net";
import { htmlToMarkdown } from "@mdream/js";
import { withMinimalPreset } from "@mdream/js/preset/minimal";
import { Agent, buildConnector, fetch } from "undici";
import { Type } from "typebox";
import { guardMcpToolResult } from "../mcp-result.js";
import { errorMessage, isRecord } from "../../unknown-values.js";
import { LABEL_PARAMETER } from "./host-fn-tool.js";
import { tagHarnessTool, type MikanHarnessTool } from "./pi-tools.js";
import type { WebFetchToolOptions } from "./types.js";

export const WEB_FETCH_TOOL = "web_fetch";

const MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
const TIMEOUT_MS = 20_000;
const USER_AGENT = "Mozilla/5.0 (compatible; mikan-web-fetch)";
const TEXT_CONTENT_TYPE = /^text\/|[/+](json|xml|javascript)\b/;

function nonPublicAddresses(): BlockList {
const list = new BlockList();
for (const [network, prefix] of [
["0.0.0.0", 8],
["10.0.0.0", 8],
["100.64.0.0", 10],
["127.0.0.0", 8],
["169.254.0.0", 16],
["172.16.0.0", 12],
["192.168.0.0", 16],
["224.0.0.0", 3],
] as const) {
list.addSubnet(network, prefix, "ipv4");
}
for (const [network, prefix] of [
["::", 127],
["fc00::", 7],
["fe80::", 10],
["ff00::", 8],
] as const) {
list.addSubnet(network, prefix, "ipv6");
}
return list;
}

const NON_PUBLIC = nonPublicAddresses();

export function isNonPublicAddress(address: string): boolean {
return isBlocked(NON_PUBLIC, address);
}

function isBlocked(blocked: BlockList, address: string): boolean {
const family = isIP(address);
return family === 0 || blocked.check(address, family === 4 ? "ipv4" : "ipv6");
}

function refusal(address: string, host: string): Error {
return new Error(`web_fetch refuses non-public address ${address} for ${host}`);
}

function publicOnlyLookup(blocked: BlockList): LookupFunction {
return (hostname, options, callback) =>
lookup(hostname, { ...options, all: true }, (error, addresses) => {
if (error) return callback(error, "", 0);
const refused = addresses.find(({ address }) => isBlocked(blocked, address));
if (refused) return callback(refusal(refused.address, hostname), "", 0);
if (options.all) return callback(null, addresses);
return callback(null, addresses[0]!.address, addresses[0]!.family);
});
}

function publicOnlyDispatcher(blocked: BlockList): Agent {
const connect = buildConnector({ lookup: publicOnlyLookup(blocked) });
return new Agent({
maxResponseSize: MAX_RESPONSE_BYTES,
connect: (options, callback) => {
const host = options.hostname.replace(/^\[|\]$/g, "");
if (isIP(host) && isBlocked(blocked, host)) return callback(refusal(host, host), null);
return connect(options, callback);
},
});
}

const webFetchSchema = Type.Object({
label: LABEL_PARAMETER,
url: Type.String({ description: "Absolute http or https URL of a public page or API" }),
});

function requestedUrl(args: unknown): URL {
const raw = isRecord(args) && typeof args.url === "string" ? args.url : "";
if (!URL.canParse(raw)) throw new Error(`web_fetch needs an absolute http or https URL: ${raw}`);
const url = new URL(raw);
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error(`web_fetch supports only http and https URLs, not ${url.protocol}`);
}
return url;
}

export function createWebFetchTool(options: WebFetchToolOptions = {}): MikanHarnessTool {
let dispatcher: Agent | undefined;
return tagHarnessTool({
name: WEB_FETCH_TOOL,
description: [
"Read a public web page or API URL from the mikan host. HTML is returned as Markdown with navigation and other page chrome removed; JSON and plain text are returned as they are.",
"Use it to verify current facts such as versions, releases, and dates against the official page, registry, or API, and cite the URL.",
"Private, loopback, and link-local addresses are refused.",
].join(" "),
parameters: webFetchSchema,
execute: async (args, api, context) => {
const url = requestedUrl(args);
dispatcher ??= publicOnlyDispatcher(options.blocked ?? NON_PUBLIC);
const timeout = AbortSignal.timeout(TIMEOUT_MS);
const response = await fetch(url, {
dispatcher,
signal: context.abortSignal ? AbortSignal.any([context.abortSignal, timeout]) : timeout,
headers: { "user-agent": USER_AGENT },
}).catch((error: unknown) => {
const reason = error instanceof Error && error.cause instanceof Error ? error.cause : error;
throw new Error(`web_fetch failed for ${url.href}: ${errorMessage(reason)}`, {
cause: error,
});
});
const finalUrl = response.url || url.href;
if (!response.ok) throw new Error(`web_fetch got HTTP ${response.status} for ${finalUrl}`);
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
if (contentType && !TEXT_CONTENT_TYPE.test(contentType)) {
await response.body?.cancel();
throw new Error(`Unsupported content type ${contentType.split(";")[0]} for ${finalUrl}`);
}
const body = await response.text();
const text = contentType.includes("html")
? htmlToMarkdown(body, withMinimalPreset({ origin: new URL(finalUrl).origin }))
: body;
return guardMcpToolResult(
{
content: [
{
type: "text",
text: finalUrl === url.href ? text : `Redirected to ${finalUrl}\n\n${text}`,
},
],
},
api.env,
context,
);
},
});
}
Loading
Loading
0