arcade-specstream 0.1.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,68 @@
1
+ # Python
2
+ .venv/
3
+ __pycache__/
4
+ *.py[cod]
5
+ .pytest_cache/
6
+ .mypy_cache/
7
+ .ruff_cache/
8
+ .coverage
9
+ coverage/
10
+
11
+ # Node/frontend
12
+ node_modules/
13
+ build/
14
+ dist/
15
+ playwright-report/
16
+ test-results/
17
+ .react-router/
18
+
19
+ # Runtime/output
20
+ site-*/
21
+ *.log
22
+ *.dump
23
+ /exports/*
24
+ /growth/email/out/
25
+ screenshots/
26
+
27
+ # Secrets
28
+ .env
29
+ .env.*
30
+ !.env.example
31
+ *.pem
32
+ *.key
33
+
34
+ # Editors/OS
35
+ .DS_Store
36
+ .idea/
37
+ .vscode/
38
+
39
+ # Isolated engine verification state
40
+ .engine-local/
41
+
42
+ # Isolated product-hardening verification state
43
+ .hardening-local/
44
+
45
+ # Isolated product-maturation verification state (short Unix socket paths)
46
+ /.maturation-local/
47
+ /.t/
48
+
49
+ .runtime/
50
+ /design/brand/street-world/specstream-street-world.zip
51
+
52
+ /artifacts/launch-validation/
53
+
54
+ /artifacts/launch-package/
55
+
56
+ # Website build output read by the pages (page dates from git)
57
+ apps/website/src/data/lastmod.generated.json
58
+ plugins/openai/ui/harness/harness.js
59
+ apps/workspace/dist-chatgpt/
60
+ marketing/native/*/
61
+ marketing/native/START-HERE.html
62
+
63
+ # the crew board and its runs (ops/crew.py): a database and job scripts, not source
64
+ /var/crew/
65
+
66
+ # Work trees of parallel helpers: full copies of the repo. Searches and git must not walk them
67
+ # (Nov 12: 50 copies inside the repo kept the /home disk at 100% busy).
68
+ .claude/worktrees
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SpecStream SAS
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,87 @@
1
+ Metadata-Version: 2.5
2
+ Name: arcade-specstream
3
+ Version: 0.1.0
4
+ Summary: SpecStream for Arcade: Deep Search lists from the live web with the source page of every row, plus the Search API and the Extract API.
5
+ Project-URL: Homepage, https://specstream.ai
6
+ Project-URL: Documentation, https://specstream.ai/docs
7
+ Project-URL: Repository, https://github.com/specstream/specstream-tools/tree/main/packages/arcade-specstream
8
+ Project-URL: Issues, https://github.com/specstream/specstream-tools/issues
9
+ Project-URL: Pricing, https://specstream.ai/pricing
10
+ Author-email: SpecStream <support@specstream.ai>
11
+ Maintainer-email: SpecStream <support@specstream.ai>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: agents,arcade,arcade-ai,arcade-mcp,company-list,deep-search,extract,lead-lists,live-web,mcp,specstream,toolkit,tools,web-data,web-search
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Internet :: WWW/HTTP
25
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: <3.14,>=3.10
28
+ Requires-Dist: arcade-mcp-server<2.0.0,>=1.17.0
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest>=8; extra == 'test'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # arcade-specstream
34
+
35
+ SpecStream tools for [Arcade](https://www.arcade.dev). [SpecStream](https://specstream.ai) is the live web data engine for teams and agents: ask for any dataset in plain words and get every match on the live web, in structured rows, with the source page and read time of every value.
36
+
37
+ ```bash
38
+ pip install arcade-specstream
39
+ ```
40
+
41
+ A free account comes with $10 of credit and needs no card: [specstream.ai](https://specstream.ai/signup). Create an API key under Agents & API in your SpecStream workspace.
42
+
43
+ ## Tools
44
+
45
+ | Tool | What it does | Price |
46
+ | --- | --- | --- |
47
+ | `FindList` | Deep Search: a list of real things that meet conditions, from a plain-English request, with the page each row was read from | per delivered row, within the ceiling you set |
48
+ | `GetListResults` | Every row found so far for a list | free |
49
+ | `WebSearch` | Search the live web in seconds (Search API). `speed` set to `fast` returns the ranked results in about a second | $5 per 1,000 searches of up to 10 results; a fast search costs $1 per 1,000 |
50
+ | `ExtractPages` | Main text, title and date of 1 to 20 URLs, PDF, Word or Excel (Extract API) | $0.80 per 1,000 pages; empty pages free |
51
+
52
+ ## Secrets
53
+
54
+ | Secret | Used by | Value |
55
+ | --- | --- | --- |
56
+ | `SPECSTREAM_API_KEY` | every tool | your SpecStream API key |
57
+ | `SPECSTREAM_MAX_PRICE_USD` | `FindList` | the most one list may cost, in US dollars, for example `5` |
58
+
59
+ The model writes the request and picks how many rows. It can't raise the price ceiling: a list whose price is above it doesn't run, and the tool answers `over_maximum` with the price. Rows that couldn't be confirmed are left out and aren't charged. The same request within the hour returns the same list, so a retried step never buys it twice.
60
+
61
+ ## Run it
62
+
63
+ Locally, as an MCP server over stdio (secrets come from the environment):
64
+
65
+ ```bash
66
+ export SPECSTREAM_API_KEY=ss_live_...
67
+ export SPECSTREAM_MAX_PRICE_USD=5
68
+ arcade-specstream # stdio
69
+ arcade-specstream http 127.0.0.1 8000
70
+ ```
71
+
72
+ Or add the tools to your own Arcade server:
73
+
74
+ ```python
75
+ from arcade_mcp_server import MCPApp
76
+ import arcade_specstream
77
+
78
+ app = MCPApp(name="SpecStream")
79
+ app.add_tools_from_module(arcade_specstream)
80
+ app.run()
81
+ ```
82
+
83
+ ## What `FindList` returns
84
+
85
+ `status`, `list_id`, `list_link` (the list in your workspace), `row_count` and `rows`. Each row holds the list's own columns, the page of each value (`<field>_source`), `source_url` and `checked_at`. If the list is still running after about seven minutes, call `GetListResults` with its `list_id` for the rest.
86
+
87
+ MIT licensed. Source: [specstream/specstream-tools](https://github.com/specstream/specstream-tools/tree/main/packages/arcade-specstream).
@@ -0,0 +1,55 @@
1
+ # arcade-specstream
2
+
3
+ SpecStream tools for [Arcade](https://www.arcade.dev). [SpecStream](https://specstream.ai) is the live web data engine for teams and agents: ask for any dataset in plain words and get every match on the live web, in structured rows, with the source page and read time of every value.
4
+
5
+ ```bash
6
+ pip install arcade-specstream
7
+ ```
8
+
9
+ A free account comes with $10 of credit and needs no card: [specstream.ai](https://specstream.ai/signup). Create an API key under Agents & API in your SpecStream workspace.
10
+
11
+ ## Tools
12
+
13
+ | Tool | What it does | Price |
14
+ | --- | --- | --- |
15
+ | `FindList` | Deep Search: a list of real things that meet conditions, from a plain-English request, with the page each row was read from | per delivered row, within the ceiling you set |
16
+ | `GetListResults` | Every row found so far for a list | free |
17
+ | `WebSearch` | Search the live web in seconds (Search API). `speed` set to `fast` returns the ranked results in about a second | $5 per 1,000 searches of up to 10 results; a fast search costs $1 per 1,000 |
18
+ | `ExtractPages` | Main text, title and date of 1 to 20 URLs, PDF, Word or Excel (Extract API) | $0.80 per 1,000 pages; empty pages free |
19
+
20
+ ## Secrets
21
+
22
+ | Secret | Used by | Value |
23
+ | --- | --- | --- |
24
+ | `SPECSTREAM_API_KEY` | every tool | your SpecStream API key |
25
+ | `SPECSTREAM_MAX_PRICE_USD` | `FindList` | the most one list may cost, in US dollars, for example `5` |
26
+
27
+ The model writes the request and picks how many rows. It can't raise the price ceiling: a list whose price is above it doesn't run, and the tool answers `over_maximum` with the price. Rows that couldn't be confirmed are left out and aren't charged. The same request within the hour returns the same list, so a retried step never buys it twice.
28
+
29
+ ## Run it
30
+
31
+ Locally, as an MCP server over stdio (secrets come from the environment):
32
+
33
+ ```bash
34
+ export SPECSTREAM_API_KEY=ss_live_...
35
+ export SPECSTREAM_MAX_PRICE_USD=5
36
+ arcade-specstream # stdio
37
+ arcade-specstream http 127.0.0.1 8000
38
+ ```
39
+
40
+ Or add the tools to your own Arcade server:
41
+
42
+ ```python
43
+ from arcade_mcp_server import MCPApp
44
+ import arcade_specstream
45
+
46
+ app = MCPApp(name="SpecStream")
47
+ app.add_tools_from_module(arcade_specstream)
48
+ app.run()
49
+ ```
50
+
51
+ ## What `FindList` returns
52
+
53
+ `status`, `list_id`, `list_link` (the list in your workspace), `row_count` and `rows`. Each row holds the list's own columns, the page of each value (`<field>_source`), `source_url` and `checked_at`. If the list is still running after about seven minutes, call `GetListResults` with its `list_id` for the rest.
54
+
55
+ MIT licensed. Source: [specstream/specstream-tools](https://github.com/specstream/specstream-tools/tree/main/packages/arcade-specstream).
@@ -0,0 +1,6 @@
1
+ """SpecStream tools for Arcade: Deep Search lists, the Search API and the Extract API."""
2
+
3
+ from arcade_specstream._api import SpecStreamError
4
+ from arcade_specstream.tools import extract_pages, find_list, get_list_results, web_search
5
+
6
+ __all__ = ["SpecStreamError", "extract_pages", "find_list", "get_list_results", "web_search"]
@@ -0,0 +1,31 @@
1
+ """Run the SpecStream tools as an MCP server: `arcade-specstream` (stdio) or `arcade-specstream http 127.0.0.1 8000`."""
2
+
3
+ import sys
4
+ from typing import cast
5
+
6
+ from arcade_mcp_server import MCPApp
7
+ from arcade_mcp_server.mcp_app import TransportType
8
+
9
+ import arcade_specstream
10
+
11
+ app = MCPApp(
12
+ name="SpecStream",
13
+ instructions=(
14
+ "Use this server for data from the live web. For a complete list of things that meet conditions, with the "
15
+ "same facts on each row, call FindList. For one fact or a quick answer, call WebSearch. For the text of "
16
+ "known pages, call ExtractPages."
17
+ ),
18
+ )
19
+
20
+ app.add_tools_from_module(arcade_specstream)
21
+
22
+
23
+ def main() -> None:
24
+ transport = sys.argv[1] if len(sys.argv) > 1 else "stdio"
25
+ host = sys.argv[2] if len(sys.argv) > 2 else "127.0.0.1"
26
+ port = int(sys.argv[3]) if len(sys.argv) > 3 else 8000
27
+ app.run(transport=cast(TransportType, transport), host=host, port=port)
28
+
29
+
30
+ if __name__ == "__main__":
31
+ main()
@@ -0,0 +1,243 @@
1
+ """The SpecStream REST calls the tools share: read a request, price it, start it within a maximum, read its rows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import time
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from dataclasses import dataclass
12
+ from typing import Any, Callable
13
+
14
+ DEFAULT_BASE_URL = "https://api.specstream.ai"
15
+ USER_AGENT = "arcade-specstream/0.1.0"
16
+ # A list runs for up to about five minutes, so the tools wait a little longer than that by default.
17
+ DEFAULT_WAIT_SECONDS = 420.0
18
+ FINISHED = {"completed", "partial"}
19
+ STOPPED = {"failed", "cancelled", "canceled", "expired"}
20
+ # Fields every row carries; a column with the same name is renamed so it can't overwrite them.
21
+ RESERVED = {"list_id", "list_link", "position", "source_url", "checked_at"}
22
+
23
+ Opener = Callable[[urllib.request.Request, float], Any]
24
+
25
+
26
+ class SpecStreamError(RuntimeError):
27
+ """SpecStream refused a call or answered with something this package can't read."""
28
+
29
+
30
+ def _dollars(cents: int) -> str:
31
+ return f"${cents / 100:.2f}"
32
+
33
+
34
+ def list_link(find_id: str) -> str:
35
+ return f"https://specstream.ai/workspace/collections/{urllib.parse.quote(find_id, safe='')}"
36
+
37
+
38
+ def _sources(flat: dict[str, Any]) -> dict[str, Any]:
39
+ """Each value's page in the API's flat row: <field>_source beside the <field> it belongs to."""
40
+ return {key: value for key, value in flat.items() if key.endswith("_source") and key[: -len("_source")] in flat}
41
+
42
+
43
+ def flatten_row(find_id: str, record: dict[str, Any], flat: dict[str, Any] | None = None) -> dict[str, Any]:
44
+ """One row as flat fields: each column's label holds what the list shows. The page of each value
45
+ (<field>_source) and of the fact that put the row in the list (source_url, checked_at) come from
46
+ the API's flat row, so every tool shows the same pages."""
47
+ flat = flat or {}
48
+ sources = _sources(flat)
49
+ row: dict[str, Any] = {"list_id": find_id, "position": record.get("ordinal")}
50
+ for cell in record.get("details") or record.get("cells") or []:
51
+ label = str(cell.get("label") or cell.get("column_id") or "").strip()
52
+ if not label:
53
+ continue
54
+ if label in RESERVED or label in sources:
55
+ label = f"{label} (column)"
56
+ if cell.get("absence"):
57
+ value: Any = ""
58
+ elif cell.get("display") is not None:
59
+ value = cell["display"]
60
+ else:
61
+ value = cell.get("value") if cell.get("value") is not None else ""
62
+ row[label] = value
63
+ row.update(sources)
64
+ row["source_url"] = flat.get("source_url") or ""
65
+ row["checked_at"] = flat.get("checked_at") or ""
66
+ row["list_link"] = list_link(find_id)
67
+ return row
68
+
69
+
70
+ @dataclass
71
+ class SpecStreamAPI:
72
+ api_key: str
73
+ base_url: str = DEFAULT_BASE_URL
74
+ timeout: float = 150.0
75
+ opener: Opener | None = None
76
+ sleep: Callable[[float], None] = time.sleep
77
+ clock: Callable[[], float] = time.monotonic
78
+
79
+ def request(self, method: str, path: str, body: dict[str, Any] | None = None, *, allow_404: bool = False) -> dict[str, Any] | None:
80
+ key = (self.api_key or "").strip()
81
+ if not key:
82
+ raise SpecStreamError("Set SPECSTREAM_API_KEY or pass api_key. Create a key under Agents & API in your SpecStream workspace.")
83
+ request = urllib.request.Request(
84
+ self.base_url.rstrip("/") + path,
85
+ data=None if body is None else json.dumps(body).encode(),
86
+ method=method,
87
+ headers={
88
+ "Authorization": key if key.lower().startswith("bearer ") else f"Bearer {key}",
89
+ "Accept": "application/json",
90
+ "Content-Type": "application/json",
91
+ "User-Agent": USER_AGENT,
92
+ },
93
+ )
94
+ open_ = self.opener or (lambda req, timeout: urllib.request.urlopen(req, timeout=timeout))
95
+ try:
96
+ response = open_(request, self.timeout)
97
+ try:
98
+ raw = response.read()
99
+ finally:
100
+ response.close()
101
+ except urllib.error.HTTPError as error:
102
+ if allow_404 and error.code == 404:
103
+ return None
104
+ raise SpecStreamError(_error_message(error)) from None
105
+ except urllib.error.URLError as error:
106
+ raise SpecStreamError(f"Couldn't reach SpecStream: {error.reason}") from None
107
+ try:
108
+ payload = json.loads(raw or b"{}")
109
+ except ValueError:
110
+ payload = None
111
+ if not isinstance(payload, dict) or not isinstance(payload.get("data"), dict):
112
+ raise SpecStreamError("SpecStream returned a response this package couldn't read.")
113
+ return payload["data"]
114
+
115
+
116
+ def web_search(self, q: str, *, passages: bool = False, speed: str | None = None) -> dict[str, Any]:
117
+ """Search the live web with GET /v1/web-search ($5 per 1,000 searches of up to 10 results, no quote needed).
118
+
119
+ speed="fast" returns the ranked results in about a second, at $1 per 1,000 searches.
120
+ Left out, no speed is sent and the API's default search runs.
121
+ """
122
+ query = (q or "").strip()
123
+ if not query or len(query) > 2000:
124
+ raise ValueError("q must be between 1 and 2,000 characters.")
125
+ speed = (speed or "").strip().lower() or None
126
+ if speed not in (None, "default", "fast"):
127
+ raise ValueError('speed must be "default" or "fast".')
128
+ params: dict[str, str] = {"q": query}
129
+ if passages:
130
+ params["passages"] = "true"
131
+ if speed:
132
+ params["speed"] = speed
133
+ return self.request("GET", f"/v1/web-search?{urllib.parse.urlencode(params)}") or {}
134
+
135
+ def extract_pages(self, urls: list[str], *, format: str = "markdown") -> dict[str, Any]:
136
+ """Extract the main text of 1 to 20 URLs live with POST /v1/extract ($0.80 per 1,000 pages)."""
137
+ cleaned = [str(u or "").strip() for u in (urls or []) if str(u or "").strip()]
138
+ if not 1 <= len(cleaned) <= 20:
139
+ raise ValueError("Provide 1 to 20 http or https URLs.")
140
+ fmt = "text" if format == "text" else "markdown"
141
+ return self.request("POST", "/v1/extract", {"urls": cleaned, "format": fmt}) or {}
142
+ def results(self, find_id: str) -> dict[str, Any]:
143
+ """Every row found so far for a list, following the pages."""
144
+ rows: list[dict[str, Any]] = []
145
+ cursor: str | None = None
146
+ status = "running"
147
+ while True:
148
+ query = {"limit": "100", **({"cursor": cursor} if cursor else {})}
149
+ page = self.request("GET", f"/v1/finds/{urllib.parse.quote(find_id, safe='')}/rows?{urllib.parse.urlencode(query)}") or {}
150
+ status = page.get("status") or status
151
+ flat = {str(item.get("id")): item for item in page.get("flat_rows") or []}
152
+ rows.extend(
153
+ flatten_row(find_id, record, flat.get(f"{find_id}:{record.get('entity_id')}"))
154
+ for record in page.get("rows") or []
155
+ )
156
+ cursor = page.get("next_cursor")
157
+ if not cursor:
158
+ break
159
+ return {"list_id": find_id, "status": status, "list_link": list_link(find_id), "row_count": len(rows), "rows": rows}
160
+
161
+ def find_list(
162
+ self,
163
+ request: str,
164
+ *,
165
+ max_results: int,
166
+ max_price_usd: float,
167
+ wait_seconds: float = DEFAULT_WAIT_SECONDS,
168
+ poll_interval: float = 3.0,
169
+ locale: str = "en-US",
170
+ key_prefix: str = "arcade",
171
+ ) -> dict[str, Any]:
172
+ q = (request or "").strip()
173
+ if not q:
174
+ raise ValueError("Describe the list to find.")
175
+ if not isinstance(max_results, int) or max_results < 1:
176
+ raise ValueError("max_results must be 1 or more.")
177
+ max_cents = round(float(max_price_usd) * 100)
178
+ if max_cents <= 0:
179
+ raise ValueError("max_price_usd must be greater than 0.")
180
+
181
+ # The same request with the same limits gets the run it already started in this hour or the one before,
182
+ # so a retried agent step never buys the list twice, even across the turn of the hour.
183
+ def key_for(at: float) -> str:
184
+ hour = time.strftime("%Y-%m-%dT%H", time.gmtime(at))
185
+ return f"{key_prefix}-" + hashlib.sha256(f"{q}|{max_results}|{max_cents}|{hour}".encode()).hexdigest()[:32]
186
+
187
+ now = time.time()
188
+ request_key = key_for(now)
189
+ existing = None
190
+ for candidate in (request_key, key_for(now - 3600)):
191
+ existing = self.request("GET", f"/v1/capacity/requests/{urllib.parse.quote(candidate, safe='')}", allow_404=True)
192
+ if existing and existing.get("find_id"):
193
+ break
194
+ if existing and existing.get("find_id"):
195
+ find_id = existing["find_id"]
196
+ maximum_cents = int(existing.get("maximum_cents") or max_cents)
197
+ else:
198
+ reading = self.request("POST", "/v1/parse", {"q": q, "locale": locale}) or {}
199
+ if reading.get("status") != "runnable":
200
+ read_as = reading.get("canonical_sentence") or q
201
+ return {
202
+ "status": "needs_edit",
203
+ "request": q,
204
+ "message": f'SpecStream needs a clearer request before it can price it. It read: "{read_as}". Add the place or what every row must meet.',
205
+ }
206
+ quote = self.request(
207
+ "POST", "/v1/capacity/quotes", {"ast_hash": reading["ast_hash"], "operation": "find", "requested_units": max_results}
208
+ ) or {}
209
+ maximum_cents = int(quote.get("maximum_cents") or 0)
210
+ if maximum_cents > max_cents:
211
+ return {
212
+ "status": "over_maximum",
213
+ "request": q,
214
+ "maximum_price_usd": maximum_cents / 100,
215
+ "message": f"Nothing ran: this list can cost up to {_dollars(maximum_cents)}, above the maximum of {_dollars(max_cents)}. Ask for fewer results or raise max_price_usd.",
216
+ }
217
+ run = self.request(
218
+ "POST",
219
+ "/v1/capacity/executions",
220
+ {"quote_id": quote["quote_id"], "quote_hash": quote["quote_hash"], "confirm_max_cents": maximum_cents, "idempotency_key": request_key},
221
+ ) or {}
222
+ find_id = run["find_id"]
223
+
224
+ deadline = self.clock() + max(0.0, wait_seconds)
225
+ while True:
226
+ result = self.results(find_id)
227
+ if result["status"] in FINISHED | STOPPED or self.clock() >= deadline:
228
+ break
229
+ self.sleep(poll_interval)
230
+ result.update({"request": q, "maximum_price_usd": maximum_cents / 100})
231
+ if result["status"] not in FINISHED | STOPPED:
232
+ result["message"] = "Still running. Call the GetListResults tool with this list_id for the rest."
233
+ return result
234
+
235
+
236
+ def _error_message(error: urllib.error.HTTPError) -> str:
237
+ try:
238
+ payload = json.loads(error.read() or b"{}")
239
+ except ValueError:
240
+ payload = {}
241
+ detail = payload.get("error") if isinstance(payload, dict) else None
242
+ message = detail.get("message") if isinstance(detail, dict) else detail if isinstance(detail, str) else None
243
+ return f"SpecStream answered {error.code}: {message or error.reason}"
File without changes
@@ -0,0 +1,146 @@
1
+ """Arcade tools for SpecStream: Deep Search lists, the Search API and the Extract API.
2
+
3
+ Every tool reads the key from the Arcade secret SPECSTREAM_API_KEY. FindList also reads the secret
4
+ SPECSTREAM_MAX_PRICE_USD: the most one list may cost. The developer sets it in Arcade; the model can't raise it.
5
+ """
6
+
7
+ # No `from __future__ import annotations`: Arcade reads the parameter types at runtime to find the Context.
8
+ import asyncio
9
+ from typing import Annotated, Any
10
+
11
+ from arcade_mcp_server import Context, tool
12
+ from arcade_mcp_server.exceptions import RetryableToolError, ToolExecutionError
13
+ from arcade_mcp_server.metadata import Behavior, Classification, Operation, ServiceDomain, ToolMetadata
14
+
15
+ from arcade_specstream._api import DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, SpecStreamAPI, SpecStreamError
16
+
17
+ KEY = "SPECSTREAM_API_KEY"
18
+ MAX_PRICE = "SPECSTREAM_MAX_PRICE_USD"
19
+ MAX_RESULTS = 1000
20
+ POLL_SECONDS = 3.0
21
+
22
+
23
+ def _metadata(operation: Operation, *, read_only: bool, idempotent: bool) -> ToolMetadata:
24
+ return ToolMetadata(
25
+ classification=Classification(service_domains=[ServiceDomain.WEB_SCRAPING]),
26
+ behavior=Behavior(
27
+ operations=[operation],
28
+ read_only=read_only,
29
+ destructive=False,
30
+ idempotent=idempotent,
31
+ open_world=True,
32
+ ),
33
+ )
34
+
35
+
36
+ def _api(context: Context) -> SpecStreamAPI:
37
+ try:
38
+ key = context.get_secret(KEY).strip()
39
+ except ValueError:
40
+ key = ""
41
+ if not key:
42
+ raise ToolExecutionError(
43
+ "SpecStream needs an API key.",
44
+ developer_message="Set the Arcade secret SPECSTREAM_API_KEY. Create a key under Agents & API in your SpecStream workspace.",
45
+ )
46
+ return SpecStreamAPI(key, DEFAULT_BASE_URL)
47
+
48
+
49
+ def _max_price_usd(context: Context) -> float:
50
+ try:
51
+ value = float(context.get_secret(MAX_PRICE).strip().lstrip("$"))
52
+ except ValueError:
53
+ value = 0.0
54
+ if not value > 0:
55
+ raise ToolExecutionError(
56
+ "No price ceiling is set for SpecStream lists, so nothing ran.",
57
+ developer_message="Set the Arcade secret SPECSTREAM_MAX_PRICE_USD to the most one list may cost, in US dollars (for example 5).",
58
+ )
59
+ return value
60
+
61
+
62
+ async def _call(func: Any, *args: Any, **kwargs: Any) -> dict[str, Any]:
63
+ try:
64
+ return await asyncio.to_thread(func, *args, **kwargs)
65
+ except ValueError as error:
66
+ raise RetryableToolError(str(error), additional_prompt_content=str(error)) from None
67
+ except SpecStreamError as error:
68
+ raise ToolExecutionError(str(error)) from None
69
+
70
+
71
+ @tool(
72
+ requires_secrets=[KEY, MAX_PRICE],
73
+ metadata=_metadata(Operation.CREATE, read_only=False, idempotent=True),
74
+ )
75
+ async def find_list(
76
+ context: Context,
77
+ request: Annotated[
78
+ str,
79
+ "The list in plain words: what to find, where, what every row must meet, and the facts to bring back. "
80
+ 'Example: "Dental clinics in Lisbon with online booking, with their website and phone".',
81
+ ],
82
+ max_results: Annotated[int, "How many rows to find, from 1 to 1000. The price grows with the matches."] = 25,
83
+ ) -> Annotated[dict[str, Any], "status, list_id, list_link and rows, each with its columns, source_url and checked_at"]:
84
+ """Find a list of real things on the live web from a plain-English request, with the page each row was read from.
85
+
86
+ Use it when the answer is many things that meet conditions: companies in a city, local businesses with a
87
+ service, funding filings, open grants, tenders, clinical trials, repositories, people in a role. For one fact,
88
+ use WebSearch. Rows that couldn't be confirmed are left out and aren't charged. status "over_maximum" means
89
+ nothing ran because the price was above the ceiling: ask for fewer rows or tell the user. status "needs_edit"
90
+ means the request was too vague to price: add the place or the conditions and call again. If the list is still
91
+ running, call GetListResults with its list_id for the rest. The same request within the hour returns the same
92
+ list and is not bought twice.
93
+ """
94
+ api = _api(context)
95
+ ceiling = _max_price_usd(context)
96
+ return await _call(
97
+ api.find_list,
98
+ request,
99
+ max_results=max(1, min(int(max_results), MAX_RESULTS)),
100
+ max_price_usd=ceiling,
101
+ wait_seconds=DEFAULT_WAIT_SECONDS,
102
+ poll_interval=POLL_SECONDS,
103
+ )
104
+
105
+
106
+ @tool(
107
+ requires_secrets=[KEY],
108
+ metadata=_metadata(Operation.READ, read_only=True, idempotent=True),
109
+ )
110
+ async def get_list_results(
111
+ context: Context,
112
+ list_id: Annotated[str, 'The list_id that FindList returned, like "fnd_gk5y3d0r97bvyz0t08zzh75kr6".'],
113
+ ) -> Annotated[dict[str, Any], "status, list_id, list_link and every row found so far"]:
114
+ """Read every row found so far for a SpecStream list, such as one that was still running. Reading is free."""
115
+ return await _call(_api(context).results, (list_id or "").strip())
116
+
117
+
118
+ @tool(
119
+ requires_secrets=[KEY],
120
+ metadata=_metadata(Operation.READ, read_only=True, idempotent=True),
121
+ )
122
+ async def web_search(
123
+ context: Context,
124
+ query: Annotated[str, "Search query or question in everyday words, up to 2,000 characters."],
125
+ passages: Annotated[bool, "Include main text passages from the top matching pages."] = False,
126
+ speed: Annotated[
127
+ str,
128
+ 'Search speed: "fast" returns the ranked results in about a second for $1 per 1,000 searches; '
129
+ '"default" also reads the answer from the pages, for $5 per 1,000. Leave it empty for the default search.',
130
+ ] = "",
131
+ ) -> Annotated[dict[str, Any], "answer (value, page and seen_at), matching rows, ranked sources and optional passages"]:
132
+ """Search the live web in seconds with the SpecStream Search API ($5 per 1,000 searches of up to 10 results; a fast search costs $1 per 1,000)."""
133
+ return await _call(_api(context).web_search, query, passages=passages, speed=speed)
134
+
135
+
136
+ @tool(
137
+ requires_secrets=[KEY],
138
+ metadata=_metadata(Operation.READ, read_only=True, idempotent=True),
139
+ )
140
+ async def extract_pages(
141
+ context: Context,
142
+ urls: Annotated[list[str], "1 to 20 http or https URLs to read live: web pages, PDF, Word or Excel files."],
143
+ format: Annotated[str, 'Output format: "markdown" or "text".'] = "markdown",
144
+ ) -> Annotated[dict[str, Any], "each page's main text, title and published date"]:
145
+ """Read the main text, title and published date of 1 to 20 URLs live with the SpecStream Extract API ($0.80 per 1,000 pages, empty pages free)."""
146
+ return await _call(_api(context).extract_pages, urls, format=format)
@@ -0,0 +1,53 @@
1
+ [project]
2
+ name = "arcade-specstream"
3
+ version = "0.1.0"
4
+ description = "SpecStream for Arcade: Deep Search lists from the live web with the source page of every row, plus the Search API and the Extract API."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10,<3.14"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "SpecStream", email = "support@specstream.ai" }]
10
+ maintainers = [{ name = "SpecStream", email = "support@specstream.ai" }]
11
+ keywords = ["arcade", "arcade-ai", "arcade-mcp", "toolkit", "mcp", "specstream", "agents", "tools", "web-data", "live-web", "deep-search", "web-search", "extract", "lead-lists", "company-list"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
23
+ "Topic :: Internet :: WWW/HTTP",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = ["arcade-mcp-server>=1.17.0,<2.0.0"]
27
+
28
+ [project.optional-dependencies]
29
+ test = ["pytest>=8"]
30
+
31
+ [project.scripts]
32
+ arcade-specstream = "arcade_specstream.__main__:main"
33
+ arcade_specstream = "arcade_specstream.__main__:main"
34
+
35
+ [project.urls]
36
+ Homepage = "https://specstream.ai"
37
+ Documentation = "https://specstream.ai/docs"
38
+ Repository = "https://github.com/specstream/specstream-tools/tree/main/packages/arcade-specstream"
39
+ Issues = "https://github.com/specstream/specstream-tools/issues"
40
+ Pricing = "https://specstream.ai/pricing"
41
+
42
+ [build-system]
43
+ requires = ["hatchling>=1.27,<2"]
44
+ build-backend = "hatchling.build"
45
+
46
+ [tool.hatch.build.targets.wheel]
47
+ packages = ["arcade_specstream"]
48
+
49
+ [tool.hatch.build.targets.sdist]
50
+ include = ["arcade_specstream", "tests", "README.md", "LICENSE"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
@@ -0,0 +1,232 @@
1
+ import asyncio
2
+ import io
3
+ import json
4
+ import urllib.error
5
+ import urllib.parse
6
+
7
+ import pytest
8
+ from arcade_core.schema import ToolContext
9
+ from arcade_mcp_server.exceptions import RetryableToolError, ToolExecutionError
10
+
11
+ import arcade_specstream
12
+ from arcade_specstream import extract_pages, find_list, get_list_results, tools, web_search
13
+
14
+ KEY = "ss_live_test_key"
15
+
16
+
17
+ def cell(label, value, source=None):
18
+ provenance = {"source_url": source, "observed_at": "2026-10-14T08:00:00Z"} if source else None
19
+ return {"label": label, "value": value, "display": value, "absence": None, "provenance": provenance}
20
+
21
+
22
+ ROWS = [
23
+ {"entity_id": "e1", "ordinal": 1, "cells": [cell("Organization", "Clínica Sorriso", "https://sorriso.pt/marcacoes"), cell("Website", "https://sorriso.pt")]},
24
+ {"entity_id": "e2", "ordinal": 2, "cells": [cell("Organization", "Dentes de Lisboa", "https://dentesdelisboa.pt"), cell("Website", None) | {"absence": "Not published"}]},
25
+ ]
26
+
27
+ FLAT = {
28
+ "e1": {"id": "fnd_1:e1", "name": "Clínica Sorriso", "name_source": "https://sorriso.pt/marcacoes", "source_url": "https://filings.example/e1", "checked_at": "2026-10-15T09:00:00Z"},
29
+ "e2": {"id": "fnd_1:e2", "name": "Dentes de Lisboa", "name_source": "https://dentesdelisboa.pt", "source_url": "https://filings.example/e2", "checked_at": "2026-10-15T09:00:00Z"},
30
+ }
31
+
32
+
33
+ class FakeSpecStream:
34
+ """Answers like the SpecStream API: the request, its quote, the run, then rows over two polls and two pages."""
35
+
36
+ def __init__(self, maximum_cents=250, runnable=True, status=200):
37
+ self.maximum_cents = maximum_cents
38
+ self.runnable = runnable
39
+ self.status = status
40
+ self.calls = []
41
+ self.polls = 0
42
+
43
+ def __call__(self, request, timeout=None):
44
+ url = urllib.parse.urlsplit(request.full_url)
45
+ body = json.loads(request.data) if request.data else None
46
+ self.calls.append((request.get_method(), url.path, body, dict(request.header_items()), dict(urllib.parse.parse_qsl(url.query))))
47
+ query = dict(urllib.parse.parse_qsl(url.query))
48
+ if self.status != 200:
49
+ raise urllib.error.HTTPError(request.full_url, self.status, "Unauthorized", {}, io.BytesIO(b'{"error": {"message": "Invalid API key"}}'))
50
+ if url.path.startswith("/v1/capacity/requests/"):
51
+ raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}"))
52
+ if url.path == "/v1/parse":
53
+ return self.reply({"status": "runnable" if self.runnable else "needs_input", "ast_hash": "a" * 64, "canonical_sentence": "25 dental clinics in Lisbon"})
54
+ if url.path == "/v1/capacity/quotes":
55
+ return self.reply({"quote_id": "cqt_1", "quote_hash": "b" * 64, "maximum_cents": self.maximum_cents})
56
+ if url.path == "/v1/capacity/executions":
57
+ return self.reply({"find_id": "fnd_1", "state": "running"})
58
+ if url.path == "/v1/finds/fnd_1/rows":
59
+ if query.get("cursor") == "page-2":
60
+ return self.reply({"status": "completed", "rows": ROWS[1:], "next_cursor": None})
61
+ self.polls += 1
62
+ if self.polls == 1:
63
+ return self.reply({"status": "running", "rows": [], "next_cursor": None})
64
+ return self.reply({"status": "completed", "rows": ROWS[:1], "next_cursor": "page-2"})
65
+ if url.path == "/v1/web-search":
66
+ return self.reply({"kind": "fact", "answer": {"value": "Lisbon", "page": "https://example.pt"}})
67
+ if url.path == "/v1/extract":
68
+ return self.reply({"results": [{"url": u, "title": "Page"} for u in body["urls"]]})
69
+ raise AssertionError(f"unexpected call {request.get_method()} {url.path}")
70
+
71
+ @staticmethod
72
+ def reply(data):
73
+ if "rows" in data:
74
+ data = {**data, "flat_rows": [FLAT[row["entity_id"]] for row in data["rows"]]}
75
+ return io.BytesIO(json.dumps({"data": data}).encode())
76
+
77
+ def paths(self):
78
+ return [call[1] for call in self.calls]
79
+
80
+
81
+ @pytest.fixture
82
+ def api(monkeypatch):
83
+ monkeypatch.setattr(tools, "POLL_SECONDS", 0)
84
+
85
+ def install(**kwargs):
86
+ fake = FakeSpecStream(**kwargs)
87
+ monkeypatch.setattr("urllib.request.urlopen", fake)
88
+ return fake
89
+
90
+ return install
91
+
92
+
93
+ def context(key=KEY, max_price="5"):
94
+ ctx = ToolContext()
95
+ if key is not None:
96
+ ctx.set_secret("SPECSTREAM_API_KEY", key)
97
+ if max_price is not None:
98
+ ctx.set_secret("SPECSTREAM_MAX_PRICE_USD", max_price)
99
+ return ctx
100
+
101
+
102
+ def run(coro):
103
+ return asyncio.run(coro)
104
+
105
+
106
+ def test_finds_a_list_within_the_ceiling_and_returns_every_row(api):
107
+ fake = api()
108
+ result = run(find_list(context(), "Dental clinics in Lisbon with online booking", 25))
109
+
110
+ assert result["status"] == "completed"
111
+ assert result["row_count"] == 2
112
+ assert result["list_link"] == "https://specstream.ai/workspace/collections/fnd_1"
113
+ first, second = result["rows"]
114
+ assert first["Organization"] == "Clínica Sorriso"
115
+ assert first["source_url"] == "https://filings.example/e1"
116
+ assert first["name_source"] == "https://sorriso.pt/marcacoes"
117
+ assert second["Website"] == ""
118
+ run_body = next(call[2] for call in fake.calls if call[1] == "/v1/capacity/executions")
119
+ assert run_body["confirm_max_cents"] == 250
120
+ assert run_body["idempotency_key"].startswith("arcade-")
121
+ headers = fake.calls[0][3]
122
+ assert headers["Authorization"] == f"Bearer {KEY}"
123
+ assert headers["User-agent"].startswith("arcade-specstream/")
124
+
125
+
126
+ def test_nothing_runs_when_the_price_is_above_the_ceiling(api):
127
+ fake = api(maximum_cents=900)
128
+ result = run(find_list(context(max_price="$5"), "Dental clinics in Lisbon"))
129
+
130
+ assert result["status"] == "over_maximum"
131
+ assert "$9.00" in result["message"] and "$5.00" in result["message"]
132
+ assert "/v1/capacity/executions" not in fake.paths()
133
+
134
+
135
+ def test_the_rows_asked_for_stay_between_1_and_1000(api):
136
+ fake = api()
137
+ run(find_list(context(), "Dental clinics in Lisbon", 50000))
138
+
139
+ quote = next(call[2] for call in fake.calls if call[1] == "/v1/capacity/quotes")
140
+ assert quote["requested_units"] == 1000
141
+
142
+
143
+ def test_an_unclear_request_comes_back_with_how_it_was_read(api):
144
+ fake = api(runnable=False)
145
+ result = run(find_list(context(), "clinics"))
146
+
147
+ assert result["status"] == "needs_edit"
148
+ assert "25 dental clinics in Lisbon" in result["message"]
149
+ assert "/v1/capacity/quotes" not in fake.paths()
150
+
151
+
152
+ @pytest.mark.parametrize("max_price", [None, "", "0", "five"])
153
+ def test_without_a_price_ceiling_nothing_is_called(api, max_price):
154
+ fake = api()
155
+ with pytest.raises(ToolExecutionError) as error:
156
+ run(find_list(context(max_price=max_price), "Dental clinics in Lisbon"))
157
+
158
+ assert "SPECSTREAM_MAX_PRICE_USD" in error.value.developer_message
159
+ assert fake.calls == []
160
+
161
+
162
+ def test_without_a_key_nothing_is_called(api):
163
+ fake = api()
164
+ with pytest.raises(ToolExecutionError) as error:
165
+ run(web_search(context(key=None), "capital of Portugal"))
166
+
167
+ assert "SPECSTREAM_API_KEY" in error.value.developer_message
168
+ assert fake.calls == []
169
+
170
+
171
+ def test_an_api_refusal_is_a_tool_error_with_its_message(api):
172
+ api(status=401)
173
+ with pytest.raises(ToolExecutionError) as error:
174
+ run(get_list_results(context(), "fnd_1"))
175
+
176
+ assert "401" in str(error.value) and "Invalid API key" in str(error.value)
177
+ assert KEY not in str(error.value)
178
+
179
+
180
+ def test_reading_a_list_follows_every_page(api):
181
+ fake = api()
182
+ fake.polls = 1
183
+ result = run(get_list_results(context(), " fnd_1 "))
184
+
185
+ assert result["status"] == "completed"
186
+ assert [row["Organization"] for row in result["rows"]] == ["Clínica Sorriso", "Dentes de Lisboa"]
187
+
188
+
189
+ def test_web_search_sends_the_query_and_passages(api):
190
+ fake = api()
191
+ result = run(web_search(context(), "capital of Portugal", True))
192
+
193
+ assert result["answer"]["value"] == "Lisbon"
194
+ method, path, _, _, query = fake.calls[0]
195
+ assert (method, path) == ("GET", "/v1/web-search")
196
+ assert query == {"q": "capital of Portugal", "passages": "true"}
197
+
198
+
199
+ def test_an_empty_query_asks_the_model_again(api):
200
+ fake = api()
201
+ with pytest.raises(RetryableToolError):
202
+ run(web_search(context(), " "))
203
+ assert fake.calls == []
204
+
205
+
206
+ def test_extract_pages_posts_the_urls(api):
207
+ fake = api()
208
+ result = run(extract_pages(context(), ["https://example.com/a", "https://example.com/b"], "text"))
209
+
210
+ assert len(result["results"]) == 2
211
+ assert fake.calls[0][2] == {"urls": ["https://example.com/a", "https://example.com/b"], "format": "text"}
212
+
213
+
214
+ def test_the_toolkit_registers_four_tools_with_their_secrets():
215
+ from arcade_core.catalog import ToolCatalog
216
+
217
+ catalog = ToolCatalog()
218
+ catalog.add_module(arcade_specstream, "SpecStream")
219
+ definitions = {tool.definition.name: tool.definition for tool in catalog}
220
+
221
+ assert set(definitions) == {"FindList", "GetListResults", "WebSearch", "ExtractPages"}
222
+ secrets = {name: {s.key for s in d.requirements.secrets or []} for name, d in definitions.items()}
223
+ assert secrets["FindList"] == {"SPECSTREAM_API_KEY", "SPECSTREAM_MAX_PRICE_USD"}
224
+ assert secrets["WebSearch"] == {"SPECSTREAM_API_KEY"}
225
+ params = {p.name for p in definitions["FindList"].input.parameters}
226
+ assert params == {"request", "max_results"}
227
+
228
+
229
+ def test_the_mcp_server_loads():
230
+ from arcade_specstream.__main__ import app
231
+
232
+ assert app is not None
@@ -0,0 +1,45 @@
1
+ import asyncio
2
+ import io
3
+ import json
4
+ import urllib.parse
5
+
6
+ import pytest
7
+ from arcade_core.schema import ToolContext
8
+ from arcade_mcp_server.exceptions import RetryableToolError
9
+
10
+ from arcade_specstream import web_search
11
+
12
+
13
+ @pytest.fixture
14
+ def queries(monkeypatch):
15
+ seen = []
16
+
17
+ def fake(request, timeout=None):
18
+ url = urllib.parse.urlsplit(request.full_url)
19
+ assert url.path == "/v1/web-search"
20
+ seen.append(dict(urllib.parse.parse_qsl(url.query)))
21
+ return io.BytesIO(json.dumps({"data": {"kind": "list", "sources": []}}).encode())
22
+
23
+ monkeypatch.setattr("urllib.request.urlopen", fake)
24
+ return seen
25
+
26
+
27
+ def context():
28
+ ctx = ToolContext()
29
+ ctx.set_secret("SPECSTREAM_API_KEY", "ss_live_test_key")
30
+ return ctx
31
+
32
+
33
+ @pytest.mark.parametrize(
34
+ ("speed", "sent"),
35
+ [("fast", {"q": "espresso machines", "speed": "fast"}), ("", {"q": "espresso machines"})],
36
+ )
37
+ def test_web_search_sends_the_speed_only_when_one_is_given(queries, speed, sent):
38
+ asyncio.run(web_search(context(), "espresso machines", False, speed))
39
+ assert queries == [sent]
40
+
41
+
42
+ def test_an_unknown_speed_is_refused_before_any_call(queries):
43
+ with pytest.raises(RetryableToolError):
44
+ asyncio.run(web_search(context(), "espresso machines", False, "turbo"))
45
+ assert queries == []