botsting 0.0.3__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.
Files changed (56) hide show
  1. botsting/__init__.py +3 -0
  2. botsting/__main__.py +8 -0
  3. botsting/attacks/__init__.py +0 -0
  4. botsting/attacks/adaptive.py +495 -0
  5. botsting/attacks/library.py +239 -0
  6. botsting/attacks/pyrit_adapter.py +227 -0
  7. botsting/attacks/strategy.py +157 -0
  8. botsting/authorize_cli.py +148 -0
  9. botsting/ci.py +122 -0
  10. botsting/cli.py +464 -0
  11. botsting/console.py +240 -0
  12. botsting/core/__init__.py +0 -0
  13. botsting/core/authorization.py +550 -0
  14. botsting/core/benchmark.py +199 -0
  15. botsting/core/canary.py +80 -0
  16. botsting/core/judge.py +175 -0
  17. botsting/core/matcher.py +367 -0
  18. botsting/core/meter.py +228 -0
  19. botsting/core/models.py +560 -0
  20. botsting/core/preflight.py +283 -0
  21. botsting/core/replay.py +145 -0
  22. botsting/core/runner.py +39 -0
  23. botsting/core/scan.py +917 -0
  24. botsting/core/stats.py +42 -0
  25. botsting/demo.py +215 -0
  26. botsting/doctor.py +271 -0
  27. botsting/egress_trap.py +243 -0
  28. botsting/exits.py +38 -0
  29. botsting/frameworks.py +453 -0
  30. botsting/harness.py +893 -0
  31. botsting/harness_tools.py +260 -0
  32. botsting/llm/__init__.py +0 -0
  33. botsting/llm/base.py +31 -0
  34. botsting/llm/ollama.py +165 -0
  35. botsting/llm/scripted.py +122 -0
  36. botsting/mcp_server.py +643 -0
  37. botsting/practice_server.py +190 -0
  38. botsting/presets.py +222 -0
  39. botsting/quick.py +485 -0
  40. botsting/report_html.py +588 -0
  41. botsting/report_markdown.py +472 -0
  42. botsting/reporting.py +73 -0
  43. botsting/seal.py +245 -0
  44. botsting/shell.py +40 -0
  45. botsting/sterility.py +407 -0
  46. botsting/targets/__init__.py +0 -0
  47. botsting/targets/base.py +207 -0
  48. botsting/targets/hardened.py +360 -0
  49. botsting/targets/http.py +826 -0
  50. botsting/targets/registry.py +96 -0
  51. botsting/targets/toy.py +310 -0
  52. botsting-0.0.3.dist-info/METADATA +495 -0
  53. botsting-0.0.3.dist-info/RECORD +56 -0
  54. botsting-0.0.3.dist-info/WHEEL +4 -0
  55. botsting-0.0.3.dist-info/entry_points.txt +2 -0
  56. botsting-0.0.3.dist-info/licenses/LICENSE +202 -0
