# Web to Markdown Scraper for AI Agents (MCP Server & API) (`upadhyay.labs/web-to-markdown-mcp`) Actor

Turn any URL into clean, token-efficient Markdown for AI agents and RAG. Ask a question to get only the relevant sections (up to 90% fewer tokens), or map a site from its sitemap or llms.txt first. MCP server and REST API, plus batch crawling — a browser renders a page only when it needs JavaScript.

- **URL**: https://apify.com/upadhyay.labs/web-to-markdown-mcp.md
- **Developed by:** [Upadhyay Labs](https://apify.com/upadhyay.labs) (community)
- **Features:** Limited permissions, Multi-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.10 / 1,000 page reads

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Web to Markdown for AI Agents (MCP Server & API)

**Give your AI agent the ability to read the web.** Send a URL, get back clean, token-efficient Markdown. Ask a question, and get back only the parts of the page that answer it.

Works as an **MCP server** (Claude, Cursor, VS Code, and any MCP client) and as a plain **REST API** for LangChain, LlamaIndex, OpenAI function calling, n8n, and your own code. One request in, one response out. No runs to start, no datasets to poll.

### What does it do?

- **Ask, don't dump.** Pass a `query` and receive only the relevant sections. A 15,000-token article becomes about 1,500 tokens, ranked locally with no LLM and no extra API key.
- **Fast by default.** A plain HTTP fetch usually answers in a few hundred milliseconds. A real browser starts only when a page truly needs JavaScript or blocks plain requests.
- **Map before you read.** `map_site` lists a site's pages from `llms.txt` or `sitemap.xml`, so your agent opens the right page instead of crawling blindly.
- **Built for LLM context windows.** Navigation, footers, cookie banners, scripts and dialogs are removed. Links become absolute. Doc-generator noise is stripped. Output is capped with `maxTokens`.
- **Safe to expose.** Requests to localhost, private networks and cloud-metadata addresses are refused.

It can be used three ways:

1. **MCP server** — `SERVER_URL/mcp`, tools `read_page`, `read_pages`, `map_site`, `crawl_site`.
2. **REST API** — `SERVER_URL/read`, `/map`, `/crawl`, both available the moment the Actor is published (Standby mode, no run to start).
3. **Batch mode** — a normal Actor run that crawls a site and saves every page to a dataset.

### How does it work?

```text
URL ──► safety check ──► plain HTTP fetch ──► looks like it needs JavaScript, or blocked?
        (public hosts       (fast path)              │ yes                      │ no
         only)                                       ▼                          ▼
                                              real browser fallback      clean + convert
                                                        └──────────────►  to Markdown
                                                                                │
                                              query? ─► rank sections ─► return the best ones
```

- **Safety first.** Every redirect and every browser sub-request is checked. Localhost, private ranges and cloud-metadata addresses are refused.
- **Fast path first.** Plain HTTP + Cheerio handles most pages. A real Playwright browser only starts when the page looks JavaScript-rendered (thin content, an SPA shell) or the site returns 403/429/503.
- **Relevance ranking.** With a `query`, the page is split by heading, scored with BM25 (headings count extra), and the best sections are returned in page order. Reference lists and "See also" blocks are down-weighted.
- **Cache.** Fetched pages are kept in memory for 5 minutes, so repeat reads and follow-up questions skip the network.

### Quick start (about 60 seconds)

1. Open this Actor's **Server** tab in Apify Console and copy the **Server URL**. It looks like `https://<username>--<actor-name>.apify.actor`. Below it is written as `SERVER_URL`.
2. Copy your [Apify API token](https://console.apify.com/account/integrations).
3. Connect your agent, or just try it:

```bash
curl -H "Authorization: Bearer $APIFY_TOKEN" \
  "SERVER_URL/read?url=https://example.com&format=markdown"
```

That returns the page as Markdown. The MCP endpoint is `SERVER_URL/mcp`.

### Integration

#### MCP clients

Replace `SERVER_URL` and `YOUR_APIFY_TOKEN`. The token goes in an `Authorization: Bearer` header, which keeps it out of server logs.

##### Claude Code

```bash
claude mcp add --transport http web-to-markdown SERVER_URL/mcp \
  --header "Authorization: Bearer YOUR_APIFY_TOKEN"
```

##### Cursor (`~/.cursor/mcp.json`)

```json
{
    "mcpServers": {
        "web-to-markdown": {
            "url": "SERVER_URL/mcp",
            "headers": { "Authorization": "Bearer YOUR_APIFY_TOKEN" }
        }
    }
}
```

##### VS Code (`.vscode/mcp.json`)

```json
{
    "servers": {
        "web-to-markdown": {
            "type": "http",
            "url": "SERVER_URL/mcp",
            "headers": { "Authorization": "Bearer YOUR_APIFY_TOKEN" }
        }
    }
}
```

##### Claude Desktop

Claude Desktop connects to remote servers through the `mcp-remote` bridge:

```json
{
    "mcpServers": {
        "web-to-markdown": {
            "command": "npx",
            "args": ["-y", "mcp-remote", "SERVER_URL/mcp", "--header", "Authorization: Bearer YOUR_APIFY_TOKEN"]
        }
    }
}
```

> **Client that cannot set headers?** Append the token to the URL instead: `SERVER_URL/mcp?token=YOUR_APIFY_TOKEN`. It works, but is less secure because URLs can end up in logs.

#### REST API in your own agent

```python
import os, requests

def read_url(url: str, question: str | None = None, max_tokens: int = 4000) -> str:
    """Read a web page and return its content as Markdown. Pass `question` to get only the relevant parts."""
    params = {"url": url, "maxTokens": max_tokens, "format": "markdown"}
    if question:
        params["query"] = question
    r = requests.get(
        "SERVER_URL/read",
        params=params,
        headers={"Authorization": f"Bearer {os.environ['APIFY_TOKEN']}"},
        timeout=60,
    )
    r.raise_for_status()
    return r.text
```

Wrap `read_url` as an OpenAI function tool, a LangChain `@tool`, a LlamaIndex `FunctionTool`, a CrewAI tool, or an n8n HTTP Request node. Each is the same single call.

#### The agent workflow this is designed for

Agents waste most of their tokens reading the wrong page, or the right page in full. Use three steps instead:

1. **Find the page.** `map_site("https://docs.example.com")` returns up to 500 URLs in one fast call, with titles when the site publishes `llms.txt`.
2. **Read only what matters.** `read_page(url, query="how do I authenticate?")` returns the sections that answer the question, with their headings.
3. **Follow up instantly.** Ask a second question about the same page and it comes straight from the cache, in tens of milliseconds, without touching the site again.

Example of what your agent sees for a `query`:

```text
## Web scraping
Source: https://en.wikipedia.org/wiki/Web_scraping
Showing 7 of 75 sections most relevant to: "legal issues and terms of service"

#### Legal issues
...
```

### Input

#### MCP tools

| Tool         | Use it to                                    | Key arguments                                                                                              |
| ------------ | -------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `read_page`  | Read one URL as Markdown                     | `url`, `query`, `maxTokens`, `includeLinks`, `includeOutline`, `includeStructuredData`, `renderJavaScript` |
| `read_pages` | Read up to 10 URLs in parallel               | `urls`, `query`, `maxTokensPerPage`                                                                        |
| `map_site`   | List a site's pages **without reading them** | `url`, `limit` (up to 500)                                                                                 |
| `crawl_site` | Ingest a small site, up to 50 pages          | `url`, `maxPages`, `maxDepth`, `maxTokensPerPage`                                                          |

`read_page` arguments:

| Argument                | Default                  | What it does                                                                                                    |
| ----------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------- |
| `url`                   | required                 | Absolute `http(s)` URL                                                                                          |
| `query`                 | none                     | A question or keywords. Returns only the most relevant sections (about 1,500 tokens unless you set `maxTokens`) |
| `maxTokens`             | 8000 (1500 with `query`) | Cap on the returned Markdown, in estimated tokens                                                               |
| `includeLinks`          | `false`                  | Also return the page's links, absolute and de-duplicated                                                        |
| `includeOutline`        | `false`                  | Also return the heading outline (h1 to h3)                                                                      |
| `includeStructuredData` | `false`                  | Also return JSON-LD (product details, article author and date, events)                                          |
| `renderJavaScript`      | `auto`                   | `auto` uses a browser only when needed. `never` is fastest. `always` forces a browser                           |

#### REST API parameters

Every endpoint accepts GET with query parameters or POST with a JSON body, and the same Bearer token.

| Endpoint             | Purpose                                    |
| -------------------- | ------------------------------------------ |
| `GET` / `POST /read` | One page as Markdown                       |
| `GET` / `POST /map`  | List a site's pages                        |
| `POST /crawl`        | Crawl a site, up to 50 pages               |
| `POST /mcp`          | MCP server (Streamable HTTP, JSON-RPC 2.0) |

```bash
## Only what answers a question
curl -H "Authorization: Bearer $APIFY_TOKEN" \
  "SERVER_URL/read?url=https://en.wikipedia.org/wiki/Web_scraping&query=legal+issues&format=markdown"

## Discover a site's pages
curl -H "Authorization: Bearer $APIFY_TOKEN" \
  "SERVER_URL/map?url=https://crawlee.dev&limit=50"

## JSON with metadata, token count and RAG chunks
curl -X POST -H "Authorization: Bearer $APIFY_TOKEN" -H "Content-Type: application/json" \
  -d '{"url":"https://crawlee.dev/docs","chunkTokens":800,"includeLinks":true}' \
  "SERVER_URL/read"

## Crawl a docs site
curl -X POST -H "Authorization: Bearer $APIFY_TOKEN" -H "Content-Type: application/json" \
  -d '{"url":"https://crawlee.dev/docs","maxPages":20,"maxDepth":2}' \
  "SERVER_URL/crawl"
```

`/read` parameters:

| Parameter                                                 | Default                  | Notes                                                                  |
| --------------------------------------------------------- | ------------------------ | ---------------------------------------------------------------------- |
| `url`                                                     | required                 | Absolute `http(s)` URL                                                 |
| `query`                                                   | none                     | Return only the most relevant sections                                 |
| `maxTokens`                                               | 8000 (1500 with `query`) | Cap on the Markdown                                                    |
| `maxAgeSecs`                                              | 300                      | Serve a cached copy up to this old. `0` always fetches fresh           |
| `render`                                                  | `auto`                   | `auto`, `never` or `always`                                            |
| `includeLinks`, `includeOutline`, `includeStructuredData` | `false`                  | Extra fields in the response                                           |
| `chunkTokens`                                             | none                     | Also return heading-aware chunks of about this size, for vector stores |
| `includeSelectors`                                        | none                     | CSS selectors. Only matching content is converted                      |
| `excludeSelectors`                                        | none                     | CSS selectors removed in addition to the built-in defaults             |
| `timeoutSecs`                                             | 30                       | 3 to 55                                                                |
| `format`                                                  | `json`                   | `markdown` returns the raw Markdown body only                          |

#### Batch mode input

Need a one-off crawl saved to a dataset? Run the Actor from the **Input** tab.

```json
{
    "startUrls": [{ "url": "https://crawlee.dev" }],
    "maxPages": 50,
    "maxDepth": 1,
    "renderJavaScript": "auto",
    "includeSelectors": [],
    "excludeSelectors": [],
    "maxMarkdownLength": 8000
}
```

| Field                | Default  | Meaning                                                                                                           |
| -------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| `startUrls`          | required | Where to start. Only same-domain links are followed                                                               |
| `maxPages`           | 50       | Total pages to fetch                                                                                              |
| `maxDepth`           | 1        | Link hops from the start URLs. `0` means only the start URLs                                                      |
| `renderJavaScript`   | `auto`   | `auto`, `never` or `always`                                                                                       |
| `includeSelectors`   | none     | Convert only content matching these CSS selectors                                                                 |
| `excludeSelectors`   | none     | Extra CSS selectors to remove                                                                                     |
| `maxMarkdownLength`  | 8000     | Pages longer than this are also split into heading-aware chunks                                                   |
| `proxyConfiguration` | none     | Route the browser fallback through [Apify Proxy](https://docs.apify.com/proxy) for sites that block plain fetches |

### Output

#### What you get back, and what is removed

| Kept                                                | Removed                                                   |
| --------------------------------------------------- | --------------------------------------------------------- |
| Main content, headings, lists, tables, code blocks  | Navigation, footers, site headers, sidebars               |
| Absolute, de-duplicated links                       | Cookie banners, dialogs, modals, ads                      |
| Title, description, author, language, canonical URL | Scripts, styles, iframes, SVG                             |
| Optional outline and JSON-LD                        | HTML comments and empty-text links left by doc generators |

Sites that already serve `text/markdown` are passed through and cleaned, not re-converted.

#### REST / MCP response

```json
{
    "url": "https://example.com/",
    "title": "Example Domain",
    "markdown": "This domain is for use in ...",
    "tokenCount": 39,
    "truncated": false,
    "metadata": { "title": "Example Domain", "language": "en" },
    "status": 200,
    "fetchedWith": "http",
    "cached": false,
    "fetchedAt": "2026-11-13T15:43:12.204Z"
}
```

With `query`, the response also includes `focused: { query, matched, selectedSections, totalSections }`. If nothing matches, `matched` is `false` and you get the start of the page instead of an empty result.

Errors are JSON: `400` invalid or non-public URL, `415` the page is not HTML, text, Markdown or JSON (e.g. a PDF or image), `502` the site returned an error, `504` the site timed out.

#### Batch mode output

Each page becomes one dataset item with `markdown`, `tokenCount`, `metadata`, `fetchedWith` and, for long pages, `chunks`.

### Use cases

- **Research agents** that need to read sources, then quote them.
- **Coding assistants** that look up current library docs instead of guessing from stale training data.
- **RAG pipelines** that need clean, chunked Markdown with token counts.
- **Monitoring and summarising** product pages, changelogs and news.
- **Documentation ingestion**: map a docs site, then crawl or read the pages you need.

### FAQ

**Does `query` use an LLM or send my content anywhere?**
No. Ranking runs inside the Actor with a keyword algorithm. No model call, no extra API key.

**Will it match meaning or only keywords?**
Keywords. A search for "cost" will not find a section that only says "pricing". Use several related words in the query, for example `pricing cost plans`.

**How do I know whether a browser was used?**
Check `fetchedWith` in the response: `http` or `browser`. Force a mode with `render` or `renderJavaScript`.

**Is the cache shared between users?**
The cache lives in the memory of the running instance and holds public pages only. Set `maxAgeSecs` to `0` to always fetch fresh.

**How do I get only part of a page?**
Use `query`, or pass `includeSelectors` over the REST API to convert only matching elements.

**What happens when a site blocks plain requests?**
In `auto` mode the Actor retries with a real browser. In batch mode you can also set `proxyConfiguration` to route that browser fallback through Apify Proxy. It does not solve CAPTCHAs or defeat strong anti-bot systems.

### Limits

- **Public pages only.** No logins or cookies. Apify Proxy is supported for the browser fallback in batch mode (see Input above); the REST/MCP server does not yet accept per-request proxy settings.
- **No PDFs or other binary files** are converted yet.
- **Page size:** responses over 5 MB are rejected.
- **Crawls:** up to 50 pages per `crawl_site` call, 500 URLs per `map_site` call, 10 URLs per `read_pages` call.
- **Request time:** a server request must return within 5 minutes. A single page read times out earlier (up to 55 seconds).
- **Cache** is per running instance and is cleared when the instance restarts.

### Responsible use

Respect each site's Terms of Service and robots.txt, and do not use this Actor to collect private or sensitive personal data. It only reads publicly accessible pages, and it does not bypass access controls.

### Feedback and support

Found a page that converts badly, or want a feature? Open an issue from this Actor's **Issues** tab with the URL and what you expected. Real examples help the most.

# Actor input Schema

## `startUrls` (type: `array`):

The URLs to start from. Only links on the same domain are followed.

## `maxPages` (type: `integer`):

Maximum number of pages to fetch in total.

## `maxDepth` (type: `integer`):

How many link hops to follow from the start URLs. 0 = only the start URLs.

## `renderJavaScript` (type: `string`):

Auto uses fast plain HTTP and switches to a real browser only for pages that need JavaScript.

## `includeSelectors` (type: `array`):

CSS selectors to exclusively convert. If empty, the main content of the page is detected automatically.

## `excludeSelectors` (type: `array`):

CSS selectors to remove in addition to the built-in defaults (navigation, footer, scripts, cookie banners, dialogs).

## `maxMarkdownLength` (type: `integer`):

Pages longer than this are also split into heading-aware chunks of about this size.

## `proxyConfiguration` (type: `object`):

Route the real-browser fallback through Apify Proxy. Only used for pages that need JavaScript rendering or that block plain HTTP requests.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://crawlee.dev"
    }
  ],
  "maxPages": 50,
  "maxDepth": 1,
  "renderJavaScript": "auto",
  "includeSelectors": [],
  "excludeSelectors": [],
  "maxMarkdownLength": 8000,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `overview` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "startUrls": [
        {
            "url": "https://crawlee.dev"
        }
    ],
    "proxyConfiguration": {
        "useApifyProxy": false
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("upadhyay.labs/web-to-markdown-mcp").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "startUrls": [{ "url": "https://crawlee.dev" }],
    "proxyConfiguration": { "useApifyProxy": False },
}

# Run the Actor and wait for it to finish
run = client.actor("upadhyay.labs/web-to-markdown-mcp").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "startUrls": [
    {
      "url": "https://crawlee.dev"
    }
  ],
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}' |
apify call upadhyay.labs/web-to-markdown-mcp --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,upadhyay.labs/web-to-markdown-mcp"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/GgjeAy1ebozQSMHKI/builds/SY1YHR2aBWGwc6BhV/openapi.json
