langbot-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,3 @@
1
+ """Langbot MCP server package."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,322 @@
1
+ """``draft_strategy``: turn a plain-English thesis into a Langbot strategy file (the one shape
2
+ every runner accepts: a class with a synchronous ``on_event(evt, ctx)``).
3
+
4
+ Uses the Anthropic SDK (``LANGBOT_LLM_MODEL``, default ``claude-opus-5-5``).
5
+ Without ``ANTHROPIC_API_KEY`` it returns a filled-in template with a clear note
6
+ so the tool is still useful offline. The user always reviews the code before it
7
+ runs — the MCP server never executes a drafted strategy live.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import os
14
+ import re
15
+ from typing import Any
16
+
17
+ log = logging.getLogger("langbot.mcp.drafting")
18
+
19
+ DEFAULT_MODEL = "claude-opus-5-5"
20
+
21
+ SYSTEM_PROMPT = """You write trading strategies for Langbot, the data and simulation layer for \
22
+ every market on Kalshi and Polymarket. Output ONE complete, runnable Python file that defines \
23
+ exactly one strategy class, wrapped in a single ```python fenced block, followed by a short \
24
+ plain-English explanation (3-6 sentences) of the logic and its risks.
25
+
26
+ Strategy shape (the one shape `langbot sim run`, `langbot backtest` and `langbot run` all accept): \
27
+ a plain class with a synchronous `on_event(self, evt, ctx)`. No base class, no async.
28
+ ```python
29
+ import logging
30
+ from fnmatch import fnmatch
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+ class MyStrategy:
35
+ markets = ["KXEARNINGSMENTIONNVDA-*"] # fnmatch globs over venue tickers
36
+ phrases = ["blackwell"] # phrases to listen for (may be empty)
37
+
38
+ def __init__(self, qty=10): ... # keyword params only; keep state here
39
+ def on_start(self, ctx): ... # optional, once
40
+ def on_event(self, evt, ctx): # evt is a dict, as the stream sends it
41
+ # evt["type"] in {"phrase_detected","transcript_delta","speaker_change","event_started","event_ended",...}
42
+ # evt.get("phrase"), evt.get("market_refs") (tickers), evt.get("speaker"), evt["t_spoken"] (ms)
43
+ ...
44
+ def on_book(self, ticker, book, ctx): ... # optional; book.yes_bid, book.yes_ask, book.mid (dollars 0-1)
45
+ def on_fill(self, fill, ctx): ... # optional; fill is a dict
46
+ def on_end(self, ctx): ... # optional
47
+ ```
48
+ `ctx`: `now` (ms), `tickers`, `book(ticker)`, `position(ticker)` (`.yes`, `.no`), \
49
+ `orders(ticker=None)`, `buy(ticker, side="yes"|"no", qty, limit=None, tif=None|"ioc")`, \
50
+ `sell(...)`, `cancel_all(ticker=None)`. `limit=None` takes the top of the book now; a limit \
51
+ rests unless `tif="ioc"`.
52
+
53
+ Rules:
54
+ - Prices are dollars in (0, 1). Quantities are whole contracts.
55
+ - Live, every order passes the risk rails (max position USD, daily loss, allowlist); do not try to bypass them.
56
+ - Filter tickers yourself with `fnmatch` against `markets`.
57
+ - Guard against missing books (`book is None` or `book.yes_ask is None`).
58
+ - Do not place more than one order per market per trigger unless the thesis says so.
59
+ - No network calls, no `while True` loops, no prints; use `logging`.
60
+ - End the file with `strategy = <YourClassName>`.
61
+
62
+ Base rates (pricing a mention market):
63
+ - The user message may include a `Base rates:` block from Langbot's history API: how often this \
64
+ speaker/phrase mention market settled YES (`yes_rate`), over how many markets, the average opening \
65
+ price and `mispricing` = avg(result - open price). These are venue settlement facts, not signals.
66
+ - When present, put them on the class as constants (`base_rate = 0.72 # 18 markets, 365d`), \
67
+ derive the price ceiling from them (e.g. only lift YES asks below `base_rate - edge`, or fade YES \
68
+ above `base_rate + edge`), and say so in the explanation. Treat small samples (< 5 markets) as weak.
69
+ - Agents can refresh these with the `get_base_rates` MCP tool or `LangbotClient.base_rates()`.
70
+ """
71
+
72
+ TEMPLATE = '''"""Strategy drafted from thesis: {thesis_short}
73
+
74
+ TODO: review and edit before running. Generated as a template because no
75
+ ANTHROPIC_API_KEY was available to the MCP server ({note}).
76
+
77
+ Replay it against recorded books first:
78
+ langbot sim run -e EVENT_ID -s this_file.py
79
+ """
80
+
81
+ from __future__ import annotations
82
+
83
+ import logging
84
+ from fnmatch import fnmatch
85
+ from typing import Any
86
+
87
+ log = logging.getLogger(__name__)
88
+
89
+
90
+ class DraftedStrategy:
91
+ """{thesis_short}"""
92
+
93
+ markets = {markets!r}
94
+ phrases = {phrases!r}
95
+
96
+ max_price = 0.60 # never lift YES asks above this (dollars)
97
+ base_rate = {base_rate!r} # {base_rate_note}
98
+ edge = 0.10 # required discount to the base rate before lifting an ask
99
+ count = 10 # contracts per trigger
100
+
101
+ def __init__(self) -> None:
102
+ self.taken: set[str] = set()
103
+
104
+ @property
105
+ def price_ceiling(self) -> float:
106
+ """Highest YES ask worth lifting: the base rate minus `edge`, capped by `max_price`."""
107
+ if self.base_rate is None:
108
+ return self.max_price
109
+ return min(self.max_price, self.base_rate - self.edge)
110
+
111
+ def tracks(self, ticker: str) -> bool:
112
+ return any(fnmatch(ticker, g) for g in self.markets)
113
+
114
+ def on_event(self, evt: dict[str, Any], ctx: Any) -> None:
115
+ if evt.get("type") != "phrase_detected" or evt.get("phrase") not in self.phrases:
116
+ return
117
+ for ticker in evt.get("market_refs") or []:
118
+ if ticker in self.taken or not self.tracks(ticker):
119
+ continue
120
+ book = ctx.book(ticker)
121
+ if book is None or book.yes_ask is None or book.yes_ask >= self.price_ceiling:
122
+ continue
123
+ self.taken.add(ticker)
124
+ log.info("%r detected; buying %s @ %.2f", evt.get("phrase"), ticker, book.yes_ask)
125
+ ctx.buy(ticker, "yes", self.count, limit=book.yes_ask, tif="ioc")
126
+
127
+
128
+ strategy = DraftedStrategy
129
+ '''
130
+
131
+ _TICKER_RE = re.compile(r"\b(KX[A-Z0-9]+(?:-[A-Z0-9]+)*\*?)\b")
132
+ _QUOTED_RE = re.compile(r"[\"'“‘]([^\"'”’]{2,40})[\"'”’]")
133
+
134
+
135
+ def guess_markets_and_phrases(thesis: str) -> tuple[list[str], list[str]]:
136
+ """Heuristically pull ticker globs and quoted phrases out of a thesis string."""
137
+ tickers = _TICKER_RE.findall(thesis.upper())
138
+ markets = sorted({t if "*" in t or t.count("-") >= 2 else t + "-*" for t in tickers})
139
+ phrases = sorted({q.strip().lower() for q in _QUOTED_RE.findall(thesis) if q.strip()})
140
+ if not markets:
141
+ markets = ["KXEARNINGSMENTION*"]
142
+ return markets, phrases
143
+
144
+
145
+ def _rate_fields(base_rates: dict[str, Any] | None) -> tuple[float | None, str]:
146
+ """``(base_rate, comment)`` for the template from a base-rates dict (or none)."""
147
+ if not base_rates or base_rates.get("yes_rate") is None:
148
+ return None, "no base rate; set from get_base_rates(speaker, phrase) to price the market"
149
+ rate = round(float(base_rates["yes_rate"]), 3)
150
+ who = f"{base_rates.get('speaker') or '*'} / {base_rates.get('phrase') or '*'}"
151
+ n = int(base_rates.get("markets") or 0)
152
+ window = base_rates.get("window_days")
153
+ note = f"P(YES) for {who} over {n} settled markets"
154
+ if window:
155
+ note += f" ({window}d)"
156
+ if n < 5:
157
+ note += " - small sample"
158
+ return rate, note
159
+
160
+
161
+ def format_base_rates(base_rates: dict[str, Any] | None) -> str:
162
+ """Render a base-rates dict as the ``Base rates:`` block appended to the model prompt."""
163
+ if not base_rates:
164
+ return ""
165
+ keys = (
166
+ "speaker",
167
+ "phrase",
168
+ "series",
169
+ "window_days",
170
+ "markets",
171
+ "yes",
172
+ "no",
173
+ "void",
174
+ "yes_rate",
175
+ "avg_open_price",
176
+ "avg_close_price",
177
+ "mispricing",
178
+ )
179
+ lines = [f"- {k}: {base_rates[k]}" for k in keys if base_rates.get(k) is not None]
180
+ months = base_rates.get("by_month") or []
181
+ if months:
182
+ lines.append(
183
+ "- by_month: "
184
+ + ", ".join(
185
+ f"{m.get('month')}={m.get('yes_rate')} (n={m.get('markets')})" for m in months[-6:]
186
+ )
187
+ )
188
+ return "\n\nBase rates (venue settlement facts from Langbot history):\n" + "\n".join(lines)
189
+
190
+
191
+ def template_strategy(thesis: str, note: str, base_rates: dict[str, Any] | None = None) -> str:
192
+ """Render the offline template for ``thesis`` (pricing off ``base_rates`` when given)."""
193
+ markets, phrases = guess_markets_and_phrases(thesis)
194
+ short = " ".join(thesis.split())[:160].replace('"', "'")
195
+ base_rate, base_rate_note = _rate_fields(base_rates)
196
+ return TEMPLATE.format(
197
+ thesis_short=short,
198
+ note=note,
199
+ markets=markets,
200
+ phrases=phrases,
201
+ base_rate=base_rate,
202
+ base_rate_note=base_rate_note,
203
+ )
204
+
205
+
206
+ def extract_code(text: str) -> str | None:
207
+ """Return the first ```python fenced block in ``text`` (or ``None``)."""
208
+ m = re.search(r"```(?:python|py)?\s*\n(.*?)```", text, re.DOTALL)
209
+ if not m:
210
+ return None
211
+ return m.group(1).strip() + "\n"
212
+
213
+
214
+ def model_name() -> str:
215
+ """``LANGBOT_LLM_MODEL`` or the default."""
216
+ return os.environ.get("LANGBOT_LLM_MODEL") or DEFAULT_MODEL
217
+
218
+
219
+ async def _call_model(thesis: str, model: str, base_rates: dict[str, Any] | None = None) -> str:
220
+ """Call Claude and return the raw assistant text (code block + explanation)."""
221
+ import anthropic
222
+
223
+ client = anthropic.AsyncAnthropic()
224
+ kwargs: dict[str, Any] = {}
225
+ effort = os.environ.get("LANGBOT_LLM_EFFORT", "high")
226
+ if effort and effort != "none":
227
+ kwargs["output_config"] = {"effort": effort}
228
+ prompt = f"Thesis:\n{thesis}{format_base_rates(base_rates)}"
229
+ async with client.messages.stream(
230
+ model=model,
231
+ max_tokens=16000,
232
+ system=SYSTEM_PROMPT,
233
+ messages=[{"role": "user", "content": prompt}],
234
+ **kwargs,
235
+ ) as stream:
236
+ message = await stream.get_final_message()
237
+ if message.stop_reason == "refusal":
238
+ detail = getattr(message, "stop_details", None)
239
+ raise RuntimeError(f"model declined: {getattr(detail, 'explanation', None) or 'refusal'}")
240
+ return "".join(block.text for block in message.content if block.type == "text")
241
+
242
+
243
+ async def draft_strategy(
244
+ thesis: str, model: str | None = None, base_rates: dict[str, Any] | None = None
245
+ ) -> dict[str, Any]:
246
+ """Draft a strategy file for ``thesis``.
247
+
248
+ ``base_rates`` (a ``GET /v1/history/base-rates`` payload) lets the draft price the
249
+ mention market off its historical YES rate instead of a fixed ceiling.
250
+
251
+ Returns ``{"code", "explanation", "model", "source": "llm"|"template", "note", "base_rates"}``.
252
+ """
253
+ thesis = thesis.strip()
254
+ if not thesis:
255
+ raise ValueError("thesis must not be empty")
256
+ model = model or model_name()
257
+ rate_hint = (
258
+ " The draft's `base_rate` is set from Langbot's history; tune `edge` to taste."
259
+ if base_rates and base_rates.get("yes_rate") is not None
260
+ else ""
261
+ )
262
+ if not os.environ.get("ANTHROPIC_API_KEY"):
263
+ note = "set ANTHROPIC_API_KEY to draft with Claude"
264
+ return {
265
+ "code": template_strategy(thesis, note, base_rates),
266
+ "explanation": (
267
+ "No ANTHROPIC_API_KEY is configured for the MCP server, so this is the default "
268
+ "template filled in from your thesis (a phrase trigger on mention markets, one "
269
+ "example market type). Edit `markets`, `phrases`, `max_price`, `edge` and "
270
+ "`count`, then replay it against recorded books with `langbot sim run -e "
271
+ "EVENT_ID -s file.py` before running it." + rate_hint
272
+ ),
273
+ "model": None,
274
+ "source": "template",
275
+ "note": note,
276
+ "base_rates": base_rates,
277
+ }
278
+ try:
279
+ text = await _call_model(thesis, model, base_rates)
280
+ except Exception as exc: # noqa: BLE001 - surface any SDK/API failure as a template
281
+ log.warning("draft_strategy fell back to template: %s", exc)
282
+ note = f"{type(exc).__name__}: {exc}"
283
+ return {
284
+ "code": template_strategy(thesis, note, base_rates),
285
+ "explanation": f"Claude call failed ({note}); returning the template instead.{rate_hint}",
286
+ "model": model,
287
+ "source": "template",
288
+ "note": note,
289
+ "base_rates": base_rates,
290
+ }
291
+ code = extract_code(text)
292
+ if code is None:
293
+ note = "model response had no python code block"
294
+ return {
295
+ "code": template_strategy(thesis, note, base_rates),
296
+ "explanation": text.strip()[:2000],
297
+ "model": model,
298
+ "source": "template",
299
+ "note": note,
300
+ "base_rates": base_rates,
301
+ }
302
+ explanation = re.sub(r"```.*?```", "", text, flags=re.DOTALL).strip()
303
+ return {
304
+ "code": code,
305
+ "explanation": explanation,
306
+ "model": model,
307
+ "source": "llm",
308
+ "note": None,
309
+ "base_rates": base_rates,
310
+ }
311
+
312
+
313
+ __all__ = [
314
+ "DEFAULT_MODEL",
315
+ "SYSTEM_PROMPT",
316
+ "draft_strategy",
317
+ "extract_code",
318
+ "format_base_rates",
319
+ "guess_markets_and_phrases",
320
+ "model_name",
321
+ "template_strategy",
322
+ ]