botsting/mcp_server.py ADDED
@@ -0,0 +1,643 @@
1
+ """`botsting mcp`: let a developer's coding assistant set BotSting up and run it.
2
+
3
+ This is a Model Context Protocol server over standard input and output. A coding
4
+ assistant (Claude Code, Cursor and others) that is connected to it can:
5
+
6
+ setup_guide read how to wire a bot for testing, step by step
7
+ find_tools list functions in the project that look like risky tools
8
+ check_description check a target description and say what is wrong with it
9
+ authorization_status see whether a person has authorized testing an origin
10
+ doctor check the whole setup step by step and learn what to fix next
11
+ first_scan scan a bot that carries the drop-in harness, from its chat address alone
12
+ scan run a scan of a described target and get the result and where the reports are
13
+ read_report read a finished report
14
+
15
+ claude mcp add botsting -- botsting mcp
16
+
17
+ What it will not do
18
+ -------------------
19
+ It never creates or changes an authorization. Permission to test is a person taking
20
+ responsibility by name, so it is recorded by a person running `botsting authorize`
21
+ in a terminal. Without one, `scan` is refused for anything but the built-in practice
22
+ bots, exactly as on the command line. `first_scan` never asks anyone to type a name,
23
+ as the command does for a bot on the developer's own machine: an assistant is not a
24
+ person at a keyboard, so it sends nothing until that authorization is on record.
25
+
26
+ It never edits the project. `find_tools` and `check_description` only read; the
27
+ assistant proposes the changes and the developer approves them in their own editor.
28
+
29
+ It reads and writes only under the folder it was started in.
30
+
31
+ The protocol is small enough to implement with the standard library: JSON-RPC 2.0,
32
+ one message per line.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import ast
38
+ import contextlib
39
+ import io
40
+ import json
41
+ import os
42
+ import re
43
+ import sys
44
+ from collections.abc import Callable, Iterator
45
+ from pathlib import Path
46
+ from typing import Any, TextIO
47
+
48
+ from botsting import __version__
49
+ from botsting.exits import EXIT_OK
50
+
51
+ PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
52
+ _MAX_FILES = 2000
53
+ _MAX_FILE_BYTES = 400_000
54
+ _MAX_TEXT = 60_000
55
+ _MAX_REPORT_BYTES = 5_000_000
56
+ _SKIP_DIRS = {".git", ".venv", "venv", "node_modules", "__pycache__", "dist", "build", ".tox", "site-packages"}
57
+
58
+ GUIDE = """\
59
+ # Setting a bot up for BotSting
60
+
61
+ BotSting tests a bot its owner controls and reports only what is proven: a fake
62
+ secret it planted leaked, or a forbidden tool call was recorded at the tool. This
63
+ guide is the same for a developer and for a coding assistant working for one. An
64
+ assistant proposes each change as a diff for the developer to approve, and does not
65
+ scan anything but the built-in practice bots until the developer has recorded an
66
+ authorization themselves.
67
+
68
+ ## 1. Find the pieces
69
+ - The web app object and the chat endpoint (path, request body, where the reply is).
70
+ - How the bot knows who is talking (a header, a token, a field in the body).
71
+ - Every function that sends, pays, books, changes or deletes something. Call
72
+ `find_tools` for candidates, then read the code: the list is a starting point.
73
+ - Where the bot's instructions are built, and where it reads one user's data.
74
+
75
+ ## 2. Add the drop-in harness (Python here; for Node see js/harness/README.md in the BotSting repository)
76
+ ```python
77
+ import botsting.harness as pp
78
+
79
+ app = pp.wrap(app) # FastAPI/Starlette (ASGI) or Flask/Django (WSGI)
80
+
81
+ @pp.action("issue_refund") # on each risky function, after the app's own checks
82
+ def issue_refund(order_id: str, amount: float): ...
83
+
84
+ prompt = BASE_PROMPT + pp.planted("admin_code") # a secret in the instructions
85
+ note = pp.planted("bob_note", note) if user == "bob" else note # a secret in one user's data
86
+ ```
87
+ Rules:
88
+ - The library must be installed in the bot's own environment, with the bot's Python:
89
+ `pip install botsting`. Installing the `botsting` command does not do that.
90
+ - `pp.wrap(app)` goes last, after the routes, and the wrapped app is what the server runs.
91
+ A Flask or Quart app stays the same object, so `app.run()` still works and is wrapped.
92
+ - Put `@pp.action` on the function that does the deed, below the app's own permission
93
+ checks, so a call that reaches it means the app let it through.
94
+ - During a test a marked function is not run and returns a stand-in that reads as
95
+ {"status": "ok"} and as the text "ok". If the bot needs more from the answer, give
96
+ one: `@pp.action("issue_refund", result="Refunded.")`, or a function of the tool's own
97
+ arguments: `result=lambda order_id, amount: {"status": "ok", "refunded": amount}`.
98
+ - Call `pp.planted(...)` while a message is being handled. Each test conversation gets
99
+ its own fake secret, so instructions put together once, when the app starts, cannot
100
+ receive one; the scan then says secret leaks were not tested and names the slot.
101
+ - For a central tool registry, pass the complete list or mapping through
102
+ `botsting.harness_tools` and list only read-only tools in `reads`.
103
+ See "Cover every tool at once" in the README for framework examples.
104
+ - If the work is handed to a job queue or a thread the app starts itself, mark the
105
+ function that hands it over, not the worker.
106
+ - `pp.planted(slot, default)` returns the default for real users. Place it where a
107
+ real secret of that kind lives, and nowhere the attacker's own account can read.
108
+ - Nothing changes for requests without a signed BotSting session.
109
+
110
+ If the bot was built in Flowise, Dify or Langflow there is no code to add lines to. Ask the
111
+ developer to run `botsting init --preset <builder> --origin <url>` instead; it writes the
112
+ description and prints the one line to add to the bot's instructions. Skip to step 4.
113
+
114
+ ## 2b. The first scan needs no description
115
+ Once the lines above are in and the bot is running with the harness key set, the
116
+ developer runs `botsting scan http://localhost:8000/chat` (their chat address); an
117
+ assistant calls `first_scan` with that address, after the developer has authorized it. It
118
+ works out the request shape and the secrets the bot reads, asks the developer to type
119
+ their name to authorize a bot on their own machine, and saves the description it
120
+ worked out, under a name it prints (`http:quick-localhost-8000`). Where nobody can type
121
+ (a script, a pipeline, an assistant running the command) the developer first runs
122
+ `botsting authorize <origin> --by "NAME" --scope "..." --environment test --tool <each
123
+ tool marked never_for_users>` themselves; a tool the authorization does not name is left untested.
124
+ That first scan tests secrets held in the instructions, tools marked
125
+ `never_for_users="what an attacker would ask for"`, and text the bot reads from elsewhere at
126
+ each place the code reads with `pp.content("order_note", note)` (if the bot reads it only for
127
+ some requests, pass one as `message`, or `--message` on the command). Before any attack it checks that the
128
+ bot can say each secret at all: in one check conversation only, the harness adds a line
129
+ telling the bot to give the value to a user who states a pass phrase made for that scan.
130
+ The report says that route was supplied by the test. Steps 3 and 4 are for going further:
131
+ tools some users may use, other users' data, and bots across a network.
132
+
133
+ ## 3. Describe the bot in `botsting.targets.json`
134
+ ```json
135
+ {"targets": {"staging": {
136
+ "origin": "https://staging.example.com",
137
+ "harness": "sdk",
138
+ "chat": {"path": "/api/chat", "body": {"message": "{message}", "session_id": "{session}"}, "reply_pointer": "/reply"},
139
+ "attacker_principal": "customer:alice",
140
+ "principals": {
141
+ "customer:alice": {"headers": {"Authorization": "Bearer ${ALICE_TOKEN}"}},
142
+ "customer:bob": {"headers": {"Authorization": "Bearer ${BOB_TOKEN}"}},
143
+ "staff:dana": {"headers": {"Authorization": "Bearer ${DANA_TOKEN}"}}
144
+ },
145
+ "tool_safety": "sinks",
146
+ "slots": [
147
+ {"id": "admin_code", "kind": "instruction_secret", "description": "a staff code in the instructions",
148
+ "hint": "the staff code", "authorized": ["staff:dana"],
149
+ "control_principal": "staff:dana", "control_prompt": "What is the staff code?"},
150
+ {"id": "bob_note", "kind": "other_user_record", "canary_style": "name",
151
+ "description": "a note on Bob's order", "hint": "the note on Bob's order", "authorized": ["customer:bob"],
152
+ "control_principal": "customer:bob", "control_prompt": "What is the note on my order?"}
153
+ ],
154
+ "tool_rules": [
155
+ {"id": "refund_by_customer", "tool": "issue_refund", "description": "customers cannot issue refunds",
156
+ "hint": "a refund", "authorized": ["staff:dana"],
157
+ "control_principal": "staff:dana", "control_prompt": "Refund order A-1001 by 5."}
158
+ ],
159
+ "task_checks": [
160
+ {"id": "hello", "principal": "customer:alice", "prompt": "What are your opening hours?", "expect_substring": "open"}
161
+ ]
162
+ }}}
163
+ ```
164
+ - Use test accounts for every principal. Credentials are `${ENV_NAME}`, never written out.
165
+ - Each slot's `control_prompt` must make the bot give that secret to someone who is
166
+ allowed it; the scan checks this first, and is inconclusive if it fails.
167
+ - `canary_style: "name"` plants an invented name; use it where the bot would treat a
168
+ code-like value as a password and refuse to repeat it even to its owner.
169
+ - Call `check_description` until it reports no problems.
170
+
171
+ ## 4. The developer's own steps (you cannot do these for them)
172
+ ```
173
+ botsting harness-key # then set BOTSTING_HARNESS_KEY on staging and locally
174
+ botsting authorize https://staging.example.com --by "THEIR NAME" \\
175
+ --scope "the support bot on staging" --environment staging --tool issue_refund
176
+ # set BOTSTING_CHALLENGE on staging to the printed line, deploy, then:
177
+ botsting authorize --verify https://staging.example.com
178
+ botsting sterile-check --env-file staging.env # an export of staging's settings: no production keys
179
+ ```
180
+
181
+ ## 5. Check, then scan
182
+ Call `doctor` with target `http:staging` after each change: it says which step is not
183
+ passed yet and what fixes it. When it says "Ready", call `scan` with the same target. Read the result with `read_report`. Explain
184
+ each finding to the developer with its transcript, and propose a fix in the app's own
185
+ code (a permission check at the tool or data layer, not a sentence in the prompt).
186
+ Then scan again: a finding is fixed when its replay no longer works.
187
+
188
+ To see what a report looks like first, scan the practice bots `toy:vulnerable` and
189
+ `toy:fixed`. They run inside this process and need no permission.
190
+ """
191
+
192
+ _RISKY = re.compile(
193
+ r"(send|email|mail|sms|notify|post|publish|pay|charge|refund|transfer|withdraw|payout|invoice|book|cancel|"
194
+ r"delete|remove|drop|purge|update|write|create|insert|grant|revoke|reset|execute|run_|shell|deploy|order|purchase)",
195
+ re.IGNORECASE,
196
+ )
197
+ _TOOL_MARK = re.compile(r"tool|function_tool|action", re.IGNORECASE)
198
+
199
+
200
+ class ToolError(Exception):
201
+ """A problem to report to the assistant as the tool's result."""
202
+
203
+
204
+ def _inside(root: Path, value: str) -> Path:
205
+ path = (root / value).resolve()
206
+ if not path.is_relative_to(root.resolve()):
207
+ raise ToolError(f"{value!r} is outside the project folder; this server reads and writes only inside it")
208
+ return path
209
+
210
+
211
+ # -- the tools ------------------------------------------------------------------------------
212
+
213
+
214
+ def _setup_guide(root: Path, arguments: dict[str, Any]) -> str:
215
+ return GUIDE
216
+
217
+
218
+ def _decorator_names(node: ast.AST) -> list[str]:
219
+ names = []
220
+ for decorator in getattr(node, "decorator_list", []):
221
+ target = decorator.func if isinstance(decorator, ast.Call) else decorator
222
+ names.append(ast.unparse(target))
223
+ return names
224
+
225
+
226
+ def _python_files(start: Path) -> Iterator[Path]:
227
+ """Python files under `start`, in order, without entering skipped folders or following links."""
228
+ for folder, folders, files in os.walk(start, followlinks=False):
229
+ folders[:] = sorted(d for d in folders if d not in _SKIP_DIRS and not Path(folder, d).is_symlink())
230
+ for name in sorted(files):
231
+ if name.endswith(".py"):
232
+ yield Path(folder, name)
233
+
234
+
235
+ def _find_tools(root: Path, arguments: dict[str, Any]) -> str:
236
+ start = _inside(root, str(arguments.get("path", ".")))
237
+ if not start.exists():
238
+ raise ToolError(f"{start} does not exist")
239
+ found: list[str] = []
240
+ marked = 0
241
+ read = 0
242
+ for file in [start] if start.is_file() else _python_files(start):
243
+ if not file.resolve().is_relative_to(root.resolve()):
244
+ continue # reached through a link that leads out of the project
245
+ if read >= _MAX_FILES:
246
+ found.append(f"(stopped after {_MAX_FILES} files; give a narrower path)")
247
+ break
248
+ read += 1
249
+ try:
250
+ if file.stat().st_size > _MAX_FILE_BYTES:
251
+ continue
252
+ tree = ast.parse(file.read_text(encoding="utf-8"))
253
+ except (OSError, SyntaxError, ValueError):
254
+ continue
255
+ for node in ast.walk(tree):
256
+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
257
+ continue
258
+ decorators = _decorator_names(node)
259
+ if any(name == "action" or name.endswith(".action") for name in decorators):
260
+ marked += 1
261
+ continue
262
+ reasons = []
263
+ if any(_TOOL_MARK.search(name) for name in decorators):
264
+ reasons.append("registered as a tool (@" + ", @".join(decorators) + ")")
265
+ if _RISKY.search(node.name):
266
+ reasons.append("its name suggests it changes something")
267
+ if reasons:
268
+ where = file.resolve().relative_to(root.resolve()).as_posix()
269
+ arguments_text = ", ".join(a.arg for a in node.args.args if a.arg not in ("self", "cls"))
270
+ found.append(f"{where}:{node.lineno} {node.name}({arguments_text}) - {'; '.join(reasons)}")
271
+ lines = [
272
+ f"Read {read} Python file(s). {marked} function(s) already carry @pp.action.",
273
+ f"{len(found)} candidate(s) that may need @pp.action. Read each one before deciding: a function that only",
274
+ "reads, or that the bot can never reach, does not need it; one that this list missed still does.",
275
+ "",
276
+ *found[:300],
277
+ ]
278
+ return "\n".join(lines)
279
+
280
+
281
+ def _check_description(root: Path, arguments: dict[str, Any]) -> str:
282
+ from botsting.targets.http import TargetConfigError, parse_config
283
+
284
+ path = _inside(root, str(arguments.get("file", "botsting.targets.json")))
285
+ try:
286
+ data = json.loads(path.read_text(encoding="utf-8"))
287
+ except (OSError, ValueError) as error:
288
+ raise ToolError(f"could not read {path.name}: {error}") from error
289
+ targets = data.get("targets") if isinstance(data, dict) else None
290
+ if not isinstance(targets, dict) or not targets:
291
+ raise ToolError(f'{path.name} must look like {{"targets": {{"<name>": {{...}}}}}}')
292
+ wanted = arguments.get("name")
293
+ names = [str(wanted)] if wanted else sorted(targets)
294
+ lines = []
295
+ for name in names:
296
+ if name not in targets:
297
+ lines.append(f"{name}: not in the file (it has: {', '.join(sorted(targets))})")
298
+ continue
299
+ try:
300
+ config = parse_config(name, targets[name])
301
+ except TargetConfigError as error:
302
+ lines.append(f"{name}: PROBLEM: {error}")
303
+ continue
304
+ notes = []
305
+ if not config.slots and not config.tool_rules:
306
+ notes.append("it protects nothing: add at least one slot or tool rule, or a scan has nothing to prove")
307
+ if config.harness == "endpoint":
308
+ notes.append('it uses a hand-written reset endpoint; "harness": "sdk" needs less code in the bot')
309
+ if not config.task_checks:
310
+ notes.append("no task_checks: add one normal request, so a bot that refuses everything is not called safe")
311
+ if any(v for p in targets[name].get("principals", {}).values() for v in p.get("headers", {}).values() if "${" not in v):
312
+ notes.append("a header value is written out; use ${ENV_NAME} so no credential is in the file")
313
+ summary = (
314
+ f"{name}: OK. origin {config.origin}, {len(config.slots)} secret slot(s), {len(config.tool_rules)} tool rule(s), "
315
+ f"{len(config.injection_points)} injection point(s), {len(config.task_checks)} normal-use check(s)."
316
+ )
317
+ lines.append(summary + "".join(f"\n note: {note}" for note in notes))
318
+ return "\n".join(lines)
319
+
320
+
321
+ def _authorization_status(root: Path, arguments: dict[str, Any]) -> str:
322
+ from datetime import UTC, datetime
323
+
324
+ from botsting.core.authorization import AuthorizationError, AuthorizationStore
325
+
326
+ origin = str(arguments.get("origin", ""))
327
+ how = (
328
+ "Only a person can authorize a test. Ask the developer to run this in their terminal:\n"
329
+ f' botsting authorize {origin or "<origin>"} --by "THEIR NAME" --scope "what may be tested" '
330
+ "--environment staging --tool <each tool>"
331
+ )
332
+ try:
333
+ record = AuthorizationStore(_inside(root, "botsting.authorizations.json")).find(origin)
334
+ except (AuthorizationError, ValueError) as error:
335
+ raise ToolError(f"{error}\n{how}") from error
336
+ if record is None:
337
+ return f"No authorization on record for {origin}.\n{how}"
338
+ if record.expired(datetime.now(UTC)):
339
+ return f"The authorization for {record.origin} expired at {record.expires_at}.\n{how}"
340
+ state = "ready"
341
+ if record.needs_proof and not record.verified_at:
342
+ state = f"not verified yet: the developer must run `botsting authorize --verify {record.origin}`"
343
+ return (
344
+ f"{record.origin}: {state}. Authorized by {record.authorized_by} for {record.environment}, until {record.expires_at}.\n"
345
+ f"Scope: {record.scope}\nTools that may be exercised: {', '.join(record.allowed_tools) or 'none'}\n"
346
+ f"Tools that may be carried out for real, under caps: {', '.join(record.live_tools) or 'none'}"
347
+ )
348
+
349
+
350
+ def _doctor(root: Path, arguments: dict[str, Any]) -> str:
351
+ from botsting.doctor import diagnose
352
+
353
+ target = str(arguments.get("target", ""))
354
+ if not target:
355
+ raise ToolError("give a target, for example http:staging")
356
+ lines: list[str] = []
357
+ diagnose(target, offline=bool(arguments.get("offline", False)), out=lines.append)
358
+ return "\n".join(lines)
359
+
360
+
361
+ def _first_scan(root: Path, arguments: dict[str, Any]) -> str:
362
+ """`botsting scan URL` for an assistant: work the description out from the harness, save it, scan."""
363
+ from botsting.practice_server import write_description
364
+ from botsting.quick import QuickError, _keep_earlier, discover
365
+ from botsting.targets.http import targets_file
366
+
367
+ url = str(arguments.get("url", ""))
368
+ if not url:
369
+ raise ToolError("give the bot's chat address, for example http://localhost:8000/chat")
370
+ directory = str(arguments.get("dir", "botsting-report"))
371
+ _inside(root, directory)
372
+ path = targets_file()
373
+ if not path.resolve().is_relative_to(root.resolve()):
374
+ raise ToolError("the targets file is outside the project folder; this server reads and writes only inside it")
375
+
376
+ def given(key: str) -> str | None:
377
+ return str(arguments[key]) if arguments.get(key) not in (None, "") else None
378
+
379
+ said: list[str] = []
380
+ try:
381
+ # Nobody is asked to type a name here: an authorization is a person's act, made in their own terminal.
382
+ name, description, notes = discover(
383
+ url, given("name"), given("field"), given("session_field"), given("reply"),
384
+ ask_name=lambda origin: "", say=said.append, message=given("message"),
385
+ ) # fmt: skip
386
+ except QuickError as error:
387
+ raise ToolError("\n".join([*said, f"Not scanned: {error}"])) from error
388
+ kept = _keep_earlier(path, name, description)
389
+ if kept is not None:
390
+ said.append(f"The description saved earlier as http:{name} differed; it was kept as {kept.name}.")
391
+ write_description(path, name, description)
392
+ said.append(f"Saved what was worked out as target http:{name} in {path.name}.")
393
+ result = _scan(root, {**{k: v for k, v in arguments.items() if k in _SCAN_OPTIONS}, "target": f"http:{name}", "dir": directory})
394
+ return "\n".join([*said, "", result, *(["", *notes] if notes else [])])
395
+
396
+
397
+ _SCAN_OPTIONS = ("strategy", "replays", "max_seconds", "max_messages")
398
+
399
+
400
+ def _scan(root: Path, arguments: dict[str, Any]) -> str:
401
+ from botsting.cli import main
402
+
403
+ target = str(arguments.get("target", ""))
404
+ if not target:
405
+ raise ToolError("give a target, for example toy:vulnerable or http:staging")
406
+ directory = str(arguments.get("dir", "botsting-report"))
407
+ _inside(root, directory)
408
+ argv = ["ci", "--target", target, "--dir", directory, "--fail-on", "never"]
409
+ argv += ["--strategy", str(arguments.get("strategy", "static"))]
410
+ argv += ["--replays", str(int(arguments.get("replays", 3)))]
411
+ argv += ["--max-seconds", str(float(arguments.get("max_seconds", 600)))]
412
+ argv += ["--max-messages", str(int(arguments.get("max_messages", 1000)))]
413
+ before = _inside(root, directory) / "scan.botsting.json"
414
+ existed = before.exists()
415
+ try:
416
+ main(argv)
417
+ except SystemExit as error: # argparse refusing an option
418
+ raise ToolError(f"the scan options were not accepted (exit {error.code})") from error
419
+ if existed or not before.exists():
420
+ # What the command printed (captured by the caller) says why. Do not claim reports that were not written.
421
+ raise ToolError("The scan did not run, so no report was written. The lines above say why.")
422
+ return f"Reports are in {directory}/ (report.md, report.html, scan.botsting.json). Use read_report to read one."
423
+
424
+
425
+ def _read_report(root: Path, arguments: dict[str, Any]) -> str:
426
+ path = _inside(root, str(arguments.get("path", "botsting-report/report.md")))
427
+ if path.suffix not in (".md", ".json"):
428
+ raise ToolError("read_report reads .md and .json reports")
429
+ try:
430
+ if path.stat().st_size > _MAX_REPORT_BYTES:
431
+ raise ToolError(f"{path.name} is larger than {_MAX_REPORT_BYTES} bytes; open it in an editor instead")
432
+ text = path.read_text(encoding="utf-8")
433
+ except (OSError, ValueError) as error:
434
+ raise ToolError(f"could not read {path.name}: {error}") from error
435
+ return text
436
+
437
+
438
+ def _text_schema(properties: dict[str, Any], required: list[str] | None = None) -> dict[str, Any]:
439
+ return {"type": "object", "properties": properties, "required": required or [], "additionalProperties": False}
440
+
441
+
442
+ TOOLS: dict[str, tuple[str, dict[str, Any], Callable[[Path, dict[str, Any]], str]]] = {
443
+ "setup_guide": (
444
+ "How to wire the developer's own bot for BotSting, step by step. Read this first.",
445
+ _text_schema({}),
446
+ _setup_guide,
447
+ ),
448
+ "find_tools": (
449
+ "List Python functions in the project that look like risky tools (they send, pay, book, change or delete), "
450
+ "as candidates for @pp.action. Read-only.",
451
+ _text_schema({"path": {"type": "string", "description": "A folder or file inside the project. Default: the project."}}),
452
+ _find_tools,
453
+ ),
454
+ "check_description": (
455
+ "Check a target description in botsting.targets.json and say exactly what is wrong. Read-only.",
456
+ _text_schema({
457
+ "file": {"type": "string", "description": "Default: botsting.targets.json"},
458
+ "name": {"type": "string", "description": "One target; default: all of them"},
459
+ }),
460
+ _check_description,
461
+ ),
462
+ "authorization_status": (
463
+ "Say whether a person has authorized testing this origin. This server cannot create an authorization.",
464
+ _text_schema({"origin": {"type": "string", "description": "For example https://staging.example.com"}}, ["origin"]),
465
+ _authorization_status,
466
+ ),
467
+ "doctor": (
468
+ "Check a target's setup step by step (description, credentials, key, authorization, proof of control, the "
469
+ "harness, legitimate use) and say what to fix next. Sends nothing hostile, and nothing at all without an "
470
+ "authorization.",
471
+ _text_schema(
472
+ {
473
+ "target": {"type": "string", "description": "For example http:staging"},
474
+ "offline": {"type": "boolean", "description": "Only checks that need no contact with the bot"},
475
+ },
476
+ ["target"],
477
+ ),
478
+ _doctor,
479
+ ),
480
+ "first_scan": (
481
+ "Scan the developer's own bot from its chat address alone, once the drop-in harness lines are in the bot and it "
482
+ "is running with the harness key set. Works out the request shape, the secrets the bot reads and the tools "
483
+ "marked never_for_users, saves that as a target, scans, and writes the reports. Refused, with the command the "
484
+ "developer must run themselves, until a person has recorded an authorization for that address.",
485
+ _text_schema(
486
+ {
487
+ "url": {"type": "string", "description": "The chat address, for example http://localhost:8000/chat"},
488
+ "dir": {"type": "string", "description": "A new or empty folder for the reports. Default: botsting-report"},
489
+ "name": {"type": "string", "description": "The name to save the description under. Default: made from the address"},
490
+ "field": {"type": "string", "description": "The request field that carries the message, if it is not found"},
491
+ "session_field": {"type": "string", "description": "A request field for the conversation id, if the bot has one"},
492
+ "reply": {"type": "string", "description": "A JSON pointer to the reply text, such as /data/answer"},
493
+ "message": {
494
+ "type": "string",
495
+ "description": 'An ordinary request to send while working the bot out. Default "Hello". Give one '
496
+ "that makes the bot read its notes or documents, so planted text there is tested",
497
+ },
498
+ "strategy": {"type": "string", "enum": ["static", "adaptive", "both"]},
499
+ "replays": {"type": "integer", "minimum": 1, "maximum": 20},
500
+ "max_seconds": {"type": "number", "minimum": 1, "maximum": 3600},
501
+ "max_messages": {"type": "integer", "minimum": 1, "maximum": 5000},
502
+ },
503
+ ["url"],
504
+ ),
505
+ _first_scan,
506
+ ),
507
+ "scan": (
508
+ "Run a scan and write the reports. Practice bots (toy:vulnerable, toy:fixed) need no permission; any other "
509
+ "target is refused unless a person has recorded an authorization for it.",
510
+ _text_schema(
511
+ {
512
+ "target": {"type": "string", "description": "For example toy:vulnerable or http:staging"},
513
+ "dir": {"type": "string", "description": "A new or empty folder for the reports. Default: botsting-report"},
514
+ "strategy": {"type": "string", "enum": ["static", "adaptive", "both"]},
515
+ "replays": {"type": "integer", "minimum": 1, "maximum": 20},
516
+ "max_seconds": {"type": "number", "minimum": 1, "maximum": 3600},
517
+ "max_messages": {"type": "integer", "minimum": 1, "maximum": 5000},
518
+ },
519
+ ["target"],
520
+ ),
521
+ _scan,
522
+ ),
523
+ "read_report": (
524
+ "Read a finished report (.md or .json) from the project folder.",
525
+ _text_schema({"path": {"type": "string", "description": "Default: botsting-report/report.md"}}),
526
+ _read_report,
527
+ ),
528
+ }
529
+
530
+
531
+ def _note(title: str, reads_only: bool, reaches_out: bool) -> dict[str, Any]:
532
+ """What an assistant, and a directory that lists this server, may assume about a tool.
533
+
534
+ None of the tools deletes or overwrites anything: a scan writes into a new or empty folder
535
+ and refuses one that holds files. `reaches_out` is true for the tools that send messages to
536
+ the developer's bot."""
537
+ return {"title": title, "readOnlyHint": reads_only, "destructiveHint": False, "openWorldHint": reaches_out}
538
+
539
+
540
+ ANNOTATIONS: dict[str, dict[str, Any]] = {
541
+ "setup_guide": _note("Read the setup guide", True, False),
542
+ "find_tools": _note("Find risky functions in the project", True, False),
543
+ "check_description": _note("Check a target description", True, False),
544
+ "authorization_status": _note("See whether a test is authorized", True, False),
545
+ "doctor": _note("Check the setup step by step", False, True),
546
+ "first_scan": _note("Scan a bot from its chat address", False, True),
547
+ "scan": _note("Scan a described bot", False, True),
548
+ "read_report": _note("Read a finished report", True, False),
549
+ }
550
+
551
+
552
+ # -- the protocol ---------------------------------------------------------------------------
553
+
554
+
555
+ def _call(root: Path, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
556
+ if name not in TOOLS:
557
+ return {"content": [{"type": "text", "text": f"unknown tool {name!r}"}], "isError": True}
558
+ captured = io.StringIO()
559
+ failed = False
560
+ try:
561
+ # Standard output is the protocol's channel: nothing a tool prints may reach it.
562
+ with contextlib.redirect_stdout(captured), contextlib.redirect_stderr(captured):
563
+ text = TOOLS[name][2](root, arguments)
564
+ except ToolError as error:
565
+ text, failed = str(error), True
566
+ except Exception as error:
567
+ text, failed = f"{type(error).__name__}: {error}", True
568
+ printed = captured.getvalue().strip()
569
+ if printed:
570
+ text = printed + "\n\n" + text
571
+ if len(text) > _MAX_TEXT:
572
+ text = text[:_MAX_TEXT] + f"\n\n(cut at {_MAX_TEXT} characters)"
573
+ return {"content": [{"type": "text", "text": text}], "isError": failed}
574
+
575
+
576
+ def handle(root: Path, message: Any) -> dict[str, Any] | None:
577
+ """Answer one JSON-RPC message. Returns None for a notification."""
578
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
579
+ return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "not a JSON-RPC 2.0 request"}}
580
+ if "id" not in message:
581
+ return None
582
+ identifier, method = message["id"], message["method"]
583
+ params = message.get("params") if isinstance(message.get("params"), dict) else {}
584
+
585
+ def answer(result: Any) -> dict[str, Any]:
586
+ return {"jsonrpc": "2.0", "id": identifier, "result": result}
587
+
588
+ if method == "initialize":
589
+ asked = params.get("protocolVersion")
590
+ return answer(
591
+ {
592
+ "protocolVersion": asked if asked in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0],
593
+ "capabilities": {"tools": {}},
594
+ "serverInfo": {"name": "botsting", "version": __version__},
595
+ "instructions": "Call setup_guide first. Only the developer can authorize a test; never do it for them.",
596
+ }
597
+ )
598
+ if method == "ping":
599
+ return answer({})
600
+ if method == "tools/list":
601
+ return answer(
602
+ {
603
+ "tools": [
604
+ {"name": n, "description": d, "inputSchema": schema, "annotations": ANNOTATIONS[n]}
605
+ for n, (d, schema, _) in TOOLS.items()
606
+ ]
607
+ }
608
+ )
609
+ if method == "tools/call":
610
+ arguments = params.get("arguments")
611
+ return answer(_call(root, str(params.get("name")), arguments if isinstance(arguments, dict) else {}))
612
+ return {"jsonrpc": "2.0", "id": identifier, "error": {"code": -32601, "message": f"unknown method {method}"}}
613
+
614
+
615
+ def serve(root: Path, incoming: TextIO, outgoing: TextIO) -> None:
616
+ for line in incoming:
617
+ if not line.strip():
618
+ continue
619
+ try:
620
+ message = json.loads(line)
621
+ except ValueError:
622
+ reply: dict[str, Any] | None = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "not JSON"}}
623
+ else:
624
+ reply = handle(root, message)
625
+ if reply is not None:
626
+ outgoing.write(json.dumps(reply, separators=(",", ":")) + "\n")
627
+ outgoing.flush()
628
+
629
+
630
+ def register(commands: Any) -> None:
631
+ parser = commands.add_parser("mcp", help="serve BotSting to a coding assistant (Model Context Protocol, stdio)")
632
+ parser.set_defaults(handler=_serve_command)
633
+ guide = commands.add_parser("guide", help="print how to wire a bot for testing")
634
+ guide.set_defaults(handler=lambda args: print(GUIDE) or 0)
635
+
636
+
637
+ def _serve_command(args: Any) -> int:
638
+ # The real streams are captured here, before any tool redirects standard output.
639
+ for stream in (sys.stdin, sys.stdout):
640
+ if hasattr(stream, "reconfigure"):
641
+ stream.reconfigure(encoding="utf-8", newline="\n")
642
+ serve(Path.cwd(), sys.stdin, sys.stdout)
643
+ return EXIT_OK