api-everything 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- api_everything/__init__.py +3 -0
- api_everything/__main__.py +8 -0
- api_everything/check.py +168 -0
- api_everything/chrome_cmd.py +131 -0
- api_everything/cli.py +803 -0
- api_everything/config.py +321 -0
- api_everything/delivery.py +518 -0
- api_everything/delivery_git.py +94 -0
- api_everything/driver/__init__.py +37 -0
- api_everything/driver/attach.py +95 -0
- api_everything/driver/base.py +80 -0
- api_everything/driver/chrome.py +127 -0
- api_everything/driver/profile.py +84 -0
- api_everything/engine.py +381 -0
- api_everything/errors.py +23 -0
- api_everything/hooks.py +52 -0
- api_everything/login.py +95 -0
- api_everything/mcp_bridge.py +249 -0
- api_everything/metrics.py +87 -0
- api_everything/mock_site/__init__.py +5 -0
- api_everything/mock_site/__main__.py +18 -0
- api_everything/mock_site/app.py +262 -0
- api_everything/pipeline.py +934 -0
- api_everything/pool.py +553 -0
- api_everything/ratelimit.py +67 -0
- api_everything/recipe/__init__.py +6 -0
- api_everything/recipe/actions.py +56 -0
- api_everything/recipe/jsonpath.py +22 -0
- api_everything/recipe/loader.py +142 -0
- api_everything/recipe/params.py +120 -0
- api_everything/recipe/schema.py +235 -0
- api_everything/recipes/alignmentforum/feed.yaml +15 -0
- api_everything/recipes/alpine_docs/search.yaml +32 -0
- api_everything/recipes/angular_docs/search.yaml +32 -0
- api_everything/recipes/anthropic_status/summary.yaml +17 -0
- api_everything/recipes/apis_guru/providers.yaml +15 -0
- api_everything/recipes/arbeitnow/jobs.yaml +20 -0
- api_everything/recipes/arin_rdap/ip.yaml +24 -0
- api_everything/recipes/artifacthub/browse.yaml +22 -0
- api_everything/recipes/artifacthub/search.yaml +24 -0
- api_everything/recipes/astro_docs/search.yaml +32 -0
- api_everything/recipes/atlassian_status/summary.yaml +17 -0
- api_everything/recipes/babel_docs/search.yaml +32 -0
- api_everything/recipes/binance/price.yaml +24 -0
- api_everything/recipes/bugzilla/bugs.yaml +24 -0
- api_everything/recipes/bundlephobia/size.yaml +24 -0
- api_everything/recipes/caddy_docs/search.yaml +32 -0
- api_everything/recipes/caniuse/search.yaml +24 -0
- api_everything/recipes/capacitor_docs/search.yaml +32 -0
- api_everything/recipes/cdnjs/library.yaml +22 -0
- api_everything/recipes/cdnjs/search.yaml +27 -0
- api_everything/recipes/certspotter/issuances.yaml +27 -0
- api_everything/recipes/cheerio_docs/search.yaml +32 -0
- api_everything/recipes/circleci_status/summary.yaml +17 -0
- api_everything/recipes/cisa_kev/catalog.yaml +17 -0
- api_everything/recipes/civitai/models.yaml +26 -0
- api_everything/recipes/cloudflare_status/summary.yaml +17 -0
- api_everything/recipes/cncf_landscape/projects.yaml +20 -0
- api_everything/recipes/cncf_landscape/ui.yaml +18 -0
- api_everything/recipes/coinbase/rates.yaml +24 -0
- api_everything/recipes/coingecko/trending.yaml +17 -0
- api_everything/recipes/conda_forge/package.yaml +25 -0
- api_everything/recipes/crates/categories.yaml +15 -0
- api_everything/recipes/crates/downloads.yaml +22 -0
- api_everything/recipes/crates/keywords.yaml +15 -0
- api_everything/recipes/crates/reverse_deps.yaml +22 -0
- api_everything/recipes/crates/search.yaml +24 -0
- api_everything/recipes/crates/summary.yaml +15 -0
- api_everything/recipes/crates/user.yaml +22 -0
- api_everything/recipes/crates/versions.yaml +22 -0
- api_everything/recipes/crossref/works.yaml +24 -0
- api_everything/recipes/cve_org/record.yaml +24 -0
- api_everything/recipes/debian_sources/search.yaml +24 -0
- api_everything/recipes/deps_dev/npm_spa.yaml +22 -0
- api_everything/recipes/deps_dev/package.yaml +23 -0
- api_everything/recipes/devdocs/index.yaml +18 -0
- api_everything/recipes/devto/articles.yaml +26 -0
- api_everything/recipes/devto/latest.yaml +18 -0
- api_everything/recipes/devto/tags.yaml +18 -0
- api_everything/recipes/devto/top.yaml +18 -0
- api_everything/recipes/digitalocean_status/summary.yaml +17 -0
- api_everything/recipes/digitalocean_status/ui.yaml +15 -0
- api_everything/recipes/discord_status/summary.yaml +17 -0
- api_everything/recipes/dns_google/resolve.yaml +24 -0
- api_everything/recipes/drizzle_docs/search.yaml +32 -0
- api_everything/recipes/echojs/latest.yaml +17 -0
- api_everything/recipes/ecosystems/package.yaml +25 -0
- api_everything/recipes/endoflife/product.yaml +24 -0
- api_everything/recipes/epss/score.yaml +24 -0
- api_everything/recipes/exchangerate/latest.yaml +24 -0
- api_everything/recipes/firefox_addons/search.yaml +26 -0
- api_everything/recipes/fly_status/summary.yaml +17 -0
- api_everything/recipes/formik_docs/search.yaml +32 -0
- api_everything/recipes/frankfurter/rates.yaml +24 -0
- api_everything/recipes/gcp_status/incidents.yaml +20 -0
- api_everything/recipes/github/explore.yaml +35 -0
- api_everything/recipes/github/gists.yaml +18 -0
- api_everything/recipes/github/issues.yaml +30 -0
- api_everything/recipes/github/license.yaml +23 -0
- api_everything/recipes/github/org.yaml +22 -0
- api_everything/recipes/github/releases.yaml +30 -0
- api_everything/recipes/github/repo.yaml +28 -0
- api_everything/recipes/github/user.yaml +22 -0
- api_everything/recipes/github_advisories/list.yaml +20 -0
- api_everything/recipes/github_status/summary.yaml +17 -0
- api_everything/recipes/github_status/ui.yaml +15 -0
- api_everything/recipes/gitlab/issues.yaml +24 -0
- api_everything/recipes/gitlab/repo.yaml +21 -0
- api_everything/recipes/gitlab/search.yaml +26 -0
- api_everything/recipes/go_proxy/latest.yaml +24 -0
- api_everything/recipes/grafana_status/summary.yaml +17 -0
- api_everything/recipes/hackage/versions.yaml +24 -0
- api_everything/recipes/hackernews/ask.yaml +18 -0
- api_everything/recipes/hackernews/front_page.yaml +18 -0
- api_everything/recipes/hackernews/item.yaml +21 -0
- api_everything/recipes/hackernews/jobs.yaml +18 -0
- api_everything/recipes/hackernews/latest.yaml +25 -0
- api_everything/recipes/hackernews/search.yaml +34 -0
- api_everything/recipes/hackernews/show.yaml +18 -0
- api_everything/recipes/hashicorp_releases/list.yaml +27 -0
- api_everything/recipes/hashicorp_status/summary.yaml +17 -0
- api_everything/recipes/helm_docs/search.yaml +32 -0
- api_everything/recipes/heroku_status/current.yaml +17 -0
- api_everything/recipes/hexpm/search.yaml +27 -0
- api_everything/recipes/hf_papers/daily.yaml +20 -0
- api_everything/recipes/himalayas/jobs.yaml +17 -0
- api_everything/recipes/homebrew/cask.yaml +22 -0
- api_everything/recipes/homebrew/formula.yaml +26 -0
- api_everything/recipes/hono_docs/search.yaml +32 -0
- api_everything/recipes/httpbin/json.yaml +17 -0
- api_everything/recipes/httpbin/uuid.yaml +15 -0
- api_everything/recipes/huggingface/datasets.yaml +25 -0
- api_everything/recipes/huggingface/model_info.yaml +27 -0
- api_everything/recipes/huggingface/models.yaml +28 -0
- api_everything/recipes/huggingface/spaces.yaml +25 -0
- api_everything/recipes/inspirehep/papers.yaml +24 -0
- api_everything/recipes/ionic_docs/search.yaml +32 -0
- api_everything/recipes/ipify/ipv4.yaml +17 -0
- api_everything/recipes/ipwho/lookup.yaml +24 -0
- api_everything/recipes/jest_docs/search.yaml +32 -0
- api_everything/recipes/jsdelivr/gh.yaml +27 -0
- api_everything/recipes/jsdelivr/npm.yaml +24 -0
- api_everything/recipes/jsr/search.yaml +27 -0
- api_everything/recipes/launchdarkly_status/summary.yaml +17 -0
- api_everything/recipes/lemmy/hot.yaml +17 -0
- api_everything/recipes/lesswrong/feed.yaml +17 -0
- api_everything/recipes/llamaindex_docs/search.yaml +32 -0
- api_everything/recipes/lobsters/hottest.yaml +20 -0
- api_everything/recipes/luma/category.yaml +22 -0
- api_everything/recipes/luma/events.yaml +17 -0
- api_everything/recipes/mastodon/explore.yaml +26 -0
- api_everything/recipes/mastodon/tag.yaml +23 -0
- api_everything/recipes/mastodon/trends_tags.yaml +18 -0
- api_everything/recipes/mdn/search.yaml +24 -0
- api_everything/recipes/metacpan/search.yaml +24 -0
- api_everything/recipes/microlink/preview.yaml +24 -0
- api_everything/recipes/mikro_orm_docs/search.yaml +32 -0
- api_everything/recipes/mock/items.yaml +35 -0
- api_everything/recipes/mongodb_status/summary.yaml +17 -0
- api_everything/recipes/nager_date/holidays.yaml +32 -0
- api_everything/recipes/neon_docs/search.yaml +32 -0
- api_everything/recipes/nestjs_docs/search.yaml +32 -0
- api_everything/recipes/netlify_status/summary.yaml +17 -0
- api_everything/recipes/nextjs_docs/search.yaml +32 -0
- api_everything/recipes/nodejs_dist/releases.yaml +17 -0
- api_everything/recipes/npm/dist_tags.yaml +22 -0
- api_everything/recipes/npm/package.yaml +25 -0
- api_everything/recipes/npm/search.yaml +25 -0
- api_everything/recipes/npm_downloads/weekly.yaml +24 -0
- api_everything/recipes/npm_status/summary.yaml +17 -0
- api_everything/recipes/npmtrends/compare.yaml +22 -0
- api_everything/recipes/nuget/search.yaml +27 -0
- api_everything/recipes/nuxt_docs/search.yaml +32 -0
- api_everything/recipes/nvd/cve.yaml +22 -0
- api_everything/recipes/nvd/cves.yaml +24 -0
- api_everything/recipes/open_elevation/lookup.yaml +29 -0
- api_everything/recipes/openai_status/summary.yaml +17 -0
- api_everything/recipes/opencollective/search.yaml +22 -0
- api_everything/recipes/openfda/events.yaml +17 -0
- api_everything/recipes/openlibrary/search.yaml +24 -0
- api_everything/recipes/openmeteo/forecast.yaml +17 -0
- api_everything/recipes/openrouter/models.yaml +20 -0
- api_everything/recipes/openstreetmap/geocode.yaml +27 -0
- api_everything/recipes/openstreetmap/reverse.yaml +27 -0
- api_everything/recipes/osv/vuln.yaml +24 -0
- api_everything/recipes/packagist/search.yaml +27 -0
- api_everything/recipes/peps/list.yaml +17 -0
- api_everything/recipes/pinia_docs/search.yaml +32 -0
- api_everything/recipes/pkg_go_dev/browse.yaml +15 -0
- api_everything/recipes/pkg_go_dev/package.yaml +25 -0
- api_everything/recipes/playwright_docs/search.yaml +32 -0
- api_everything/recipes/pnpm_docs/search.yaml +32 -0
- api_everything/recipes/pokeapi/pokemon.yaml +24 -0
- api_everything/recipes/posthog_docs/search.yaml +32 -0
- api_everything/recipes/postman_echo/get.yaml +24 -0
- api_everything/recipes/postman_status/summary.yaml +17 -0
- api_everything/recipes/preact_docs/search.yaml +32 -0
- api_everything/recipes/pubdev/search.yaml +24 -0
- api_everything/recipes/pubmed/search.yaml +24 -0
- api_everything/recipes/puppeteer_docs/search.yaml +32 -0
- api_everything/recipes/pypi/package.yaml +24 -0
- api_everything/recipes/pypi/version.yaml +27 -0
- api_everything/recipes/quay/search.yaml +27 -0
- api_everything/recipes/quora/answers.yaml +46 -0
- api_everything/recipes/qwik_docs/search.yaml +32 -0
- api_everything/recipes/ray_docs/search.yaml +32 -0
- api_everything/recipes/rdap/domain.yaml +24 -0
- api_everything/recipes/react_docs/search.yaml +32 -0
- api_everything/recipes/react_hook_form_docs/search.yaml +32 -0
- api_everything/recipes/reactrouter_docs/search.yaml +32 -0
- api_everything/recipes/reddit/search.yaml +48 -0
- api_everything/recipes/reddit_status/summary.yaml +17 -0
- api_everything/recipes/remoteok/jobs.yaml +17 -0
- api_everything/recipes/render_status/summary.yaml +17 -0
- api_everything/recipes/repology/project.yaml +24 -0
- api_everything/recipes/ripe_stat/prefix.yaml +24 -0
- api_everything/recipes/rollup_docs/search.yaml +32 -0
- api_everything/recipes/rsbuild_docs/search.yaml +32 -0
- api_everything/recipes/rubygems/gem.yaml +22 -0
- api_everything/recipes/rubygems/search.yaml +27 -0
- api_everything/recipes/sendgrid_status/summary.yaml +17 -0
- api_everything/recipes/sequelize_docs/search.yaml +32 -0
- api_everything/recipes/shodan_internetdb/host.yaml +24 -0
- api_everything/recipes/shopify_status/summary.yaml +17 -0
- api_everything/recipes/sigstore_rekor/log.yaml +17 -0
- api_everything/recipes/slack_status/current.yaml +17 -0
- api_everything/recipes/spdx/licenses.yaml +17 -0
- api_everything/recipes/stackexchange/sites.yaml +20 -0
- api_everything/recipes/stackoverflow/answers.yaml +15 -0
- api_everything/recipes/stackoverflow/questions.yaml +18 -0
- api_everything/recipes/stackoverflow/search.yaml +27 -0
- api_everything/recipes/stackoverflow/tags.yaml +18 -0
- api_everything/recipes/strapi_docs/search.yaml +32 -0
- api_everything/recipes/strawberry_docs/search.yaml +32 -0
- api_everything/recipes/stripe_status/current.yaml +17 -0
- api_everything/recipes/substack/explore.yaml +22 -0
- api_everything/recipes/substack/search.yaml +31 -0
- api_everything/recipes/sunrise_sunset/times.yaml +29 -0
- api_everything/recipes/supabase_status/summary.yaml +17 -0
- api_everything/recipes/swr_docs/search.yaml +32 -0
- api_everything/recipes/tanstack_docs/search.yaml +32 -0
- api_everything/recipes/tc39/proposals.yaml +20 -0
- api_everything/recipes/techempower/results.yaml +15 -0
- api_everything/recipes/temporal_docs/search.yaml +32 -0
- api_everything/recipes/terraform_registry/browse.yaml +25 -0
- api_everything/recipes/terraform_registry/search.yaml +24 -0
- api_everything/recipes/testing_library_docs/search.yaml +32 -0
- api_everything/recipes/tvmaze/shows.yaml +24 -0
- api_everything/recipes/twilio_status/summary.yaml +17 -0
- api_everything/recipes/upstash_docs/search.yaml +32 -0
- api_everything/recipes/valibot_docs/search.yaml +32 -0
- api_everything/recipes/vercel_status/summary.yaml +17 -0
- api_everything/recipes/vercel_status/ui.yaml +15 -0
- api_everything/recipes/vue_docs/search.yaml +32 -0
- api_everything/recipes/w3c/specs.yaml +17 -0
- api_everything/recipes/wayback/available.yaml +24 -0
- api_everything/recipes/webdriverio_docs/search.yaml +32 -0
- api_everything/recipes/webpack_docs/search.yaml +32 -0
- api_everything/recipes/wikidata/entity.yaml +22 -0
- api_everything/recipes/wikidata/search.yaml +24 -0
- api_everything/recipes/wikimedia_commons/search.yaml +25 -0
- api_everything/recipes/wikipedia/search.yaml +25 -0
- api_everything/recipes/wikipedia/summary.yaml +33 -0
- api_everything/recipes/wordpress_plugins/search.yaml +24 -0
- api_everything/recipes/wordpress_themes/search.yaml +24 -0
- api_everything/recipes/worldbank/indicator.yaml +17 -0
- api_everything/recipes/zenodo/records.yaml +24 -0
- api_everything/recipes/zippopotam/in.yaml +22 -0
- api_everything/recipes/zippopotam/lookup.yaml +29 -0
- api_everything/recipes/zoom_status/summary.yaml +17 -0
- api_everything/record.py +327 -0
- api_everything/record_session.py +364 -0
- api_everything/repair.py +717 -0
- api_everything/repair_ai.py +194 -0
- api_everything/runlog.py +61 -0
- api_everything/server.py +323 -0
- api_everything-0.5.0.dist-info/METADATA +363 -0
- api_everything-0.5.0.dist-info/RECORD +281 -0
- api_everything-0.5.0.dist-info/WHEEL +4 -0
- api_everything-0.5.0.dist-info/entry_points.txt +2 -0
- api_everything-0.5.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""`api-everything mcp`: a stdio MCP server that exposes recipes as tools to an agent.
|
|
2
|
+
|
|
3
|
+
It is a thin bridge to a running daemon, not a second pool: every tool call becomes
|
|
4
|
+
`POST /v1/run/{recipe}`, so the warm Chrome pool, rate limits, API token and logged-in profiles
|
|
5
|
+
are shared and nothing is duplicated. The bridge never starts a daemon or a browser. If no
|
|
6
|
+
daemon answers, it still starts, and says so in the tool list and in every tool call.
|
|
7
|
+
|
|
8
|
+
By default only recipes that are `stable` and need no login are offered. Experimental recipes
|
|
9
|
+
and logged-in (`profile:`) recipes, which would act as you on an account, are opt-in.
|
|
10
|
+
|
|
11
|
+
Nothing here writes to stdout: on stdio, stdout belongs to the protocol.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import json
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
import mcp_types as types
|
|
23
|
+
from mcp.server import NotificationOptions, Server
|
|
24
|
+
from mcp.server.stdio import stdio_server
|
|
25
|
+
from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler, ToolsListChanged
|
|
26
|
+
|
|
27
|
+
from api_everything import __version__
|
|
28
|
+
|
|
29
|
+
# Offered instead of the recipe tools while the daemon cannot be reached, so an agent sees why.
|
|
30
|
+
NOT_RUNNING_TOOL = "api_everything_not_running"
|
|
31
|
+
RUN_TIMEOUT_SECONDS = 120.0 # longer than the daemon's own deadline cap, which stays in charge
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class BridgeProblem(Exception):
|
|
35
|
+
"""The daemon cannot serve this request. The message says what to do."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def tool_name(recipe_name: str) -> str:
|
|
39
|
+
"""Tool names allow letters, digits, `_` and `-`; recipe names are `site.endpoint`."""
|
|
40
|
+
return recipe_name.replace(".", "_")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Exposure:
|
|
45
|
+
include_experimental: bool = False
|
|
46
|
+
include_profiles: bool = False
|
|
47
|
+
|
|
48
|
+
def allows(self, summary: dict[str, Any]) -> bool:
|
|
49
|
+
if summary.get("status") != "stable" and not self.include_experimental:
|
|
50
|
+
return False
|
|
51
|
+
return summary.get("session") == "none" or self.include_profiles
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def input_schema(summary: dict[str, Any]) -> dict[str, Any]:
|
|
55
|
+
"""JSON Schema for a recipe's parameters, from the daemon's recipe summary.
|
|
56
|
+
|
|
57
|
+
The daemon stays the authority: it re-checks every value (patterns, lengths) and answers
|
|
58
|
+
`invalid_params`, which the agent receives as the tool's error.
|
|
59
|
+
"""
|
|
60
|
+
properties: dict[str, Any] = {}
|
|
61
|
+
required: list[str] = []
|
|
62
|
+
for name, spec in summary.get("params", {}).items():
|
|
63
|
+
prop: dict[str, Any] = {"type": spec["type"]}
|
|
64
|
+
if spec.get("description"):
|
|
65
|
+
prop["description"] = spec["description"]
|
|
66
|
+
if spec.get("default") is not None:
|
|
67
|
+
prop["default"] = spec["default"]
|
|
68
|
+
properties[name] = prop
|
|
69
|
+
if spec.get("required"):
|
|
70
|
+
required.append(name)
|
|
71
|
+
schema: dict[str, Any] = {
|
|
72
|
+
"type": "object",
|
|
73
|
+
"properties": properties,
|
|
74
|
+
"additionalProperties": False,
|
|
75
|
+
}
|
|
76
|
+
if required:
|
|
77
|
+
schema["required"] = required
|
|
78
|
+
return schema
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def to_tool(summary: dict[str, Any]) -> types.Tool:
|
|
82
|
+
notes = []
|
|
83
|
+
if summary.get("status") != "stable":
|
|
84
|
+
notes.append("EXPERIMENTAL: may be blocked by the site or return nothing.")
|
|
85
|
+
if summary.get("session") != "none":
|
|
86
|
+
notes.append("Runs as your logged-in account.")
|
|
87
|
+
notes.append("Reads the site's own JSON through a real browser; can take several seconds.")
|
|
88
|
+
description = " ".join([summary.get("description") or summary["name"], *notes])
|
|
89
|
+
read_only = summary.get("session") == "none" and not summary.get("uses_eval")
|
|
90
|
+
return types.Tool(
|
|
91
|
+
name=tool_name(summary["name"]),
|
|
92
|
+
title=summary["name"],
|
|
93
|
+
description=description,
|
|
94
|
+
input_schema=input_schema(summary),
|
|
95
|
+
annotations=types.ToolAnnotations(
|
|
96
|
+
# Only a recipe with no login and no custom JavaScript is certainly read-only. A
|
|
97
|
+
# logged-in or `eval` recipe can click and type as the user, so it makes no claim.
|
|
98
|
+
read_only_hint=True if read_only else None,
|
|
99
|
+
open_world_hint=True,
|
|
100
|
+
),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _error(text: str) -> types.CallToolResult:
|
|
105
|
+
return types.CallToolResult(content=[types.TextContent(text=text)], is_error=True)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class Bridge:
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
base_url: str,
|
|
112
|
+
*,
|
|
113
|
+
token: str | None = None,
|
|
114
|
+
exposure: Exposure | None = None,
|
|
115
|
+
client: httpx.AsyncClient | None = None,
|
|
116
|
+
) -> None:
|
|
117
|
+
self._base = base_url.rstrip("/")
|
|
118
|
+
self._headers = {"Authorization": f"Bearer {token}"} if token else {}
|
|
119
|
+
self._exposure = exposure or Exposure()
|
|
120
|
+
self._client = client or httpx.AsyncClient()
|
|
121
|
+
# True after a call showed the agent's tool list is out of date (see `call_tool`).
|
|
122
|
+
self.tools_stale = False
|
|
123
|
+
# Newer clients ask to be told about changes through `subscriptions/listen`.
|
|
124
|
+
self._bus = InMemorySubscriptionBus()
|
|
125
|
+
|
|
126
|
+
async def aclose(self) -> None:
|
|
127
|
+
await self._client.aclose()
|
|
128
|
+
|
|
129
|
+
async def _daemon(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
|
|
130
|
+
try:
|
|
131
|
+
return await self._client.request(
|
|
132
|
+
method, f"{self._base}{path}", headers=self._headers, **kwargs
|
|
133
|
+
)
|
|
134
|
+
except httpx.HTTPError as exc:
|
|
135
|
+
raise BridgeProblem(
|
|
136
|
+
f"no api-everything daemon is answering at {self._base} "
|
|
137
|
+
f"({type(exc).__name__}). Start it with `api-everything serve`, then try again."
|
|
138
|
+
) from exc
|
|
139
|
+
|
|
140
|
+
async def recipes(self) -> list[dict[str, Any]]:
|
|
141
|
+
"""The recipes the daemon serves that this bridge is allowed to offer."""
|
|
142
|
+
response = await self._daemon("GET", "/v1/recipes", timeout=10.0)
|
|
143
|
+
if response.status_code in (401, 403):
|
|
144
|
+
raise BridgeProblem(
|
|
145
|
+
f"the daemon at {self._base} refused the request ({response.status_code}). "
|
|
146
|
+
"Set API_EVERYTHING_TOKEN to the daemon's token for this bridge."
|
|
147
|
+
)
|
|
148
|
+
if response.status_code != 200:
|
|
149
|
+
raise BridgeProblem(f"the daemon at {self._base} answered {response.status_code}.")
|
|
150
|
+
listed = response.json().get("recipes", [])
|
|
151
|
+
return [summary for summary in listed if self._exposure.allows(summary)]
|
|
152
|
+
|
|
153
|
+
async def list_tools(self) -> list[types.Tool]:
|
|
154
|
+
try:
|
|
155
|
+
return [to_tool(summary) for summary in await self.recipes()]
|
|
156
|
+
except BridgeProblem as problem:
|
|
157
|
+
return [
|
|
158
|
+
types.Tool(
|
|
159
|
+
name=NOT_RUNNING_TOOL,
|
|
160
|
+
description=f"api-everything is not available: {problem}",
|
|
161
|
+
input_schema={"type": "object", "properties": {}},
|
|
162
|
+
)
|
|
163
|
+
]
|
|
164
|
+
|
|
165
|
+
async def call_tool(
|
|
166
|
+
self, name: str, arguments: dict[str, Any] | None
|
|
167
|
+
) -> types.CallToolResult:
|
|
168
|
+
self.tools_stale = False
|
|
169
|
+
try:
|
|
170
|
+
offered = {tool_name(s["name"]): s for s in await self.recipes()}
|
|
171
|
+
except BridgeProblem as problem:
|
|
172
|
+
return _error(str(problem))
|
|
173
|
+
summary = offered.get(name)
|
|
174
|
+
if summary is None:
|
|
175
|
+
# The daemon answers, so the agent's list is stale: it was built while the daemon
|
|
176
|
+
# was down, or recipes changed. Tell the client to list again.
|
|
177
|
+
self.tools_stale = True
|
|
178
|
+
if name == NOT_RUNNING_TOOL:
|
|
179
|
+
return _error(
|
|
180
|
+
"the api-everything daemon is running now; the tool list has changed, "
|
|
181
|
+
"refresh it (or reconnect this MCP server) to see the recipe tools"
|
|
182
|
+
)
|
|
183
|
+
return _error(f"unknown tool {name!r}: the recipes may have changed; list tools again")
|
|
184
|
+
|
|
185
|
+
params = {key: value for key, value in (arguments or {}).items() if value is not None}
|
|
186
|
+
try:
|
|
187
|
+
response = await self._daemon(
|
|
188
|
+
"POST", f"/v1/run/{summary['name']}", json=params, timeout=RUN_TIMEOUT_SECONDS
|
|
189
|
+
)
|
|
190
|
+
except BridgeProblem as problem:
|
|
191
|
+
return _error(str(problem))
|
|
192
|
+
try:
|
|
193
|
+
body = response.json()
|
|
194
|
+
except ValueError:
|
|
195
|
+
return _error(f"the daemon answered {response.status_code} without JSON")
|
|
196
|
+
if response.status_code != 200:
|
|
197
|
+
error = body.get("error", {})
|
|
198
|
+
text = f"{error.get('code', 'daemon_error')}: {error.get('message', 'run failed')}"
|
|
199
|
+
retry = (body.get("meta") or {}).get("retry_after")
|
|
200
|
+
if retry:
|
|
201
|
+
text += f" (retry after {retry}s)"
|
|
202
|
+
return _error(text)
|
|
203
|
+
meta = json.dumps(body.get("meta", {}), separators=(",", ":"))
|
|
204
|
+
return types.CallToolResult(
|
|
205
|
+
content=[
|
|
206
|
+
types.TextContent(text=json.dumps(body["data"], indent=2, ensure_ascii=False)),
|
|
207
|
+
types.TextContent(text=f"meta: {meta}"),
|
|
208
|
+
]
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
@staticmethod
|
|
212
|
+
def options(server: Server):
|
|
213
|
+
"""Tell clients the tool list can change (it follows the daemon's recipes)."""
|
|
214
|
+
return server.create_initialization_options(NotificationOptions(tools_changed=True))
|
|
215
|
+
|
|
216
|
+
def server(self) -> Server:
|
|
217
|
+
async def on_list_tools(ctx: Any, params: Any) -> types.ListToolsResult:
|
|
218
|
+
return types.ListToolsResult(tools=await self.list_tools())
|
|
219
|
+
|
|
220
|
+
async def on_call_tool(ctx: Any, params: types.CallToolRequestParams):
|
|
221
|
+
result = await self.call_tool(params.name, params.arguments)
|
|
222
|
+
if self.tools_stale: # best effort: a client that ignores it can still re-list
|
|
223
|
+
with contextlib.suppress(Exception):
|
|
224
|
+
await self._bus.publish(ToolsListChanged()) # newer protocol era
|
|
225
|
+
with contextlib.suppress(Exception):
|
|
226
|
+
await ctx.session.send_tool_list_changed() # handshake-era clients
|
|
227
|
+
return result
|
|
228
|
+
|
|
229
|
+
return Server(
|
|
230
|
+
"api-everything",
|
|
231
|
+
version=__version__,
|
|
232
|
+
instructions=(
|
|
233
|
+
"Each tool reads one website's own JSON through a real browser and returns "
|
|
234
|
+
"it. Calls can take several seconds and are rate limited per site; an error "
|
|
235
|
+
"such as rate_limited or queue_full says how long to wait."
|
|
236
|
+
),
|
|
237
|
+
on_list_tools=on_list_tools,
|
|
238
|
+
on_call_tool=on_call_tool,
|
|
239
|
+
on_subscriptions_listen=ListenHandler(self._bus),
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
async def serve_stdio(bridge: Bridge) -> None:
|
|
244
|
+
server = bridge.server()
|
|
245
|
+
try:
|
|
246
|
+
async with stdio_server() as (read_stream, write_stream):
|
|
247
|
+
await server.run(read_stream, write_stream, bridge.options(server))
|
|
248
|
+
finally:
|
|
249
|
+
await bridge.aclose()
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Prometheus / OpenTelemetry text exposition for operational SLO metrics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8"
|
|
9
|
+
|
|
10
|
+
# Standard latency buckets (in seconds) covering warm hits (<100ms) through cold/slow runs (60s).
|
|
11
|
+
LATENCY_BUCKETS_SECONDS: tuple[float, ...] = (
|
|
12
|
+
0.05,
|
|
13
|
+
0.1,
|
|
14
|
+
0.25,
|
|
15
|
+
0.5,
|
|
16
|
+
1.0,
|
|
17
|
+
2.5,
|
|
18
|
+
5.0,
|
|
19
|
+
10.0,
|
|
20
|
+
30.0,
|
|
21
|
+
60.0,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _escape_label(value: str) -> str:
|
|
26
|
+
return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def render_prometheus(snapshot: Mapping[str, Any]) -> str:
|
|
30
|
+
"""Format a pool metrics snapshot in Prometheus 0.0.4 text exposition format."""
|
|
31
|
+
lines: list[str] = []
|
|
32
|
+
lanes: Mapping[str, Mapping[str, Any]] = snapshot.get("lanes", {})
|
|
33
|
+
|
|
34
|
+
lines.append("# HELP browser_pool_queue_depth Current number of runs queued per browser lane.")
|
|
35
|
+
lines.append("# TYPE browser_pool_queue_depth gauge")
|
|
36
|
+
for label in sorted(lanes):
|
|
37
|
+
queued = lanes[label].get("queued", 0)
|
|
38
|
+
lines.append(f'browser_pool_queue_depth{{lane="{_escape_label(label)}"}} {queued}')
|
|
39
|
+
|
|
40
|
+
lines.append(
|
|
41
|
+
"# HELP browser_crash_restarts_total Total browser restarts per lane "
|
|
42
|
+
"(crashes or recycling)."
|
|
43
|
+
)
|
|
44
|
+
lines.append("# TYPE browser_crash_restarts_total counter")
|
|
45
|
+
for label in sorted(lanes):
|
|
46
|
+
restarts = lanes[label].get("chrome_restarts", 0)
|
|
47
|
+
lines.append(
|
|
48
|
+
f'browser_crash_restarts_total{{lane="{_escape_label(label)}"}} {restarts}'
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
runs: Mapping[str, Any] = snapshot.get("runs", {})
|
|
52
|
+
total_runs = int(runs.get("total", 0))
|
|
53
|
+
by_outcome: Mapping[str, int] = runs.get("by_outcome", {})
|
|
54
|
+
ok_runs = int(by_outcome.get("ok", 0))
|
|
55
|
+
success_rate = (ok_runs / total_runs) if total_runs > 0 else 1.0
|
|
56
|
+
|
|
57
|
+
lines.append("# HELP recipe_success_rate Ratio of successful recipe runs (0.0 to 1.0).")
|
|
58
|
+
lines.append("# TYPE recipe_success_rate gauge")
|
|
59
|
+
lines.append(f"recipe_success_rate {success_rate:.6f}")
|
|
60
|
+
|
|
61
|
+
if by_outcome:
|
|
62
|
+
lines.append("# HELP api_everything_runs_total Total recipe runs by outcome.")
|
|
63
|
+
lines.append("# TYPE api_everything_runs_total counter")
|
|
64
|
+
for outcome in sorted(by_outcome):
|
|
65
|
+
lines.append(
|
|
66
|
+
f'api_everything_runs_total{{outcome="{_escape_label(outcome)}"}} '
|
|
67
|
+
f"{by_outcome[outcome]}"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
hist: Mapping[str, Any] = snapshot.get("latency_histogram", {})
|
|
71
|
+
bounds: tuple[float, ...] = tuple(hist.get("bounds", LATENCY_BUCKETS_SECONDS))
|
|
72
|
+
counts: list[int] = list(hist.get("buckets", [0] * (len(bounds) + 1)))
|
|
73
|
+
latency_sum = float(hist.get("sum_seconds", 0.0))
|
|
74
|
+
latency_count = int(hist.get("count", 0))
|
|
75
|
+
|
|
76
|
+
lines.append(
|
|
77
|
+
"# HELP browser_lease_latency_seconds Histogram of recipe run latency on browser leases."
|
|
78
|
+
)
|
|
79
|
+
lines.append("# TYPE browser_lease_latency_seconds histogram")
|
|
80
|
+
for bound, count in zip(bounds, counts, strict=False):
|
|
81
|
+
lines.append(f'browser_lease_latency_seconds_bucket{{le="{bound}"}} {count}')
|
|
82
|
+
inf_count = counts[-1] if counts else latency_count
|
|
83
|
+
lines.append(f'browser_lease_latency_seconds_bucket{{le="+Inf"}} {inf_count}')
|
|
84
|
+
lines.append(f"browser_lease_latency_seconds_sum {latency_sum:.6f}")
|
|
85
|
+
lines.append(f"browser_lease_latency_seconds_count {latency_count}")
|
|
86
|
+
|
|
87
|
+
return "\n".join(lines) + "\n"
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Run the mock site by hand: `python -m api_everything.mock_site`.
|
|
2
|
+
|
|
3
|
+
It listens on 127.0.0.1:8799, or on the port in the MOCK_SITE_PORT environment variable.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
import uvicorn
|
|
9
|
+
|
|
10
|
+
from api_everything.mock_site import create_app
|
|
11
|
+
|
|
12
|
+
if __name__ == "__main__":
|
|
13
|
+
uvicorn.run(
|
|
14
|
+
create_app(),
|
|
15
|
+
host="127.0.0.1",
|
|
16
|
+
port=int(os.environ.get("MOCK_SITE_PORT", "8799")),
|
|
17
|
+
log_level="warning",
|
|
18
|
+
)
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""A tiny demo site whose JSON endpoints reject replayed requests.
|
|
2
|
+
|
|
3
|
+
This exists to prove the project's core claim locally, with no third-party site:
|
|
4
|
+
|
|
5
|
+
* Every page load mints a fresh, single-use token and embeds it in the page.
|
|
6
|
+
* The page's own JavaScript sends that token with its API call.
|
|
7
|
+
* The API accepts a token once. Replaying the same request later (as a HAR-replay tool
|
|
8
|
+
would) is rejected with 403, but a real browser loading the page gets a new token, so
|
|
9
|
+
capturing what the page receives works every time.
|
|
10
|
+
* Each successful API answer carries a fresh token in `X-Next-Token`, which the interactive
|
|
11
|
+
page uses for its next call, like a real single-page app that rotates tokens.
|
|
12
|
+
|
|
13
|
+
The same endpoints also feed the benchmark. They are not meant to model any real site.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import secrets
|
|
19
|
+
import threading
|
|
20
|
+
|
|
21
|
+
from fastapi import FastAPI, Request
|
|
22
|
+
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
|
23
|
+
|
|
24
|
+
ITEMS = [{"id": i, "title": f"Item {i}"} for i in range(1, 6)]
|
|
25
|
+
TOKEN_HEADER = "X-Mock-Token"
|
|
26
|
+
NEXT_TOKEN_HEADER = "X-Next-Token"
|
|
27
|
+
|
|
28
|
+
# The page calls whatever API path is in the URL fragment, for example `/page#/api/items?q=x`.
|
|
29
|
+
# A fragment never reaches the server, so the page's own URL does not contain the API path
|
|
30
|
+
# and a recipe's matcher only ever matches the real API call.
|
|
31
|
+
_PAGE = """<!doctype html>
|
|
32
|
+
<meta charset="utf-8">
|
|
33
|
+
<title>Mock site</title>
|
|
34
|
+
<meta name="mock-token" content="__TOKEN__">
|
|
35
|
+
<pre id="out">loading</pre>
|
|
36
|
+
<script>
|
|
37
|
+
const target = location.hash.slice(1) || "/api/items";
|
|
38
|
+
const token = document.querySelector('meta[name="mock-token"]').content;
|
|
39
|
+
fetch(target, { headers: { "X-Mock-Token": token } })
|
|
40
|
+
.then((r) => r.text())
|
|
41
|
+
.then((text) => { document.getElementById("out").textContent = text.slice(0, 200); });
|
|
42
|
+
</script>
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
# A page that does nothing on load. It has a search box, a "more" button and an infinite
|
|
46
|
+
# scroll, so recipes can exercise the type, click and scroll actions. Calls are queued one
|
|
47
|
+
# at a time because each answer hands back the token for the next call.
|
|
48
|
+
# A page that calls ONE api path twice with different answers (like a GraphQL endpoint), so a
|
|
49
|
+
# matcher made from the path alone cannot tell the calls apart.
|
|
50
|
+
_DUAL = """<!doctype html>
|
|
51
|
+
<title>Dual</title>
|
|
52
|
+
<script>
|
|
53
|
+
(async () => {
|
|
54
|
+
await fetch("/api/dual?n=1");
|
|
55
|
+
await fetch("/api/dual?n=2");
|
|
56
|
+
})();
|
|
57
|
+
</script>
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def _calling(*paths: str) -> str:
|
|
61
|
+
"""A page that fetches each path on load, for the repair demos below."""
|
|
62
|
+
calls = "\n".join(f' await fetch("{path}");' for path in paths)
|
|
63
|
+
return f"<!doctype html><title>Site</title><script>(async () => {{\n{calls}\n}})();</script>"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_INTERACTIVE = """<!doctype html>
|
|
67
|
+
<meta charset="utf-8">
|
|
68
|
+
<title>Interactive mock</title>
|
|
69
|
+
<meta name="mock-token" content="__TOKEN__">
|
|
70
|
+
<input id="q"> <button id="search">Search</button> <button id="more">More</button>
|
|
71
|
+
<pre id="out"></pre>
|
|
72
|
+
<div id="feed"></div>
|
|
73
|
+
<div style="height: 2000px"></div>
|
|
74
|
+
<script>
|
|
75
|
+
let token = document.querySelector('meta[name="mock-token"]').content;
|
|
76
|
+
let nextPage = 1;
|
|
77
|
+
let chain = Promise.resolve();
|
|
78
|
+
const enqueue = (fn) => { chain = chain.then(fn, fn); return chain; };
|
|
79
|
+
|
|
80
|
+
async function call(url) {
|
|
81
|
+
const r = await fetch(url, { headers: { "X-Mock-Token": token } });
|
|
82
|
+
const next = r.headers.get("X-Next-Token");
|
|
83
|
+
if (next) token = next;
|
|
84
|
+
return r.json();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
document.getElementById("search").onclick = () => enqueue(async () => {
|
|
88
|
+
const q = document.getElementById("q").value;
|
|
89
|
+
const data = await call("/api/items?q=" + encodeURIComponent(q));
|
|
90
|
+
document.getElementById("out").textContent = JSON.stringify(data);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const more = () => enqueue(async () => {
|
|
94
|
+
if (nextPage > 3) return;
|
|
95
|
+
const data = await call("/api/feed?page=" + nextPage++);
|
|
96
|
+
const block = document.createElement("div");
|
|
97
|
+
block.style.height = "1500px";
|
|
98
|
+
block.textContent = "page " + data.page;
|
|
99
|
+
document.getElementById("feed").appendChild(block);
|
|
100
|
+
});
|
|
101
|
+
document.getElementById("more").onclick = more;
|
|
102
|
+
window.addEventListener("scroll", () => {
|
|
103
|
+
if (window.innerHeight + window.scrollY >= document.body.scrollHeight - 5) more();
|
|
104
|
+
});
|
|
105
|
+
</script>
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def create_app() -> FastAPI:
|
|
110
|
+
app = FastAPI(title="Api-everything mock site")
|
|
111
|
+
live_tokens: set[str] = set()
|
|
112
|
+
lock = threading.Lock()
|
|
113
|
+
|
|
114
|
+
def mint_token() -> str:
|
|
115
|
+
token = secrets.token_urlsafe(16)
|
|
116
|
+
with lock:
|
|
117
|
+
live_tokens.add(token)
|
|
118
|
+
return token
|
|
119
|
+
|
|
120
|
+
def spend_token(token: str | None) -> bool:
|
|
121
|
+
"""Accept a token exactly once."""
|
|
122
|
+
if not token:
|
|
123
|
+
return False
|
|
124
|
+
with lock:
|
|
125
|
+
if token in live_tokens:
|
|
126
|
+
live_tokens.remove(token)
|
|
127
|
+
return True
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
def rejected() -> JSONResponse:
|
|
131
|
+
return JSONResponse({"error": "token_missing_or_used"}, status_code=403)
|
|
132
|
+
|
|
133
|
+
def answer(content, status_code: int = 200) -> JSONResponse:
|
|
134
|
+
"""A JSON answer that also hands back the next token."""
|
|
135
|
+
return JSONResponse(
|
|
136
|
+
content, status_code=status_code, headers={NEXT_TOKEN_HEADER: mint_token()}
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
@app.get("/healthz")
|
|
140
|
+
async def healthz() -> dict[str, str]:
|
|
141
|
+
return {"status": "ok"}
|
|
142
|
+
|
|
143
|
+
@app.get("/page", response_class=HTMLResponse)
|
|
144
|
+
async def page() -> HTMLResponse:
|
|
145
|
+
return HTMLResponse(_PAGE.replace("__TOKEN__", mint_token()))
|
|
146
|
+
|
|
147
|
+
@app.get("/page-interactive", response_class=HTMLResponse)
|
|
148
|
+
async def page_interactive() -> HTMLResponse:
|
|
149
|
+
return HTMLResponse(_INTERACTIVE.replace("__TOKEN__", mint_token()))
|
|
150
|
+
|
|
151
|
+
@app.get("/page-dual", response_class=HTMLResponse)
|
|
152
|
+
async def page_dual() -> HTMLResponse:
|
|
153
|
+
return HTMLResponse(_DUAL)
|
|
154
|
+
|
|
155
|
+
@app.get("/api/dual")
|
|
156
|
+
async def api_dual(n: int = 1) -> dict:
|
|
157
|
+
"""Two different shapes behind one path: n=1 and n=2."""
|
|
158
|
+
if n == 1:
|
|
159
|
+
return {"data": {"first": {"id": 1}}, "extensions": {}}
|
|
160
|
+
return {"data": {"second": [{"id": 2}]}, "extensions": {}}
|
|
161
|
+
|
|
162
|
+
# --- a site that changes, for the repair tests ------------------------------------------
|
|
163
|
+
|
|
164
|
+
@app.get("/page-moved", response_class=HTMLResponse)
|
|
165
|
+
async def page_moved() -> HTMLResponse:
|
|
166
|
+
"""The same data as `/api/items`, now served from `/api/v2/items`."""
|
|
167
|
+
return HTMLResponse(_calling("/api/v2/items"))
|
|
168
|
+
|
|
169
|
+
@app.get("/api/v2/items")
|
|
170
|
+
async def api_v2_items() -> dict:
|
|
171
|
+
return {"items": ITEMS}
|
|
172
|
+
|
|
173
|
+
@app.get("/page-shaped", response_class=HTMLResponse)
|
|
174
|
+
async def page_shaped(v: int = 1) -> HTMLResponse:
|
|
175
|
+
"""One path reshaped when `v` is 2: `items[].title` becomes `results[].name`."""
|
|
176
|
+
return HTMLResponse(_calling(f"/api/shaped/items?v={v}"))
|
|
177
|
+
|
|
178
|
+
@app.get("/api/shaped/items")
|
|
179
|
+
async def api_shaped_items(v: int = 1) -> dict:
|
|
180
|
+
if v == 1:
|
|
181
|
+
return {"items": ITEMS}
|
|
182
|
+
results = [{"id": i["id"], "name": i["title"]} for i in ITEMS]
|
|
183
|
+
return {"results": results, "total": len(ITEMS)}
|
|
184
|
+
|
|
185
|
+
@app.get("/page-blocked", response_class=HTMLResponse)
|
|
186
|
+
async def page_blocked() -> HTMLResponse:
|
|
187
|
+
return HTMLResponse(_calling("/api/blocked"))
|
|
188
|
+
|
|
189
|
+
@app.get("/api/blocked")
|
|
190
|
+
async def api_blocked() -> JSONResponse:
|
|
191
|
+
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
192
|
+
|
|
193
|
+
@app.get("/page-two", response_class=HTMLResponse)
|
|
194
|
+
async def page_two() -> HTMLResponse:
|
|
195
|
+
"""Two responses that both look like `{"items": [...]}`: ambiguous for a draft."""
|
|
196
|
+
return HTMLResponse(_calling("/api/two/a", "/api/two/b"))
|
|
197
|
+
|
|
198
|
+
@app.get("/api/two/a")
|
|
199
|
+
async def api_two_a() -> dict:
|
|
200
|
+
return {"items": ITEMS[:2]}
|
|
201
|
+
|
|
202
|
+
@app.get("/api/two/b")
|
|
203
|
+
async def api_two_b() -> dict:
|
|
204
|
+
return {"items": ITEMS}
|
|
205
|
+
|
|
206
|
+
@app.get("/page-empty", response_class=HTMLResponse)
|
|
207
|
+
async def page_empty() -> HTMLResponse:
|
|
208
|
+
"""A page that makes no API call, so nothing ever matches."""
|
|
209
|
+
return HTMLResponse("<!doctype html><title>Empty</title><p>nothing here</p>")
|
|
210
|
+
|
|
211
|
+
@app.get("/page-gated", response_class=HTMLResponse)
|
|
212
|
+
async def page_gated() -> HTMLResponse:
|
|
213
|
+
"""What a logged-out visitor sees: the page sends them to a login page."""
|
|
214
|
+
return HTMLResponse('<!doctype html><script>location.replace("/login")</script>')
|
|
215
|
+
|
|
216
|
+
@app.get("/login", response_class=HTMLResponse)
|
|
217
|
+
async def login() -> HTMLResponse:
|
|
218
|
+
return HTMLResponse("<!doctype html><title>Log in</title><p>please sign in</p>")
|
|
219
|
+
|
|
220
|
+
@app.get("/api/items")
|
|
221
|
+
async def items(request: Request, q: str = ""):
|
|
222
|
+
if not spend_token(request.headers.get(TOKEN_HEADER)):
|
|
223
|
+
return rejected()
|
|
224
|
+
found = [item for item in ITEMS if q.lower() in item["title"].lower()]
|
|
225
|
+
return answer({"items": found})
|
|
226
|
+
|
|
227
|
+
@app.get("/api/feed")
|
|
228
|
+
async def feed(request: Request, page: int = 1):
|
|
229
|
+
"""Page `page` of a feed: five items whose ids encode the page number."""
|
|
230
|
+
if not spend_token(request.headers.get(TOKEN_HEADER)):
|
|
231
|
+
return rejected()
|
|
232
|
+
items = [{"id": page * 10 + i, "title": f"Feed {page}.{i}"} for i in range(1, 6)]
|
|
233
|
+
return answer({"page": page, "items": items})
|
|
234
|
+
|
|
235
|
+
@app.get("/api/text")
|
|
236
|
+
async def text(request: Request):
|
|
237
|
+
"""200 with a body that is not JSON."""
|
|
238
|
+
if not spend_token(request.headers.get(TOKEN_HEADER)):
|
|
239
|
+
return rejected()
|
|
240
|
+
return Response("hello, this is not json", media_type="text/plain")
|
|
241
|
+
|
|
242
|
+
@app.get("/api/nan")
|
|
243
|
+
async def nan(request: Request):
|
|
244
|
+
"""A body some JSON parsers accept (NaN) but the JSON standard does not."""
|
|
245
|
+
if not spend_token(request.headers.get(TOKEN_HEADER)):
|
|
246
|
+
return rejected()
|
|
247
|
+
return Response('{"x": NaN}', media_type="application/json")
|
|
248
|
+
|
|
249
|
+
@app.get("/api/big")
|
|
250
|
+
async def big(request: Request, bytes: int = 1000):
|
|
251
|
+
"""JSON whose body is roughly `bytes` long."""
|
|
252
|
+
if not spend_token(request.headers.get(TOKEN_HEADER)):
|
|
253
|
+
return rejected()
|
|
254
|
+
return answer({"blob": "x" * max(bytes, 0)})
|
|
255
|
+
|
|
256
|
+
@app.get("/api/error")
|
|
257
|
+
async def error(request: Request):
|
|
258
|
+
if not spend_token(request.headers.get(TOKEN_HEADER)):
|
|
259
|
+
return rejected()
|
|
260
|
+
return answer({"error": "boom"}, status_code=500)
|
|
261
|
+
|
|
262
|
+
return app
|