tickwire-mcp 0.1.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,16 @@
1
+ """Tickwire MCP server: MT4/MT5 trading tools for AI agents, with the safety
2
+ built in (agent keys scoped to accounts, kill switches, the owner's pre-trade
3
+ hook, idempotent orders and truthful outcomes).
4
+
5
+ It is a thin client of the Tickwire agent API (``/v1/agent/…``, served by the
6
+ control plane); it never talks to terminals directly. Run it locally over
7
+ stdio (``tickwire-mcp stdio``) or hosted over streamable HTTP
8
+ (``tickwire-mcp http``). See ``docs/ai-agents.md``.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ __version__ = "0.1.0" # before the imports below: api.py puts it in the User-Agent
13
+
14
+ from .server import build_server # noqa: E402
15
+
16
+ __all__ = ["build_server", "__version__"]
@@ -0,0 +1,287 @@
1
+ """Run the Tickwire MCP server.
2
+
3
+ Local (stdio), for Claude Desktop / Claude Code / Cursor on your machine::
4
+
5
+ TICKWIRE_AGENT_KEY=twag_… TICKWIRE_API_URL=https://api.tickwire.io tickwire-mcp stdio
6
+
7
+ Hosted (streamable HTTP), one server for many agents; each MCP client sends its
8
+ own agent key as ``Authorization: Bearer twag_…``::
9
+
10
+ TICKWIRE_API_URL=https://api.tickwire.io \\
11
+ TICKWIRE_MCP_ALLOWED_HOSTS=api.tickwire.io tickwire-mcp http --port 8765
12
+
13
+ Environment:
14
+
15
+ ``TICKWIRE_API_URL`` Tickwire API base (default ``https://api.tickwire.io``)
16
+ ``TICKWIRE_SANDBOX`` ``1`` (or ``--sandbox``): use the sandbox instead
17
+ ``TICKWIRE_SANDBOX_URL`` the sandbox API base; required with ``--sandbox`` (no
18
+ sandbox host is built in, and it never falls back to live)
19
+ ``TICKWIRE_DOCS_URL`` docs site for ``search_tickwire_docs`` (default
20
+ ``https://tickwire.io``; public, no key sent)
21
+ ``TICKWIRE_AGENT_KEY`` stdio only: the agent key
22
+ ``TICKWIRE_MCP_IDEMPOTENCY_WINDOW_S`` window for derived idempotency keys (default 60)
23
+ ``TICKWIRE_MCP_ALLOWED_HOSTS`` http only: comma-separated Host values accepted
24
+ (DNS-rebinding protection); unset = localhost only.
25
+ The host of ``TICKWIRE_MCP_PUBLIC_URL`` is always added
26
+ ``TICKWIRE_MCP_ALLOWED_ORIGINS`` http only: extra comma-separated Origin values accepted.
27
+ Requests without Origin are always fine; the public URL's
28
+ origin and the AI apps' web origins (claude.ai, claude.com,
29
+ chatgpt.com) are always accepted
30
+ ``TICKWIRE_MCP_PUBLIC_URL`` http only: this server's public URL, exactly as users type
31
+ it into Claude or ChatGPT (``https://api.<domain>/mcp``, or
32
+ ``https://tickwire-gw.fly.dev/mcp`` while there is no
33
+ domain). With ``TICKWIRE_OAUTH_ISSUER`` and
34
+ ``TICKWIRE_MCP_RS_SECRET`` it turns on Sign in with Tickwire for AI apps
35
+ (see ``tickwire_mcp/oauth.py``)
36
+ ``TICKWIRE_MCP_MAX_BODY_BYTES`` http only: largest request body on ``/mcp`` (default 262144,
37
+ 256 KB); bigger bodies get 413 ``payload_too_large``
38
+ ``TICKWIRE_MCP_KEY_CHECK_TIMEOUT_S`` http only: how long the key check before ``tools/call``
39
+ may take (default 1); see ``tickwire_mcp/guards.py``
40
+ ``TICKWIRE_MCP_KEY_CHECK_TTL_S`` http only: how long a valid key's check is cached (default 60)
41
+
42
+ Hosted auth: ``initialize`` and ``tools/list`` need only a well-formed agent key
43
+ (``twag_…``), on purpose, so MCP directories can list the tools with a
44
+ placeholder key. ``tools/call`` checks the key first: an invalid, expired or
45
+ revoked key gets 401 ``invalid_agent_key`` at once (``guards.py``).
46
+
47
+ Hosted mode also serves ``GET /healthz`` (no auth, no secrets): 200
48
+ ``{"status": "ok"}`` when ``TICKWIRE_API_URL`` is set, 503 otherwise.
49
+ """
50
+ from __future__ import annotations
51
+
52
+ import argparse
53
+ import json
54
+ import os
55
+ import sys
56
+ from urllib.parse import urlsplit
57
+
58
+ from mcp.server.mcpserver import Context
59
+ from mcp.server.transport_security import TransportSecuritySettings
60
+
61
+ from . import __version__
62
+ from .api import TickwireApi
63
+ from .idempotency import key_fingerprint
64
+ from .guards import BodyLimit, KeyCheck
65
+ from .oauth import IDENTITY_HEADER, AuthConfig, McpAuthGuard, _challenge
66
+ from .server import build_server
67
+
68
+ DEFAULT_API_URL = "https://api.tickwire.io"
69
+ MCP_PATH = "/mcp"
70
+ TRUE = ("1", "true", "yes", "on")
71
+
72
+
73
+ class MissingKey(Exception):
74
+ pass
75
+
76
+
77
+ class ConfigError(Exception):
78
+ pass
79
+
80
+
81
+ def sandbox_enabled() -> bool:
82
+ return os.environ.get("TICKWIRE_SANDBOX", "").strip().lower() in TRUE
83
+
84
+
85
+ def api_url(sandbox: bool | None = None) -> str:
86
+ """The Tickwire API base. In sandbox mode (``sandbox=True`` or TICKWIRE_SANDBOX set),
87
+ TICKWIRE_SANDBOX_URL, which is then required."""
88
+ if sandbox or (sandbox is None and sandbox_enabled()):
89
+ url = os.environ.get("TICKWIRE_SANDBOX_URL", "").strip()
90
+ if not url:
91
+ raise ConfigError("TICKWIRE_SANDBOX is set but TICKWIRE_SANDBOX_URL is not: "
92
+ "set the sandbox API URL (the server never falls back to live)")
93
+ return url.rstrip("/")
94
+ return os.environ.get("TICKWIRE_API_URL", DEFAULT_API_URL).rstrip("/")
95
+
96
+
97
+ def stdio_factory(transport=None, base_url: str | None = None):
98
+ key = os.environ.get("TICKWIRE_AGENT_KEY", "").strip()
99
+
100
+ def factory(ctx: Context) -> TickwireApi:
101
+ if not key:
102
+ raise MissingKey("set TICKWIRE_AGENT_KEY to an agent key (twag_…)")
103
+ return TickwireApi(base_url or api_url(), key, transport=transport)
104
+ return factory
105
+
106
+
107
+ def bearer_key(headers) -> str | None:
108
+ if not headers:
109
+ return None
110
+ auth = headers.get("authorization") or ""
111
+ if auth.lower().startswith("bearer "):
112
+ tok = auth[7:].strip()
113
+ return tok or None
114
+ if auth.strip().startswith("twag_"):
115
+ return auth.strip()
116
+ tok = headers.get("x-tickwire-agent-key")
117
+ return tok.strip() if tok else None
118
+
119
+
120
+ def http_factory(transport=None, base_url: str | None = None):
121
+ def factory(ctx: Context) -> TickwireApi:
122
+ key = bearer_key(ctx.headers)
123
+ if not key:
124
+ raise MissingKey("send the agent key as Authorization: Bearer twag_…")
125
+ api = TickwireApi(base_url or api_url(), key, transport=transport)
126
+ ident = (ctx.headers or {}).get(IDENTITY_HEADER)
127
+ if ident: # a connected app: its delegated token changes per request
128
+ api.agent_fp = key_fingerprint("agent-key-id:" + ident)
129
+ return api
130
+ return factory
131
+
132
+
133
+ class RequireAgentKey:
134
+ """ASGI guard for hosted mode: MCP requests without an agent key get a 401
135
+ before reaching the protocol layer. The key itself is checked by the
136
+ Tickwire API on every tool call."""
137
+
138
+ def __init__(self, app) -> None:
139
+ self.app = app
140
+
141
+ async def __call__(self, scope, receive, send):
142
+ if scope["type"] == "http" and scope["path"].startswith(MCP_PATH):
143
+ headers = {k.decode("latin-1").lower(): v.decode("latin-1")
144
+ for k, v in scope.get("headers", [])}
145
+ key = bearer_key(headers)
146
+ if not key or not key.startswith("twag_"):
147
+ body = json.dumps({"error": "missing_agent_key",
148
+ "message": "send a Tickwire agent key as "
149
+ "Authorization: Bearer twag_…"}).encode()
150
+ await send({"type": "http.response.start", "status": 401,
151
+ "headers": [(b"content-type", b"application/json"),
152
+ (b"www-authenticate", b'Bearer realm="tickwire"')]})
153
+ await send({"type": "http.response.body", "body": body})
154
+ return
155
+ await self.app(scope, receive, send)
156
+
157
+
158
+ HEALTH_PATH = "/healthz"
159
+
160
+
161
+ class Health:
162
+ """``GET /healthz`` (no auth, no secrets): 200 ``{"status": "ok"}`` when the
163
+ server is serving and knows where the Tickwire API is; 503
164
+ ``{"status": "not_configured"}`` when ``TICKWIRE_API_URL`` is unset (it would
165
+ fall back to the placeholder default and every tool call would fail). It
166
+ doesn't call the API: that needs an agent key, which only clients have."""
167
+
168
+ def __init__(self, app, base_url: str | None = None) -> None:
169
+ self.app, self.base_url = app, base_url
170
+
171
+ async def __call__(self, scope, receive, send):
172
+ if scope["type"] == "http" and scope["path"] == HEALTH_PATH:
173
+ configured = bool(self.base_url or os.environ.get("TICKWIRE_API_URL", "").strip())
174
+ status, body = ((200, {"status": "ok"}) if configured else
175
+ (503, {"status": "not_configured",
176
+ "reason": "TICKWIRE_API_URL is not set"}))
177
+ if scope.get("method") not in ("GET", "HEAD"):
178
+ status, body = 405, {"error": "method_not_allowed", "message": "use GET"}
179
+ payload = json.dumps(body).encode()
180
+ await send({"type": "http.response.start", "status": status,
181
+ "headers": [(b"content-type", b"application/json"),
182
+ (b"cache-control", b"no-store")]})
183
+ await send({"type": "http.response.body",
184
+ "body": b"" if scope.get("method") == "HEAD" else payload})
185
+ return
186
+ await self.app(scope, receive, send)
187
+
188
+
189
+ # Web origins of the AI apps that connect to the hosted server. Their
190
+ # connectors call from their servers (no Origin header), but a browser-side
191
+ # request from these pages must not be refused as DNS rebinding.
192
+ AI_APP_ORIGINS = ("https://claude.ai", "https://claude.com", "https://chatgpt.com")
193
+
194
+
195
+ def _csv(name: str) -> list[str]:
196
+ return [v.strip() for v in os.environ.get(name, "").split(",") if v.strip()]
197
+
198
+
199
+ def transport_security(allowed_hosts: list[str] | None,
200
+ public_url: str = "") -> TransportSecuritySettings | None:
201
+ """DNS-rebinding settings for the hosted transport.
202
+
203
+ Hosts: ``allowed_hosts`` (or ``TICKWIRE_MCP_ALLOWED_HOSTS``) plus the host of
204
+ the public URL, so the one setting that names the public address is enough
205
+ (``tickwire-gw.fly.dev`` while there is no domain: the gateway keeps the
206
+ client's Host header). Nothing configured: ``None``, the SDK's localhost-only
207
+ default. Origins: the public URL's origin, :data:`AI_APP_ORIGINS` and
208
+ ``TICKWIRE_MCP_ALLOWED_ORIGINS``; a request without Origin always passes."""
209
+ hosts = list(allowed_hosts) if allowed_hosts is not None else _csv("TICKWIRE_MCP_ALLOWED_HOSTS")
210
+ origins = list(AI_APP_ORIGINS) + _csv("TICKWIRE_MCP_ALLOWED_ORIGINS")
211
+ p = urlsplit(public_url) if public_url else None
212
+ if p and p.scheme == "https" and p.hostname:
213
+ netloc = p.netloc.lower()
214
+ hosts += [netloc, f"{netloc}:*"] if p.port is None else [netloc]
215
+ origins.append(f"https://{netloc}")
216
+ if not hosts:
217
+ return None
218
+ return TransportSecuritySettings(allowed_hosts=list(dict.fromkeys(hosts)),
219
+ allowed_origins=list(dict.fromkeys(origins)))
220
+
221
+
222
+ def http_app(*, transport=None, base_url: str | None = None, allowed_hosts: list[str] | None = None,
223
+ oauth: AuthConfig | None = None):
224
+ """The hosted ASGI app (stateless streamable HTTP, JSON responses), plus
225
+ an unauthenticated ``GET /healthz`` (see :class:`Health`). With OAuth
226
+ configured (``oauth`` or the environment, see :mod:`.oauth`) it also
227
+ accepts Sign in with Tickwire access tokens."""
228
+ server = build_server(_safe(http_factory(transport, base_url)))
229
+ oauth = oauth if oauth is not None else AuthConfig.from_env(base_url or api_url())
230
+ public = oauth.resource or os.environ.get("TICKWIRE_MCP_PUBLIC_URL", "").strip()
231
+ security = transport_security(allowed_hosts, public)
232
+ app = server.streamable_http_app(streamable_http_path=MCP_PATH, stateless_http=True,
233
+ json_response=True, transport_security=security)
234
+ # Outside in: health, body limit (BUG-069), credentials, key check before
235
+ # tools/call (BUG-068), the protocol. See guards.py.
236
+ checked = KeyCheck(app, base_url=base_url or api_url(), key_of=bearer_key, mcp_path=MCP_PATH,
237
+ transport=transport,
238
+ challenge=(lambda msg: _challenge(oauth, "invalid_token", msg))
239
+ if oauth.enabled else None)
240
+ if oauth.enabled:
241
+ guarded = McpAuthGuard(checked, config=oauth, mcp_path=MCP_PATH, transport=transport)
242
+ else:
243
+ guarded = RequireAgentKey(checked)
244
+ return Health(BodyLimit(guarded, mcp_path=MCP_PATH), base_url)
245
+
246
+
247
+ def _safe(factory):
248
+ """Turn a missing key into a readable tool error (never the key itself)."""
249
+ def wrapped(ctx: Context) -> TickwireApi:
250
+ try:
251
+ return factory(ctx)
252
+ except MissingKey as exc:
253
+ from mcp.server.mcpserver.exceptions import ToolError
254
+ raise ToolError(str(exc)) from None
255
+ return wrapped
256
+
257
+
258
+ def main(argv: list[str] | None = None) -> None:
259
+ p = argparse.ArgumentParser(prog="tickwire-mcp", description="Tickwire MCP server")
260
+ p.add_argument("--version", action="version", version=f"tickwire-mcp {__version__}")
261
+ p.add_argument("--sandbox", action="store_true",
262
+ help="use the sandbox (TICKWIRE_SANDBOX_URL) instead of TICKWIRE_API_URL")
263
+ sub = p.add_subparsers(dest="mode")
264
+ sub.add_parser("stdio", help="serve one agent over stdio (default)")
265
+ h = sub.add_parser("http", help="serve many agents over streamable HTTP")
266
+ h.add_argument("--host", default="127.0.0.1")
267
+ h.add_argument("--port", type=int, default=8765)
268
+ args = p.parse_args(argv)
269
+ sandbox = args.sandbox or sandbox_enabled()
270
+ try:
271
+ target = api_url(sandbox)
272
+ except ConfigError as exc:
273
+ print(f"tickwire-mcp: {exc}", file=sys.stderr)
274
+ raise SystemExit(2) from None
275
+ print(f"tickwire-mcp {__version__}: {'sandbox' if sandbox else 'live'} API at {target}", file=sys.stderr)
276
+ if args.mode == "http":
277
+ import uvicorn
278
+ uvicorn.run(http_app(base_url=target), host=args.host, port=args.port, log_level="info",
279
+ lifespan="on")
280
+ return
281
+ if not os.environ.get("TICKWIRE_AGENT_KEY"):
282
+ print("tickwire-mcp: TICKWIRE_AGENT_KEY is not set", file=sys.stderr)
283
+ build_server(_safe(stdio_factory(base_url=target))).run("stdio")
284
+
285
+
286
+ if __name__ == "__main__":
287
+ main()
tickwire_mcp/api.py ADDED
@@ -0,0 +1,73 @@
1
+ """HTTP client for the Tickwire agent API (``/v1/agent/…``).
2
+
3
+ The agent key goes in ``X-Tickwire-Agent-Key`` (agent keys are refused on the
4
+ terminal routes, so an agent can only ever use the guarded surface). The reason
5
+ goes in ``X-Reason`` (percent-encoded), the idempotency key in
6
+ ``Idempotency-Key``, and ``X-Actor`` names the MCP client (the server records
7
+ it; the authoritative actor is the key). ``X-Tickwire-Tool`` names the tool
8
+ for the audit log. The key is never logged or echoed.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+ from urllib.parse import quote
14
+
15
+ import httpx
16
+
17
+ from . import __version__
18
+ from .idempotency import key_fingerprint
19
+
20
+ USER_AGENT = f"tickwire-mcp/{__version__}"
21
+
22
+
23
+ class TickwireApi:
24
+ def __init__(self, base_url: str, agent_key: str, *, transport=None,
25
+ timeout: float = 45.0, client_label: str = "tickwire-mcp") -> None:
26
+ self.base_url = base_url.rstrip("/")
27
+ self._key = agent_key
28
+ self.agent_fp = key_fingerprint(agent_key)
29
+ self._transport = transport
30
+ self._timeout = timeout
31
+ self.client_label = client_label
32
+
33
+ def __repr__(self) -> str: # never show the key
34
+ return f"TickwireApi({self.base_url!r})"
35
+
36
+ def _headers(self, tool: str, extra: dict | None = None) -> dict:
37
+ h = {"X-Tickwire-Agent-Key": self._key, "X-Tickwire-Tool": tool,
38
+ "User-Agent": USER_AGENT, "X-Actor": self.client_label}
39
+ if extra:
40
+ h.update(extra)
41
+ return h
42
+
43
+ async def call(self, method: str, path: str, *, tool: str, params: dict | None = None,
44
+ json: Any = None, headers: dict | None = None) -> tuple[int, Any]:
45
+ try:
46
+ async with httpx.AsyncClient(transport=self._transport, timeout=self._timeout) as c:
47
+ r = await c.request(method, self.base_url + path, params=params, json=json,
48
+ headers=self._headers(tool, headers))
49
+ except (httpx.ConnectError, httpx.ConnectTimeout, httpx.UnsupportedProtocol,
50
+ httpx.InvalidURL) as exc:
51
+ return 0, {"error": "tickwire_unreachable", "sent": False,
52
+ "message": f"could not reach the Tickwire API ({type(exc).__name__}); "
53
+ "nothing was sent"}
54
+ except httpx.HTTPError as exc:
55
+ return 0, {"error": "tickwire_no_reply", "sent": "unknown", "outcome": "unknown",
56
+ "message": f"no reply from the Tickwire API ({type(exc).__name__}). If this "
57
+ "was a trade it MAY have executed: call get_trade_status with "
58
+ "the same idempotency_key before doing anything else."}
59
+ try:
60
+ body = r.json()
61
+ except ValueError:
62
+ body = {"error": "bad_response", "message": f"HTTP {r.status_code} without JSON"}
63
+ return r.status_code, body
64
+
65
+ async def get(self, path: str, *, tool: str, params: dict | None = None) -> tuple[int, Any]:
66
+ return await self.call("GET", path, tool=tool, params=params)
67
+
68
+ async def trade(self, account_id: str, order: dict, *, idempotency_key: str, reason: str,
69
+ tool: str) -> tuple[int, Any]:
70
+ return await self.call(
71
+ "POST", f"/v1/agent/accounts/{quote(account_id, safe='')}/trade", tool=tool,
72
+ json=order, headers={"Idempotency-Key": idempotency_key,
73
+ "X-Reason": quote(reason, safe=" ,.:;!?()-_/'\"@#$&*+=<>[]{}|~^`")})
@@ -0,0 +1,119 @@
1
+ """Read-only search over Tickwire's public docs, for the ``search_tickwire_docs`` tool.
2
+
3
+ The docs site publishes every page and the whole API reference as one Markdown
4
+ file, ``<docs>/llms-full.txt`` (pages separated by ``---`` lines, each starting
5
+ with ``# Title`` and a ``Source: <url>`` line). This module fetches it (cached),
6
+ splits it into sections by heading and ranks them with a plain term score.
7
+ No credentials are sent: it's a public, unauthenticated GET.
8
+
9
+ ``TICKWIRE_DOCS_URL`` sets the docs origin (default ``https://tickwire.io``).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import re
15
+ import time
16
+ from dataclasses import dataclass
17
+
18
+ import httpx
19
+
20
+ from . import __version__
21
+
22
+ DEFAULT_DOCS_URL = "https://tickwire.io"
23
+ TTL_S = 3600.0
24
+ MAX_BYTES = 5_000_000
25
+ _WORD = re.compile(r"[a-z0-9_]+")
26
+ _PAGE_SPLIT = re.compile(r"\n---\n\n")
27
+ _HEADING = re.compile(r"^(#{1,3}) (.+)$", re.M)
28
+ _SOURCE = re.compile(r"^Source: (\S+)$", re.M)
29
+
30
+
31
+ def docs_url() -> str:
32
+ return os.environ.get("TICKWIRE_DOCS_URL", DEFAULT_DOCS_URL).strip().rstrip("/")
33
+
34
+
35
+ @dataclass
36
+ class Section:
37
+ page: str
38
+ heading: str
39
+ url: str
40
+ text: str
41
+
42
+
43
+ def split_sections(full: str) -> list[Section]:
44
+ """``llms-full.txt`` -> sections (a page's intro, then one per ## or ### heading)."""
45
+ out: list[Section] = []
46
+ for page in _PAGE_SPLIT.split(full):
47
+ page = page.strip()
48
+ if not page.startswith("# "):
49
+ continue
50
+ title = page.splitlines()[0][2:].strip()
51
+ src = _SOURCE.search(page)
52
+ url = src.group(1) if src else ""
53
+ marks = [m for m in _HEADING.finditer(page) if len(m.group(1)) > 1]
54
+ bounds = [0] + [m.start() for m in marks] + [len(page)]
55
+ for i in range(len(bounds) - 1):
56
+ chunk = page[bounds[i]:bounds[i + 1]].strip()
57
+ if not chunk:
58
+ continue
59
+ heading = title if i == 0 else marks[i - 1].group(2).strip()
60
+ anchor = "" if i == 0 else "#" + re.sub(r"[^a-z0-9]+", "-", heading.lower()).strip("-")
61
+ out.append(Section(title, heading, url + anchor if url and i else url, chunk))
62
+ return out
63
+
64
+
65
+ def _terms(s: str) -> list[str]:
66
+ return _WORD.findall(s.lower())
67
+
68
+
69
+ def search(sections: list[Section], query: str, limit: int = 5) -> list[dict]:
70
+ terms = [t for t in dict.fromkeys(_terms(query)) if len(t) > 1]
71
+ if not terms:
72
+ return []
73
+ scored = []
74
+ for s in sections:
75
+ body = _terms(s.text)
76
+ head = set(_terms(s.heading)) | set(_terms(s.page))
77
+ counts = {t: body.count(t) for t in terms}
78
+ matched = sum(1 for t in terms if counts[t] or t in head)
79
+ if not matched:
80
+ continue
81
+ score = matched * 10 + sum(min(c, 5) for c in counts.values()) + 6 * sum(1 for t in terms if t in head)
82
+ scored.append((score, -len(s.text), s))
83
+ scored.sort(key=lambda x: (x[0], x[1]), reverse=True)
84
+ return [{"page": s.page, "section": s.heading, "url": s.url, "excerpt": s.text[:1500]}
85
+ for _, _, s in scored[:limit]]
86
+
87
+
88
+ class DocsIndex:
89
+ """Fetches and caches ``llms-full.txt``; thread-unsafe but async-safe enough for one server."""
90
+
91
+ def __init__(self, base_url: str | None = None, *, transport=None, ttl_s: float = TTL_S,
92
+ clock=time.monotonic) -> None:
93
+ self.base_url = (base_url or docs_url()).rstrip("/")
94
+ self._transport = transport
95
+ self._ttl = ttl_s
96
+ self._clock = clock
97
+ self._sections: list[Section] | None = None
98
+ self._at = 0.0
99
+
100
+ async def sections(self) -> list[Section]:
101
+ if self._sections is not None and self._clock() - self._at < self._ttl:
102
+ return self._sections
103
+ async with httpx.AsyncClient(transport=self._transport, timeout=20.0,
104
+ headers={"User-Agent": f"tickwire-mcp/{__version__}"},
105
+ follow_redirects=True) as c:
106
+ r = await c.get(f"{self.base_url}/llms-full.txt")
107
+ r.raise_for_status()
108
+ text = r.text[:MAX_BYTES]
109
+ self._sections, self._at = split_sections(text), self._clock()
110
+ return self._sections
111
+
112
+ async def search(self, query: str, limit: int = 5) -> dict:
113
+ try:
114
+ sections = await self.sections()
115
+ except (httpx.HTTPError, ValueError) as e:
116
+ return {"error": "docs_unavailable",
117
+ "message": f"Couldn't fetch {self.base_url}/llms-full.txt ({type(e).__name__})."}
118
+ results = search(sections, query, limit)
119
+ return {"query": query, "results": results, "source": f"{self.base_url}/llms-full.txt"}