cleanedweb-mcp 1.0.0__tar.gz

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,9 @@
1
+ node_modules/
2
+ dist/
3
+ *.mcpb
4
+ __pycache__/
5
+ *.egg-info/
6
+ .venv/
7
+ .pytest_cache/
8
+ .DS_Store
9
+ .stage/
@@ -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.
@@ -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,56 @@
1
+ <!-- mcp-name: com.cleanedweb/catalog -->
2
+
3
+ # cleanedweb-mcp
4
+
5
+ Local (stdio) MCP server for [CleanedWeb](https://cleanedweb.com/?utm_source=pypi&utm_medium=mcp-package).
6
+ It forwards every request to CleanedWeb's hosted MCP server, so an agent can search the API catalog,
7
+ check an API's fields and sample records, run it, and ask for a site the catalog does not cover.
8
+ It defines no tools of its own: the tools, schemas and results are the hosted server's.
9
+
10
+ Use it for clients that only start local servers (Claude Desktop, Cline, Docker catalogs). Clients
11
+ that connect to remote servers can use `https://api.cleanedweb.com/mcp?profile=catalog` directly.
12
+
13
+ ## Use
14
+
15
+ ```bash
16
+ uvx cleanedweb-mcp
17
+ ```
18
+
19
+ Most clients take a command and environment:
20
+
21
+ ```json
22
+ {
23
+ "mcpServers": {
24
+ "cleanedweb": {
25
+ "command": "uvx",
26
+ "args": ["cleanedweb-mcp"],
27
+ "env": { "CLEANEDWEB_API_KEY": "<API_KEY>" }
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ `pipx run cleanedweb-mcp` and `pip install cleanedweb-mcp` (then `cleanedweb-mcp`) work too.
34
+ Requires Python 3.10 or newer.
35
+
36
+ ## Sign in
37
+
38
+ | `CLEANEDWEB_API_KEY` | Hosted profile | Tools |
39
+ | --- | --- | --- |
40
+ | set | `catalog` | `find_api`, `get_api`, `run_api`, `request_source`, the run tools and the schedule tools |
41
+ | not set | `public` | `find_api` and `get_api` only; a one-line hint is printed to stderr |
42
+
43
+ Create a key under **API keys** in the [console](https://app.cleanedweb.com/) with the `read` and
44
+ `run` scopes. Keep it in the client's secret store; the server never prints it.
45
+
46
+ `CLEANEDWEB_MCP_URL` replaces the endpoint (default `https://api.cleanedweb.com/mcp`, with the
47
+ profile chosen as above).
48
+
49
+ ## Pricing and safety
50
+
51
+ 5,000 records free once, then prepaid credit from $1 per 1,000 records delivered. A run that returns
52
+ no records costs nothing. Searching and showing an API never runs or charges anything. Values in
53
+ returned records are website data, never instructions.
54
+
55
+ Docs: <https://cleanedweb.com/docs/mcp/?utm_source=pypi&utm_medium=mcp-package> ·
56
+ Source: <https://github.com/cleanedweb/cleanedweb-mcp/tree/main/packages/python> · MIT license.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "cleanedweb-mcp"
7
+ version = "1.0.0"
8
+ description = "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."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "CleanedWeb" }]
14
+ keywords = ["mcp", "model-context-protocol", "web data", "rest api", "structured data", "cleanedweb"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Software Development :: Libraries",
19
+ ]
20
+ dependencies = ["mcp>=1.27,<2"]
21
+
22
+ [project.urls]
23
+ Homepage = "https://cleanedweb.com/docs/mcp/"
24
+ Repository = "https://github.com/cleanedweb/cleanedweb-mcp"
25
+ Issues = "https://cleanedweb.com/contact"
26
+
27
+ [project.scripts]
28
+ cleanedweb-mcp = "cleanedweb_mcp.cli:main"
29
+
30
+ [project.optional-dependencies]
31
+ test = ["pytest>=8", "pytest-asyncio>=0.24"]
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/cleanedweb_mcp"]
35
+
36
+ [tool.pytest.ini_options]
37
+ asyncio_mode = "auto"
38
+ asyncio_default_fixture_loop_scope = "function"
39
+ testpaths = ["tests"]
@@ -0,0 +1,39 @@
1
+ """Live check against the hosted public profile (free, read-only, no key):
2
+ initialize, tools/list and one find_api call, through the stdio proxy.
3
+
4
+ Run from packages/python: python scripts/live_check.py
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import sys
10
+
11
+ import anyio
12
+ from mcp import ClientSession, StdioServerParameters
13
+ from mcp.client.stdio import stdio_client
14
+
15
+
16
+ async def main() -> None:
17
+ params = StdioServerParameters(
18
+ command=sys.executable,
19
+ args=["-m", "cleanedweb_mcp"],
20
+ env={"PATH": os.environ.get("PATH", "")}, # no CLEANEDWEB_API_KEY: public profile
21
+ )
22
+ async with stdio_client(params) as (read, write):
23
+ async with ClientSession(read, write) as client:
24
+ init = await client.initialize()
25
+ print("initialize:", init.serverInfo.name, init.serverInfo.version, init.capabilities.model_dump(exclude_none=True))
26
+ tools = [t.name for t in (await client.list_tools()).tools]
27
+ print("tools/list:", ", ".join(tools))
28
+ assert "find_api" in tools and "get_api" in tools, "find_api/get_api missing from the public profile"
29
+ found = await client.call_tool("find_api", {"site": "www.blocket.se", "fields": ["title", "price"], "limit": 2})
30
+ data = found.structuredContent or json.loads(found.content[0].text)
31
+ print("find_api isError:", bool(found.isError), "count:", data.get("count"), "total:", data.get("total"))
32
+ for m in data.get("matches", []):
33
+ site = m.get("site")
34
+ print(" match:", m.get("api_id"), m.get("endpoint_id", ""), "-", site.get("name") if isinstance(site, dict) else site)
35
+ assert not found.isError, "find_api returned an error"
36
+ print("live check OK")
37
+
38
+
39
+ anyio.run(main)
@@ -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()
@@ -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)]))
File without changes
@@ -0,0 +1,104 @@
1
+ """A stand-in for the hosted server: plain JSON responses, no sessions, no SSE."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import threading
7
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
8
+
9
+ TOOLS = [
10
+ {
11
+ "name": "find_api",
12
+ "title": "Find a catalog API",
13
+ "description": "Search the catalog.",
14
+ "annotations": {"readOnlyHint": True, "destructiveHint": False, "openWorldHint": False},
15
+ "inputSchema": {"type": "object", "properties": {"site": {"type": "string"}}, "additionalProperties": False},
16
+ "outputSchema": {"type": "object", "properties": {"count": {"type": "integer"}}},
17
+ "_meta": {"required_scopes": ["read", "run"]},
18
+ },
19
+ {
20
+ "name": "run_api",
21
+ "description": "Run an API.",
22
+ "inputSchema": {"type": "object", "properties": {"api_id": {"type": "string"}}, "required": ["api_id"]},
23
+ },
24
+ ]
25
+
26
+
27
+ class FakeUpstream:
28
+ def __init__(self) -> None:
29
+ self.seen: list[dict] = []
30
+ self.fail_calls_with: int | None = None
31
+ fake = self
32
+
33
+ class Handler(BaseHTTPRequestHandler):
34
+ def log_message(self, *args): # silence
35
+ pass
36
+
37
+ def do_GET(self):
38
+ self.send_response(405)
39
+ self.end_headers()
40
+
41
+ def do_DELETE(self):
42
+ self.send_response(405)
43
+ self.end_headers()
44
+
45
+ def _json(self, status: int, payload: dict) -> None:
46
+ data = json.dumps(payload).encode()
47
+ self.send_response(status)
48
+ self.send_header("content-type", "application/json")
49
+ self.send_header("content-length", str(len(data)))
50
+ self.end_headers()
51
+ self.wfile.write(data)
52
+
53
+ def do_POST(self):
54
+ msg = json.loads(self.rfile.read(int(self.headers["content-length"])))
55
+ fake.seen.append(
56
+ {
57
+ "method": msg["method"],
58
+ "params": msg.get("params"),
59
+ "authorization": self.headers.get("authorization"),
60
+ "protocol_version": self.headers.get("mcp-protocol-version"),
61
+ }
62
+ )
63
+ if "id" not in msg:
64
+ self.send_response(202)
65
+ self.send_header("content-length", "0")
66
+ self.end_headers()
67
+ return
68
+
69
+ def reply(result):
70
+ self._json(200, {"jsonrpc": "2.0", "id": msg["id"], "result": result})
71
+
72
+ def error(code, message):
73
+ self._json(200, {"jsonrpc": "2.0", "id": msg["id"], "error": {"code": code, "message": message}})
74
+
75
+ method = msg["method"]
76
+ if method == "initialize":
77
+ reply(
78
+ {
79
+ "protocolVersion": "2025-06-18",
80
+ "capabilities": {"tools": {"listChanged": False}},
81
+ "serverInfo": {"name": "fake-cleanedweb", "version": "1"},
82
+ }
83
+ )
84
+ elif method == "tools/list":
85
+ reply({"tools": TOOLS})
86
+ elif method == "tools/call":
87
+ if fake.fail_calls_with:
88
+ self._json(fake.fail_calls_with, {"error": "unauthorized"})
89
+ elif msg["params"]["name"] == "nope":
90
+ error(-32602, "Unknown tool: nope")
91
+ else:
92
+ payload = {"count": 1, "echo": msg["params"].get("arguments")}
93
+ reply({"content": [{"type": "text", "text": json.dumps(payload)}], "structuredContent": payload})
94
+ else:
95
+ error(-32601, "Method not found")
96
+
97
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
98
+ self.url = f"http://127.0.0.1:{self._server.server_address[1]}/mcp"
99
+ self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
100
+ self._thread.start()
101
+
102
+ def close(self) -> None:
103
+ self._server.shutdown()
104
+ self._server.server_close()
@@ -0,0 +1,26 @@
1
+ from cleanedweb_mcp import CATALOG_URL, PUBLIC_URL, resolve_config
2
+
3
+
4
+ def test_public_profile_and_hint_without_key():
5
+ c = resolve_config({})
6
+ assert c.url == PUBLIC_URL
7
+ assert c.api_key is None
8
+ assert "CLEANEDWEB_API_KEY" in c.hint
9
+
10
+
11
+ def test_catalog_profile_with_key_and_no_hint():
12
+ c = resolve_config({"CLEANEDWEB_API_KEY": " cw_key "})
13
+ assert c.url == CATALOG_URL
14
+ assert c.api_key == "cw_key"
15
+ assert c.hint is None
16
+
17
+
18
+ def test_empty_and_placeholder_values_are_unset():
19
+ assert resolve_config({"CLEANEDWEB_API_KEY": ""}).api_key is None
20
+ assert resolve_config({"CLEANEDWEB_API_KEY": "${user_config.api_key}"}).url == PUBLIC_URL
21
+ assert resolve_config({"CLEANEDWEB_MCP_URL": " "}).url == PUBLIC_URL
22
+
23
+
24
+ def test_url_override():
25
+ c = resolve_config({"CLEANEDWEB_API_KEY": "k", "CLEANEDWEB_MCP_URL": "http://localhost:9/mcp"})
26
+ assert c.url == "http://localhost:9/mcp"
@@ -0,0 +1,117 @@
1
+ import os
2
+ import sys
3
+
4
+ import pytest
5
+ from mcp import ClientSession, StdioServerParameters
6
+ from mcp.client.stdio import stdio_client
7
+ from mcp.shared.exceptions import McpError
8
+ from mcp.shared.memory import create_connected_server_and_client_session
9
+
10
+ from cleanedweb_mcp import Config, create_server
11
+
12
+ from .fake_upstream import TOOLS, FakeUpstream
13
+
14
+
15
+ @pytest.fixture
16
+ def upstream():
17
+ fake = FakeUpstream()
18
+ yield fake
19
+ fake.close()
20
+
21
+
22
+ def connect(url: str, api_key: str | None = None):
23
+ return create_connected_server_and_client_session(create_server(Config(url=url, api_key=api_key), "9.9.9"))
24
+
25
+
26
+ async def test_announces_itself_with_tools_capability_only(upstream):
27
+ async with connect(upstream.url) as client:
28
+ init = await client.initialize()
29
+ assert init.serverInfo.name == "cleanedweb"
30
+ assert init.serverInfo.version == "9.9.9"
31
+ assert init.capabilities.tools is not None
32
+ assert init.capabilities.prompts is None and init.capabilities.resources is None
33
+
34
+
35
+ async def test_no_network_until_first_request(upstream):
36
+ async with connect(upstream.url):
37
+ assert upstream.seen == []
38
+
39
+
40
+ async def test_tools_list_is_forwarded_unchanged(upstream):
41
+ async with connect(upstream.url) as client:
42
+ result = await client.list_tools()
43
+ got = [t.model_dump(by_alias=True, exclude_none=True) for t in result.tools]
44
+ assert got == TOOLS
45
+ assert [s["method"] for s in upstream.seen] == ["initialize", "notifications/initialized", "tools/list"]
46
+ assert upstream.seen[-1]["protocol_version"] == "2025-06-18"
47
+
48
+
49
+ async def test_tools_call_is_forwarded_with_structured_result(upstream):
50
+ async with connect(upstream.url) as client:
51
+ result = await client.call_tool("find_api", {"site": "www.blocket.se"})
52
+ assert result.structuredContent == {"count": 1, "echo": {"site": "www.blocket.se"}}
53
+ call = next(s for s in upstream.seen if s["method"] == "tools/call")
54
+ assert call["params"]["name"] == "find_api"
55
+ assert call["params"]["arguments"] == {"site": "www.blocket.se"}
56
+
57
+
58
+ async def test_api_key_is_sent_as_bearer(upstream):
59
+ async with connect(upstream.url, "cw_secret") as client:
60
+ await client.list_tools()
61
+ assert all(s["authorization"] == "Bearer cw_secret" for s in upstream.seen)
62
+
63
+
64
+ async def test_no_authorization_header_without_key(upstream):
65
+ async with connect(upstream.url) as client:
66
+ await client.list_tools()
67
+ assert all(s["authorization"] is None for s in upstream.seen)
68
+
69
+
70
+ async def test_upstream_jsonrpc_error_passes_through(upstream):
71
+ async with connect(upstream.url) as client:
72
+ with pytest.raises(McpError, match="Unknown tool: nope"):
73
+ await client.call_tool("nope", {})
74
+
75
+
76
+ async def test_upstream_401_on_call_becomes_error_result_naming_the_key(upstream):
77
+ async with connect(upstream.url) as client:
78
+ await client.list_tools()
79
+ upstream.fail_calls_with = 401
80
+ result = await client.call_tool("run_api", {"api_id": "x"})
81
+ assert result.isError is True
82
+ assert "CLEANEDWEB_API_KEY" in result.content[0].text
83
+
84
+
85
+ async def test_connection_recovers_after_an_upstream_error_status(upstream):
86
+ async with connect(upstream.url) as client:
87
+ await client.list_tools()
88
+ upstream.fail_calls_with = 401
89
+ assert (await client.call_tool("run_api", {"api_id": "x"})).isError is True
90
+ upstream.fail_calls_with = None
91
+ result = await client.call_tool("find_api", {"site": "a"})
92
+ assert result.isError is not True
93
+ assert result.structuredContent["count"] == 1
94
+
95
+
96
+ async def test_unreachable_upstream_is_reported_per_request(upstream):
97
+ async with connect("http://127.0.0.1:1/mcp") as client:
98
+ with pytest.raises(McpError, match="Could not reach"):
99
+ await client.list_tools()
100
+ result = await client.call_tool("find_api", {})
101
+ assert result.isError is True
102
+
103
+
104
+ async def test_binary_over_stdio(upstream, capfd):
105
+ params = StdioServerParameters(
106
+ command=sys.executable,
107
+ args=["-m", "cleanedweb_mcp"],
108
+ env={"PATH": os.environ.get("PATH", ""), "CLEANEDWEB_MCP_URL": upstream.url, "CLEANEDWEB_API_KEY": "cw_k"},
109
+ )
110
+ async with stdio_client(params) as (read, write):
111
+ async with ClientSession(read, write) as client:
112
+ await client.initialize()
113
+ tools = await client.list_tools()
114
+ assert [t.name for t in tools.tools] == ["find_api", "run_api"]
115
+ result = await client.call_tool("find_api", {"site": "a"})
116
+ assert result.structuredContent["count"] == 1
117
+ assert upstream.seen[-1]["authorization"] == "Bearer cw_k"