mcpy
by ebursztein
README.md
# mcpy
Web, paper, shopping, crypto and stock tools for AI agents, as:
- **an SDK** on npm: [`mcpy`](packages/mcpy), usable from any TypeScript project
- **a hosted server** on Cloudflare Workers: [`apps/server`](apps/server), exposing the
same tools over MCP (`/mcp`) and REST (`/v1/*`), built only on the SDK
Callers never see which backend served a request. Under the hood: a fallback
chain of providers (direct fetch, Cloudflare Browser Run, Firecrawl, Bright
Data), retries with backoff, per-attempt timeouts and an overall deadline, a
circuit breaker, caching, context-size limits, and OpenTelemetry-shaped
traces and structured logs tagged with the calling client's name.
> mcpy used to be a local single-binary MCP server. That version is archived
> at [ebursztein/mcpy-legacy](https://github.com/ebursztein/mcpy-legacy).
Design and rules: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
**Giving mcpy to an agent?** Hand it [`skills/mcpy/SKILL.md`](skills/mcpy/SKILL.md)
([raw](https://raw.githubusercontent.com/ebursztein/mcpy/main/skills/mcpy/SKILL.md))
with a base URL and its own API key. It covers connecting over MCP or REST,
which tool to use when, errors, and safety rules.
## Tools
| MCP tool | REST | Does |
| --- | --- | --- |
| `web_fetch` | `GET\|POST /v1/fetch` | Page as markdown (or HTML), in parts |
| `web_grep` | `GET\|POST /v1/grep` | Find lines in a page (regex or plain text), with context |
| `web_search` | `GET\|POST /v1/search` | Search the web, news, images, videos, shopping, jobs or places |
| `paper_search` | `GET\|POST /v1/papers` | Search scholarly papers: authors, year, venue, citations, abstract, free PDF |
| `shopping_search` | `POST /v1/shopping` | Listings across marketplaces, classifieds and auction sites, one row per listing, with per-site reports |
| `shopping_cards` | `POST /v1/shopping/cards` | `shopping_search` for trading cards: game, card grade, printed language; every seller's offer on card marketplaces |
| `shopping_fashion` | `POST /v1/shopping/fashion` | `shopping_search` for clothes, shoes and bags: The RealReal, Poshmark, Gilt, Vinted, eBay by default; resale grade (very good or better unless told), size, color |
| `shopping_similar` | `POST /v1/shopping/similar` | Listings like one listing (its marketplace and id): exact, style, cheaper, same brand, category or shape, ranked |
| `shopping_item` | `POST /v1/shopping/item` | One listing in full: description, photos (the first attached), item specifics; for fashion, measurements, condition notes, disclosed defects, return policy |
| `crypto_market` | `GET\|POST /v1/crypto/market` | Coins as they are now, with whole-market totals |
| `crypto_coin` | `GET\|POST /v1/crypto/coin` | A few coins day by day |
| `stock_quote` | `GET\|POST /v1/stocks/quote` | Latest price of up to 25 stocks, ETFs, funds, indices or currencies, on most exchanges (crypto: `crypto_coin`, `crypto_market`) |
| `stock_history` | `GET\|POST /v1/stocks/history` | One symbol's daily, weekly or monthly bars, with dividends and splits |
| `stock_fundamentals` | `GET\|POST /v1/stocks/fundamentals` | A US-listed company's fiscal years from its annual reports, latest balance sheet and shares outstanding |
### Parameters
| Tool | Parameters (all but the first are optional; papers needs a query, an author, or both) |
| --- | --- |
| fetch | `url`, `format` (`markdown`\|`html`), `offset`, `version`, `max_chars` (up to 50,000), `script`, `user_agent`, `render`, `wait_ms`, `method`, `body`, `headers`, `max_age` |
| grep | `url`, `pattern`, `literal`, `context`, `max_matches`, `format`, `user_agent`, `render`, `wait_ms`, `method`, `body`, `headers`, `max_age` |
| search | `query`, `type`, `max_results`, `page`, `country`, `language`, `recency`, `device`, `sites`, `exclude_sites`, `mode`, `max_age` |
| papers | `query` and/or `author`, `max_results`, `page`, `year_from`, `year_to`, `open_access`, `sort` (`relevance`\|`citations`\|`newest`), `collection` (`preprints`\|`biomedical`), `mode`, `max_age` |
| stock_quote | `symbols` (e.g. `AAPL`, `BRK-B`, `^GSPC`, `SAP.DE`, `EURUSD=X`; a crypto pair such as `BTC-USD` is refused with `invalid_input` pointing to the crypto tools; a bare coin symbol a listed instrument also uses, such as `BTC` (an ETF), is answered with a `warning`), `max_age` (default 60) |
| stock_history | `symbol`, `from`, `to` (YYYY-MM-DD; default the last 30 days), `interval` (`day`\|`week`\|`month`), `max_age`; at most 400 bars a call |
| stock_fundamentals | `symbol`, `years` (1-10, default 5), `max_age` (default a day) |
- `user_agent`: `default` (honest mcpy agent), `chrome`, `safari`, `firefox`, `mobile`, `googlebot`.
- `type`: `web`, `news`, `images`, `videos`, `shopping`, `jobs`, `places`.
- `recency`: `hour`, `day`, `week`, `month`, `year`. `device`: `desktop`, `mobile`.
- `country` / `language`: two-letter codes (`us`, `fr`, `en`). Hints: a source that cannot honor them still answers.
- `sites` / `exclude_sites`: hostnames.
- `mode`: `fast` (first source that answers) or `thorough` (every source that supports the request, merged; results carry `sources`, the number of sources that returned them).
- `render: true`: run the page's JavaScript in a real browser first, for pages that fill in their content with scripts; `wait_ms` (up to 15,000) gives it extra time. Only sources that render are tried; `no_providers` when the server has none.
- `method`: `GET` (default), `HEAD`, or `POST`, `PUT`, `PATCH`, `DELETE` with a `body` (up to 100,000 characters) for APIs that take one; a JSON body without a `Content-Type` header is sent as `application/json`. Only a direct request sends a method other than GET (no paid fallback). A POST or PATCH is never sent twice unless the target answers 408, 425 or 429; PUT and DELETE retry as GETs do. `headers`: up to 20 extra request headers (`Host`, `Content-Length` and connection headers are refused). Method, body, headers and `render` are all part of the cache key. These fields need POST /v1/fetch with a JSON body.
- `max_age` on fetch and grep defaults to an hour for GET and HEAD, and to 0 for POST, PUT, PATCH and DELETE: a write reaches the site every time unless you pass one (a JSON-RPC read, say). A write's cached answer is kept for the client that sent it; a read's is shared.
- Batch: `POST /v1/fetch/batch` with `{"requests": [...]}` takes up to 64 fetch inputs and answers each in order, `{"result": ...}` or `{"error": ...}`; one failing never fails the others; give a request an `id` and its answer carries it. Every request is looked up in the cache at once (one KV read for the whole batch) and what the cache answers is answered right away; only requests that must call a site wait, at most 6 in flight, 4 to any one site. Identical reads in a batch are fetched once (every write is sent), and a request still waiting to call its site after 25 s is answered `timeout` without being sent. Each request is a fetch of its own (its `max_age`, `free_only`, spending, usage row), and each request counts against the per-key rate limit as the call it replaces: a batch of N counts N, and one the limit has no room for is refused (429) before any of it runs. `meta` totals `cost_usd`, `fetched`, `deduplicated`, `cache_hits` and `failed`. SDK: `mcpy.fetchBatch({ requests })`.
- Long pages: pass the returned `next_offset` as `offset`, with the returned `version`, to read on (every part then comes from the same copy of the page), or pass a `script` (`export default (page) => value`) that runs on the whole page and returns only what it extracts, as JSON. Pages too long for one call come with a `tip` saying so.
A parameter a tool does not take is refused (`invalid_input`, message
`unsupported parameter`, one detail per parameter), never ignored. MCP tools
advertise this (`additionalProperties: false`).
GET takes the same fields as query parameters, read by each tool's own schema:
lists comma-separated or repeated (`marketplaces=ebay,cardmarket`), numbers
and booleans as written (`min_price=12.5`, `literal=true`), maps as JSON
(`attributes={"Set":["Base Set"]}`).
Every call is logged (the `USAGE` Durable Object, one SQLite table, 30 days):
client, tool, query (the URL or the search text), the other args as JSON
(never headers, bodies, scripts or cursors), domain, store, search type,
status, the error and what the caller was told about it (`error_detail`),
cache hit, attempts, time taken, estimated cost and the backend that
served it (an opaque `backend_id`; admins also get its name); a
`shopping_search` or `shopping_cards` logs one row per store with that store's cost. A client
reads its own log: `GET /v1/usage` (calls, paid calls, cache hit rate,
errors, cost and time by tool, domain, store, backend, search type and day, plus
today's spend against its cap; `days=1..30`) and `GET /v1/usage/log` (rows,
newest first; filter with `tool`, `domain`, `store`, `search_type`, `query`,
`key_label`, `paid_only`, `errors_only`, `cache_hits_only`; pass the returned
`next_before` as `before` to read on). MCP clients get the same as
the `usage` and `usage_log` tools. Admin clients may pass `client=<name>`, or
`client=*` for every client.
`GET /v1/admin/dashboard` (admin clients only) gives every client's usage at
once, stacked by client x tool and day x tool, with today's spend against each
cap. The maintainers' dashboard (dash.ly.tl, its own repository) reads it and
`/v1/usage/log`.
Operators also get `GET /v1/admin/providers`, `GET /v1/admin/spending`
(today's estimated spend and cap per client) and `GET /v1/admin/cache?cache_key=<key>`
(one cache entry, by the `mcpy.cache.key` a log shows), admin clients only.
```bash
curl -s https://tools.example.com/v1/fetch \
-H "Authorization: Bearer $KEY" -H "content-type: application/json" \
-d '{"url":"https://elie.net","max_chars":5000}'
# URL-only agents can pass everything as query parameters:
curl -s "https://tools.example.com/v1/search?query=cloudflare&type=news&recency=week&max_results=5&key=$KEY"
```
## Run your own server
```bash
npm install
cp apps/server/.dev.vars.example apps/server/.dev.vars # local secrets, never committed
npm run dev # http://localhost:8787
npx wrangler secret put MCPY_CLIENTS -c apps/server/wrangler.jsonc # name[/label]:key[:admin][:tools],...
npx wrangler secret put FIRECRAWL_API_KEY -c apps/server/wrangler.jsonc
npm run deploy
```
Wrangler creates the KV namespace (cache), Analytics Engine dataset
(metrics), rate limiter and spending Durable Object on first deploy. The `lytl` environment in
`apps/server/wrangler.jsonc` is the maintainers' deployment at
`omnitoolkit.app` (and `tools.ly.tl` while its clients move over), a complete custom-domain example
(`npm run deploy -- --env lytl`).
### The website
Optionally, people sign in (GitHub, Google, Apple) and serve themselves: a daily budget, API keys, MCP
clients connected by signing in, and charts of what they used and spent. Set-up is in
[docs/SELF-SERVICE.md](docs/SELF-SERVICE.md); without it the server knows only the keys below.
### Clients and keys
`MCPY_CLIENTS` lists `name[/label]:key[:admin][:tools]` entries (keys 24+ characters, may
contain ":"). A `+`-joined list of tool names limits what a client sees:
`marianna:<key>:shopping_fashion+shopping_similar+shopping_item` lists only those
three over MCP and gets 403 on every other REST route. Any MCP tool name works,
plus `usage` and `usage_log` (the client's own usage); an unknown name stops the
Worker from starting. Without a list a client has every tool its role may have.
`USER_TOOLS` and `ADMIN_TOOLS` (vars, comma separated) cap each role:
`USER_TOOLS=shopping_fashion,shopping_similar,shopping_item,usage` gives every
user key at most those, and an entry listing more is refused at startup. Unset,
a role may have every tool. A client may hold several keys, one per app, all under its one
rate limit, daily cap and usage: `elie/claude:<key1>,elie/chatgpt:<key2>`. The
label is logged with each call (`key_label`), so a leaked key can be found and
replaced on its own; one name's keys need distinct labels and the same role. A key is accepted as `Authorization: Bearer`, `X-API-Key`, or
`?key=` for web agents that can only be given a URL. Give those their own
key: URLs can end up in browser history and proxy logs. (Cloudflare
invocation logs, which record full URLs, are disabled in `wrangler.jsonc`.)
Each client is rate-limited separately and named in every log line, span and
metric; failed authentications are rate-limited per IP. With no clients
configured, everything is rejected. Non-admin calls to admin routes get 403.
### Spending caps
`DAILY_BUDGET_USD` caps what each client may spend on paid sources per UTC
day, using mcpy's per-call cost estimates (Firecrawl, Bright Data, Cloudflare
Browser Run, OpenAlex). `CLIENT_DAILY_BUDGETS_USD` overrides it per client:
`cardy:0.5,ops:unlimited`. Over its cap a client still gets cached results
and free sources (direct fetch, arXiv, PubMed); when those cannot answer it
gets `budget_exceeded` (429) with `Retry-After` until midnight UTC. Totals
live in the `BUDGET` Durable Object, one per client; requests already in
flight when the cap is crossed still finish.
Every REST operation's response says where the client stands, so it can
pace itself without calling `/v1/usage`:
| Header | Value |
| --- | --- |
| `X-Mcpy-Cache` | `hit`, `miss` or `bypass` (answered calls) |
| `X-Mcpy-Cost-Usd` | what this call counted against the cap (answered calls) |
| `X-Mcpy-Budget-Used-Usd` | today's spend, this call included (clients with a cap) |
| `X-Mcpy-Budget-Limit-Usd` | the daily cap |
| `X-Mcpy-Budget-Remaining-Usd` | what is left of it today |
| `X-Mcpy-Budget-Reset` | seconds until 00:00 UTC, when the cap resets |
| `RateLimit-Policy`, `X-RateLimit-Limit` | the per-key request limit (360 a minute) |
Today's spend is read while the call runs, so calls running at the same time
may not count each other. The request limit's own count is not reported:
Cloudflare's rate-limit binding only answers whether a request may run.
### Alerts
With `PUSHOVER_TOKEN` and `PUSHOVER_USER` set (secrets), the server sends the
owner a Pushover alert when:
- a paid source answers 402 (out of credits, high priority) or 429 after
retries (rate limit or quota, normal priority). Each provider and kind
alerts at most once per `ALERT_COOLDOWN_SECONDS` (6 hours by default); the
window is kept in the `CACHE` KV namespace. Calls keep falling back to the
next source meanwhile.
- a client is running low: its spend today passes `CAP_WARNING_PERCENT` of
its daily cap (80% by default), so you can raise the cap before it stops.
- a client reaches its daily cap.
Each cap alert is sent once per client per UTC day, by the request whose
spend crossed the line; a single request that jumps both lines sends only the
cap alert.
A failing push is logged (`pushover alert failed`), never retried through
Pushover itself.
### Configuration
| Var | Default | Purpose |
| --- | --- | --- |
| `MCPY_CLIENTS` (secret) | - | API clients |
| `SITE_URL`, `AUTH_SECRET` (secret) | - | Turn the website on, with the `ACCOUNTS` database ([docs/SELF-SERVICE.md](docs/SELF-SERVICE.md), which also lists the sign-in credentials) |
| `ADMIN_ACCOUNTS` | - | Signed-in admins, as `provider:account-id` |
| `PERSON_DAILY_BUDGET_USD` / `SIGNED_IN_DAILY_BUDGET_USD` | `0.25` / `5` | Estimated USD a day for a signed-in person, and for all of them on that default together |
| `PAGE_PROVIDERS` | `direct,cloudflare_browser,firecrawl,brightdata` | Page fallback order |
| `SEARCH_PROVIDERS` | `serpent,firecrawl,brightdata` | Search fallback order (cheapest first) |
| `PAPER_PROVIDERS` | `openalex,arxiv,pubmed,semantic_scholar` | Paper index order |
| `CRYPTO_PROVIDERS` | `coinmetrics,kaspa,dash,mempool,coingecko,miningpoolstats` | Crypto sources, merged field by field |
| `STOCK_PROVIDERS` | `yahoo,nasdaq,alphavantage,edgar` | Stock sources: quotes and history go down the list for the symbols earlier ones did not know; fundamentals come from filings |
| `DECISION_PROVIDERS` | `clef,clef_flash` | Decision models, tried in order, 3 s each; they score how well listings match (`shopping_search`). Need a Workers AI binding named `AI` (`"ai": { "binding": "AI" }`); without it nothing is scored |
| `LISTING_PROVIDERS` | `serpent` | Marketplace listing APIs, used only when no page source could fetch a shopping site's search page (today: the eBay sites) |
| `ATTEMPT_TIMEOUT_MS` / `DEADLINE_MS` | `20000` / `60000` | Per attempt / per call |
| `RETRIES` | `2` | Retries per upstream request |
| `DAILY_BUDGET_USD` | - (`5` in `wrangler.jsonc`) | Estimated USD each client may spend on paid sources per UTC day |
| `CLIENT_DAILY_BUDGETS_USD` | - | Per-client caps: `name:usd` or `name:unlimited`, comma-separated |
| `PUSHOVER_TOKEN`, `PUSHOVER_USER` (secrets) | - | Pushover app token and user key; enables owner alerts |
| `CAP_WARNING_PERCENT` | `80` | Share of a client's daily cap that triggers the "running low" alert; `100` sends only the cap alert |
| `ALERT_COOLDOWN_SECONDS` | `21600` | Quiet time before the same provider quota alert repeats |
| `MAX_RESPONSE_BYTES` | `5000000` | Largest upstream body |
| `PAGE_CACHE_TTL_SECONDS` / `SEARCH_CACHE_TTL_SECONDS` / `PAPER_CACHE_TTL_SECONDS` | `3600` / `900` / `86400` | How long answers are kept. Each call reads only as old as its `max_age` allows, so keeping them longer only lets callers opt in to older copies |
| `DEFAULT_USER_AGENT` | `default` | `default`, `chrome`, `safari`, `firefox`, `mobile`, `googlebot` |
| `USER_AGENT_STRING` | - | Replace the `default` user-agent string |
| `SEC_USER_AGENT` | `mcpy/1.0 (+https://www.npmjs.com/package/mcpy)` | User agent for company filings. SEC wants a tool or service and a contact, and refuses `default` (it links to github.com); set this only to name your own |
| `ALLOWED_HOSTNAMES` | - | Accepted Host headers (set on custom domains) |
| `ALLOWED_ORIGIN_HOSTNAMES` | - | Extra browser origins allowed to call `/mcp` |
| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` |
| `OTEL_EXPORTER_OTLP_ENDPOINT` / `OTEL_EXPORTER_OTLP_HEADERS` | - | Export traces + logs (OTLP/HTTP JSON) |
| `OTEL_SERVICE_NAME` / `DEPLOYMENT_ENV` | `mcpy` / `production` | Resource attributes |
| `BROWSER` (binding) | bound in wrangler.jsonc | Cloudflare Browser Rendering with no API token; takes precedence over the REST settings below |
| `CF_ACCOUNT_ID`, `CF_BROWSER_API_TOKEN` | - | Cloudflare Browser Run over REST, for hosts without the binding |
| `FIRECRAWL_API_KEY`, `FIRECRAWL_API_URL` | - | Firecrawl (URL for self-hosted) |
| `FIRECRAWL_USD_PER_CREDIT` | `0.0038` (Hobby) | What a Firecrawl credit costs on your plan; cost estimates and caps use it (a scrape is 1 credit, a search 2 per 10 results) |
| `BRIGHTDATA_API_KEY`, `BRIGHTDATA_UNLOCKER_ZONE`, `BRIGHTDATA_SERP_ZONE` | - | Bright Data |
| `SERPENT_API_KEY` | - | Serpent (apiserpent.com): web, news and image search ($0.60 per 1,000 calls on the default tier) and the eBay listing fallback ($0.40 per 1,000). Prepaid credit; a 402 means it ran out and search falls back to the next source |
| `OPENALEX_API_KEY` | - | Free at openalex.org/settings/api. Needed on Cloudflare: without it OpenAlex shares one small daily budget per IP, and Workers share IPs, so it answers 429 |
| `ALPHAVANTAGE_API_KEY` | - | Free key from alphavantage.co (25 requests a day): the last stock source, for quotes and the last 100 days; skipped without it |
| `SEMANTIC_SCHOLAR_API_KEY` | - | Enables Semantic Scholar (anonymous calls are rate-limited) |
| `NCBI_API_KEY`, `NCBI_EMAIL` | - | Optional for PubMed: a free key raises the limit from 3 to 10 requests/s |
| `PAPER_CACHE_TTL_SECONDS` | `86400` | Paper search cache TTL |
| `THOROUGH_GRACE_MS` | `8000` | Thorough mode: how long to wait for other sources after the first answers |
Everything is validated with zod at startup; a bad value fails closed with a
clear log line. A provider without credentials is skipped.
### Paper indexes
OpenAlex (250M+ works with citations, venues and open-access links), arXiv
(preprints, always free to read) and PubMed (37M+ biomedical citations, with
free PubMed Central full text when available) work without a key, but on
Cloudflare OpenAlex needs one in practice (see `OPENALEX_API_KEY`): it is the
only keyless index that sorts by citations; Semantic Scholar
is used when `SEMANTIC_SCHOLAR_API_KEY` is set. `collection: preprints` or
`collection: biomedical` targets the indexes covering those collections
directly; without it, every index is eligible. Dates are when a paper became
available: an article published online in 2026 for a 2027 issue shows 2026. In `thorough` mode the same
paper found in several indexes is merged by DOI, arXiv id or title, keeping
the highest citation count. `author` resolves the name to an OpenAlex author profile, and maps to arXiv
`au:` terms and PubMed `[au]` (Semantic Scholar cannot filter by author); with
no query, an author's papers rank by citations. Sorting by citations or newest matches title and
abstract only (OpenAlex full-text matching ranked off-topic classics first).
arXiv asks for one request every 3 s and throttles otherwise, so mcpy spaces
its requests and retries patiently; its answers can take up to ~30 s.
### Bright Data setup
Create two zones in the Bright Data control panel (Proxies & Scraping):
- **Web Unlocker API** (e.g. `mcpy_unlocker`) → `BRIGHTDATA_UNLOCKER_ZONE`
- **SERP API** with data format **Full JSON** (e.g. `mcpy_serp`) → `BRIGHTDATA_SERP_ZONE`.
Light JSON only carries top organic results, so news, images, videos,
shopping and places would come back empty.
Measured on 2026-10-22: unlocker requests took 2-38 s and SERP requests
4-50 s, so mcpy gives them 45-50 s attempt budgets and keeps them after the
faster providers in the default order. Searches without a country default to
US English (Bright Data otherwise geolocates at random). Google Jobs through
the SERP API failed upstream, so `type=jobs` is not offered for Bright Data.
## Observability
- **Logs**: one structured JSON line per operation in Workers Logs, with
`client.name`, `mcpy.request.id`, trace ids, cache status, cost.
- **Traces**: set `OTEL_EXPORTER_OTLP_ENDPOINT` to send spans and logs to
any OTLP collector (Cloudflare Traces, Grafana, Honeycomb, ...). Incoming
`traceparent` headers are honored.
- **Metrics**: Analytics Engine, one row per operation and provider attempt.
Column layout in `packages/mcpy/src/telemetry/sinks/analytics.ts`.
```sql
SELECT blob7 AS client, blob3 AS provider, blob4 AS outcome, count() AS n,
avg(double1) AS avg_ms, sum(double3) AS usd
FROM mcpy WHERE blob1 = 'mcpy.attempt' AND timestamp > NOW() - INTERVAL '7' DAY
GROUP BY client, provider, outcome ORDER BY n DESC
```
## Develop
```bash
npm test # unit, contract, regression, structure, perf
npm run test:e2e # real Worker in workerd, MCP + REST against elie.net
npm run test:live # real provider APIs (keys from apps/server/.dev.vars)
npm run typecheck
```
## License
Apache-2.0
This server cannot be deployed
Maintenance
ActivityActive
ResponsivenessNo recent community issues