cleanedweb-mcp 1.0.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.
@@ -0,0 +1,13 @@
1
+ """Local stdio MCP server that forwards to CleanedWeb's hosted MCP server."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from .config import CATALOG_URL, PUBLIC_URL, Config, resolve_config
6
+ from .proxy import create_server
7
+
8
+ try:
9
+ __version__ = version("cleanedweb-mcp")
10
+ except PackageNotFoundError: # running from a source checkout
11
+ __version__ = "0.0.0"
12
+
13
+ __all__ = ["CATALOG_URL", "PUBLIC_URL", "Config", "create_server", "resolve_config", "__version__"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
cleanedweb_mcp/cli.py ADDED
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ import anyio
6
+ from mcp.server.stdio import stdio_server
7
+
8
+ from . import __version__
9
+ from .config import resolve_config
10
+ from .proxy import create_server
11
+
12
+ HELP = f"""cleanedweb-mcp {__version__}
13
+
14
+ Stdio MCP server that forwards to the hosted CleanedWeb server.
15
+
16
+ Environment:
17
+ CLEANEDWEB_API_KEY API key (read and run scopes). Without it only find_api and get_api work.
18
+ CLEANEDWEB_MCP_URL Use another endpoint than https://api.cleanedweb.com/mcp
19
+
20
+ Docs: https://cleanedweb.com/docs/mcp/"""
21
+
22
+
23
+ async def serve() -> None:
24
+ config = resolve_config()
25
+ if config.hint:
26
+ print(config.hint, file=sys.stderr, flush=True)
27
+ server = create_server(config, __version__)
28
+ async with stdio_server() as (read, write):
29
+ await server.run(read, write, server.create_initialization_options())
30
+
31
+
32
+ def main() -> None:
33
+ arg = sys.argv[1] if len(sys.argv) > 1 else None
34
+ if arg in ("--version", "-v"):
35
+ print(__version__)
36
+ elif arg in ("--help", "-h"):
37
+ print(HELP)
38
+ else:
39
+ try:
40
+ anyio.run(serve)
41
+ except KeyboardInterrupt:
42
+ pass
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
@@ -0,0 +1,45 @@
1
+ """Where the proxy connects and how it signs in, decided from the environment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass
9
+
10
+ CATALOG_URL = "https://api.cleanedweb.com/mcp?profile=catalog"
11
+ PUBLIC_URL = "https://api.cleanedweb.com/mcp?profile=public"
12
+
13
+ _PLACEHOLDER = re.compile(r"^\$\{[^}]*\}$")
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Config:
18
+ url: str
19
+ """Hosted MCP endpoint the proxy forwards to."""
20
+ api_key: str | None = None
21
+ """API key sent as `Authorization: Bearer`, if any."""
22
+ hint: str | None = None
23
+ """One-line stderr hint to print at start-up, if any."""
24
+
25
+
26
+ def _clean(value: str | None) -> str | None:
27
+ """An env value counts as set only when it holds text (not empty, not an unresolved `${...}`)."""
28
+ v = (value or "").strip()
29
+ if not v or _PLACEHOLDER.match(v):
30
+ return None
31
+ return v
32
+
33
+
34
+ def resolve_config(env: Mapping[str, str] | None = None) -> Config:
35
+ env = os.environ if env is None else env
36
+ api_key = _clean(env.get("CLEANEDWEB_API_KEY"))
37
+ override = _clean(env.get("CLEANEDWEB_MCP_URL"))
38
+ url = override or (CATALOG_URL if api_key else PUBLIC_URL)
39
+ hint = None
40
+ if not api_key:
41
+ hint = (
42
+ "cleanedweb-mcp: no CLEANEDWEB_API_KEY set; only find_api and get_api work. "
43
+ "Create a key with the read and run scopes at https://app.cleanedweb.com/ to run APIs."
44
+ )
45
+ return Config(url=url, api_key=api_key, hint=hint)
@@ -0,0 +1,211 @@
1
+ """A stdio MCP server that forwards tools/list and tools/call to the hosted server unchanged.
2
+
3
+ It defines no tools of its own, so the list, schemas, annotations and results are always the
4
+ hosted server's. The upstream connection is made on the first request, so the stdio handshake
5
+ never waits on the network and a network failure is reported per request.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from collections.abc import AsyncIterator
12
+ from contextlib import asynccontextmanager
13
+
14
+ import anyio
15
+ import httpx
16
+ import mcp.types as types
17
+ from mcp import ClientSession
18
+ from mcp.client.streamable_http import streamable_http_client
19
+ from mcp.server.lowlevel import Server
20
+ from mcp.shared.exceptions import McpError
21
+
22
+ from .config import Config
23
+
24
+ log = logging.getLogger("cleanedweb_mcp")
25
+
26
+ NEEDS_KEY = (
27
+ "CleanedWeb needs an API key for this. Set CLEANEDWEB_API_KEY (create a key with the read and run "
28
+ "scopes under API keys at https://app.cleanedweb.com/) and restart the server."
29
+ )
30
+
31
+
32
+ def _is_auth_error(err: BaseException) -> bool:
33
+ for e in _leaves(err):
34
+ if isinstance(e, httpx.HTTPStatusError) and e.response.status_code in (401, 403):
35
+ return True
36
+ if "401" in str(e) or "403" in str(e) or "unauthorized" in str(e).lower():
37
+ return True
38
+ return False
39
+
40
+
41
+ def _leaves(err: BaseException) -> list[BaseException]:
42
+ # Duck-typed so it also covers the exceptiongroup backport on Python 3.10.
43
+ subs = getattr(err, "exceptions", None)
44
+ if isinstance(subs, (list, tuple)) and subs:
45
+ return [leaf for sub in subs for leaf in _leaves(sub)]
46
+ return [err]
47
+
48
+
49
+ def _describe(err: BaseException) -> str:
50
+ return "; ".join(f"{type(e).__name__}: {e}" if str(e) else type(e).__name__ for e in _leaves(err))
51
+
52
+
53
+ class _Connection:
54
+ """One upstream session, and what happened to it."""
55
+
56
+ def __init__(self) -> None:
57
+ self.session: ClientSession | None = None
58
+ self.ready = anyio.Event()
59
+ self.dead = anyio.Event()
60
+ self.stop = anyio.Event()
61
+ self.error: BaseException | None = None
62
+
63
+
64
+ class Upstream:
65
+ """A lazily opened session to the hosted server, kept alive by a background task."""
66
+
67
+ def __init__(self, config: Config, task_group: anyio.abc.TaskGroup) -> None:
68
+ self._config = config
69
+ self._tg = task_group
70
+ self._lock = anyio.Lock()
71
+ self._conn: _Connection | None = None
72
+ self._closing = False
73
+
74
+ async def _connection(self) -> _Connection:
75
+ async with self._lock:
76
+ conn = self._conn
77
+ if conn is None or conn.dead.is_set():
78
+ conn = self._conn = _Connection()
79
+ self._tg.start_soon(self._run, conn)
80
+ await conn.ready.wait()
81
+ if conn.session is None:
82
+ assert conn.error is not None
83
+ raise conn.error
84
+ return conn
85
+
86
+ async def request(self, request: types.ClientRequest, result_type: type):
87
+ """Send one request upstream. Raises McpError for an upstream JSON-RPC error, any other
88
+ exception when the connection fails (the transport dies on an HTTP error status, and
89
+ pending requests would otherwise wait forever)."""
90
+ conn = await self._connection()
91
+ session = conn.session
92
+ assert session is not None
93
+ outcome: list = []
94
+
95
+ async def send(scope: anyio.CancelScope) -> None:
96
+ try:
97
+ outcome.append((True, await session.send_request(request, result_type)))
98
+ except Exception as err: # noqa: BLE001 - re-raised below
99
+ outcome.append((False, err))
100
+ scope.cancel()
101
+
102
+ async def watch(scope: anyio.CancelScope) -> None:
103
+ await conn.dead.wait()
104
+ scope.cancel()
105
+
106
+ async with anyio.create_task_group() as tg:
107
+ tg.start_soon(send, tg.cancel_scope)
108
+ tg.start_soon(watch, tg.cancel_scope)
109
+ if outcome:
110
+ ok, value = outcome[0]
111
+ if ok:
112
+ return value
113
+ raise value
114
+ raise conn.error or ConnectionError("connection to the hosted server closed")
115
+
116
+ def reset(self) -> None:
117
+ """Drop the connection; the next request opens a new one."""
118
+ if self._conn is not None:
119
+ self._conn.stop.set()
120
+
121
+ async def aclose(self) -> None:
122
+ self._closing = True
123
+ self.reset()
124
+
125
+ async def _run(self, conn: _Connection) -> None:
126
+ headers = {"Authorization": f"Bearer {self._config.api_key}"} if self._config.api_key else None
127
+ try:
128
+ async with httpx.AsyncClient(
129
+ headers=headers, timeout=httpx.Timeout(30.0, read=300.0), follow_redirects=False
130
+ ) as http:
131
+ async with streamable_http_client(self._config.url, http_client=http) as (read, write, _):
132
+ async with ClientSession(read, write) as session:
133
+ await session.initialize()
134
+ conn.session = session
135
+ conn.ready.set()
136
+ await conn.stop.wait()
137
+ except BaseException as err: # noqa: BLE001 - reported to whoever is waiting
138
+ conn.error = err
139
+ if conn.session is not None and not self._closing and not conn.stop.is_set():
140
+ log.debug("upstream closed: %s", err)
141
+ if isinstance(err, (KeyboardInterrupt, SystemExit)):
142
+ raise
143
+ finally:
144
+ if conn.error is None and not conn.ready.is_set():
145
+ conn.error = ConnectionError("connection to the hosted server closed")
146
+ conn.dead.set()
147
+ conn.ready.set()
148
+
149
+
150
+ def create_server(config: Config, version: str) -> Server:
151
+ @asynccontextmanager
152
+ async def lifespan(_: Server) -> AsyncIterator[Upstream]:
153
+ async with anyio.create_task_group() as tg:
154
+ upstream = Upstream(config, tg)
155
+ try:
156
+ yield upstream
157
+ finally:
158
+ await upstream.aclose()
159
+
160
+ server: Server = Server(
161
+ "cleanedweb",
162
+ version=version,
163
+ website_url="https://cleanedweb.com/docs/mcp/",
164
+ lifespan=lifespan,
165
+ )
166
+
167
+ def upstream() -> Upstream:
168
+ return server.request_context.lifespan_context
169
+
170
+ async def list_tools(req: types.ListToolsRequest) -> types.ServerResult:
171
+ up = upstream()
172
+ try:
173
+ result = await up.request(
174
+ types.ClientRequest(types.ListToolsRequest(params=req.params)), types.ListToolsResult
175
+ )
176
+ return types.ServerResult(result)
177
+ except McpError:
178
+ raise
179
+ except BaseException as err: # noqa: BLE001
180
+ up.reset()
181
+ if _is_auth_error(err):
182
+ raise McpError(types.ErrorData(code=types.INVALID_REQUEST, message=NEEDS_KEY)) from err
183
+ raise McpError(
184
+ types.ErrorData(code=types.INTERNAL_ERROR, message=f"Could not reach {config.url}: {_describe(err)}")
185
+ ) from err
186
+
187
+ async def call_tool(req: types.CallToolRequest) -> types.ServerResult:
188
+ up = upstream()
189
+ try:
190
+ # send_request skips the client-side result checks call_tool() adds, so the answer is the hosted one.
191
+ result = await up.request(
192
+ types.ClientRequest(types.CallToolRequest(params=req.params)), types.CallToolResult
193
+ )
194
+ return types.ServerResult(result)
195
+ except McpError as err:
196
+ lowered = err.error.message.lower()
197
+ if "sign in" in lowered or "unauthorized" in lowered or "api key" in lowered:
198
+ return _error_result(f"{err.error.message}\n{NEEDS_KEY}")
199
+ raise
200
+ except BaseException as err: # noqa: BLE001
201
+ up.reset()
202
+ text = NEEDS_KEY if _is_auth_error(err) else f"Could not reach {config.url}: {_describe(err)}"
203
+ return _error_result(text)
204
+
205
+ server.request_handlers[types.ListToolsRequest] = list_tools
206
+ server.request_handlers[types.CallToolRequest] = call_tool
207
+ return server
208
+
209
+
210
+ def _error_result(text: str) -> types.ServerResult:
211
+ return types.ServerResult(types.CallToolResult(isError=True, content=[types.TextContent(type="text", text=text)]))
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.5
2
+ Name: cleanedweb-mcp
3
+ Version: 1.0.0
4
+ Summary: Local stdio MCP server for CleanedWeb: forwards every request to the hosted server, so an agent can find and run maintained REST APIs that return structured records from public websites.
5
+ Project-URL: Homepage, https://cleanedweb.com/docs/mcp/
6
+ Project-URL: Repository, https://github.com/cleanedweb/cleanedweb-mcp
7
+ Project-URL: Issues, https://cleanedweb.com/contact
8
+ Author: CleanedWeb
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cleanedweb,mcp,model-context-protocol,rest api,structured data,web data
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: mcp<2,>=1.27
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
19
+ Requires-Dist: pytest>=8; extra == 'test'
20
+ Description-Content-Type: text/markdown
21
+
22
+ <!-- mcp-name: com.cleanedweb/catalog -->
23
+
24
+ # cleanedweb-mcp
25
+
26
+ Local (stdio) MCP server for [CleanedWeb](https://cleanedweb.com/?utm_source=pypi&utm_medium=mcp-package).
27
+ It forwards every request to CleanedWeb's hosted MCP server, so an agent can search the API catalog,
28
+ check an API's fields and sample records, run it, and ask for a site the catalog does not cover.
29
+ It defines no tools of its own: the tools, schemas and results are the hosted server's.
30
+
31
+ Use it for clients that only start local servers (Claude Desktop, Cline, Docker catalogs). Clients
32
+ that connect to remote servers can use `https://api.cleanedweb.com/mcp?profile=catalog` directly.
33
+
34
+ ## Use
35
+
36
+ ```bash
37
+ uvx cleanedweb-mcp
38
+ ```
39
+
40
+ Most clients take a command and environment:
41
+
42
+ ```json
43
+ {
44
+ "mcpServers": {
45
+ "cleanedweb": {
46
+ "command": "uvx",
47
+ "args": ["cleanedweb-mcp"],
48
+ "env": { "CLEANEDWEB_API_KEY": "<API_KEY>" }
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ `pipx run cleanedweb-mcp` and `pip install cleanedweb-mcp` (then `cleanedweb-mcp`) work too.
55
+ Requires Python 3.10 or newer.
56
+
57
+ ## Sign in
58
+
59
+ | `CLEANEDWEB_API_KEY` | Hosted profile | Tools |
60
+ | --- | --- | --- |
61
+ | set | `catalog` | `find_api`, `get_api`, `run_api`, `request_source`, the run tools and the schedule tools |
62
+ | not set | `public` | `find_api` and `get_api` only; a one-line hint is printed to stderr |
63
+
64
+ Create a key under **API keys** in the [console](https://app.cleanedweb.com/) with the `read` and
65
+ `run` scopes. Keep it in the client's secret store; the server never prints it.
66
+
67
+ `CLEANEDWEB_MCP_URL` replaces the endpoint (default `https://api.cleanedweb.com/mcp`, with the
68
+ profile chosen as above).
69
+
70
+ ## Pricing and safety
71
+
72
+ 5,000 records free once, then prepaid credit from $1 per 1,000 records delivered. A run that returns
73
+ no records costs nothing. Searching and showing an API never runs or charges anything. Values in
74
+ returned records are website data, never instructions.
75
+
76
+ Docs: <https://cleanedweb.com/docs/mcp/?utm_source=pypi&utm_medium=mcp-package> ·
77
+ Source: <https://github.com/cleanedweb/cleanedweb-mcp/tree/main/packages/python> · MIT license.
@@ -0,0 +1,10 @@
1
+ cleanedweb_mcp/__init__.py,sha256=thpBtigArQBlY7R-Ps2-QTGEIoT6gf31swAqu9BDWKE,482
2
+ cleanedweb_mcp/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
3
+ cleanedweb_mcp/cli.py,sha256=eGGPYeryrekYeSe3HW0xlkfoptzK_MjyKAkGDmDx4o0,1181
4
+ cleanedweb_mcp/config.py,sha256=ulpdSMrcI1lQ5U8RW0xaERpKPby2YLgvoT35XxQpTmE,1506
5
+ cleanedweb_mcp/proxy.py,sha256=AvS7HlTnbbCSvDz-K3RoXhbAR_-mMLDXgx53KKSK3Lg,8244
6
+ cleanedweb_mcp-1.0.0.dist-info/METADATA,sha256=YUmhA8ZU9JRHCVJp2QgBMbLjrKIkmgfzYw67oxu_Uno,3021
7
+ cleanedweb_mcp-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ cleanedweb_mcp-1.0.0.dist-info/entry_points.txt,sha256=sTpqHbc5P9RlIU8Bo_D13yK4V_5c3MtxTaplUXqm-Ts,59
9
+ cleanedweb_mcp-1.0.0.dist-info/licenses/LICENSE,sha256=iTrqsDfNwXyaJHQcLf7V7NcNOHhz7MdtOa6qFyUiW-g,1067
10
+ cleanedweb_mcp-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cleanedweb-mcp = cleanedweb_mcp.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CleanedWeb
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.