warlockcode-wartools-ai 0.1.1__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.
- warlockcode_wartools_ai/__init__.py +21 -0
- warlockcode_wartools_ai/_generated/__init__.py +1 -0
- warlockcode_wartools_ai/_generated/shared_data.py +5 -0
- warlockcode_wartools_ai/_lib/__init__.py +0 -0
- warlockcode_wartools_ai/_lib/canonical.py +96 -0
- warlockcode_wartools_ai/_lib/common.py +54 -0
- warlockcode_wartools_ai/_lib/errors.py +9 -0
- warlockcode_wartools_ai/_lib/html.py +32 -0
- warlockcode_wartools_ai/_lib/net.py +132 -0
- warlockcode_wartools_ai/_lib/patchapply.py +144 -0
- warlockcode_wartools_ai/_lib/sandbox.py +42 -0
- warlockcode_wartools_ai/_lib/textkit.py +59 -0
- warlockcode_wartools_ai/_lib/timekit.py +59 -0
- warlockcode_wartools_ai/_lib/udiff.py +117 -0
- warlockcode_wartools_ai/_lib/unicode.py +93 -0
- warlockcode_wartools_ai/handlers/__init__.py +43 -0
- warlockcode_wartools_ai/handlers/catalog.py +27 -0
- warlockcode_wartools_ai/handlers/context.py +35 -0
- warlockcode_wartools_ai/handlers/crypto.py +61 -0
- warlockcode_wartools_ai/handlers/csv.py +132 -0
- warlockcode_wartools_ai/handlers/doc.py +77 -0
- warlockcode_wartools_ai/handlers/doc_detect.py +55 -0
- warlockcode_wartools_ai/handlers/encoding.py +57 -0
- warlockcode_wartools_ai/handlers/fs.py +110 -0
- warlockcode_wartools_ai/handlers/json.py +220 -0
- warlockcode_wartools_ai/handlers/kv.py +103 -0
- warlockcode_wartools_ai/handlers/math.py +223 -0
- warlockcode_wartools_ai/handlers/scratchpad.py +82 -0
- warlockcode_wartools_ai/handlers/security.py +50 -0
- warlockcode_wartools_ai/handlers/state.py +40 -0
- warlockcode_wartools_ai/handlers/text.py +183 -0
- warlockcode_wartools_ai/handlers/text_patch.py +24 -0
- warlockcode_wartools_ai/handlers/text_rerank.py +50 -0
- warlockcode_wartools_ai/handlers/time.py +103 -0
- warlockcode_wartools_ai/handlers/time_business.py +109 -0
- warlockcode_wartools_ai/handlers/trace.py +33 -0
- warlockcode_wartools_ai/handlers/validate.py +58 -0
- warlockcode_wartools_ai/handlers/web.py +81 -0
- warlockcode_wartools_ai/mcp.py +106 -0
- warlockcode_wartools_ai/models.py +118 -0
- warlockcode_wartools_ai/py.typed +0 -0
- warlockcode_wartools_ai/registry.py +196 -0
- warlockcode_wartools_ai/runtime/__init__.py +4 -0
- warlockcode_wartools_ai/runtime/pipeline.py +149 -0
- warlockcode_wartools_ai/runtime/policy_store.py +63 -0
- warlockcode_wartools_ai/stores.py +267 -0
- warlockcode_wartools_ai/tools.py +66 -0
- warlockcode_wartools_ai-0.1.1.dist-info/METADATA +34 -0
- warlockcode_wartools_ai-0.1.1.dist-info/RECORD +52 -0
- warlockcode_wartools_ai-0.1.1.dist-info/WHEEL +5 -0
- warlockcode_wartools_ai-0.1.1.dist-info/entry_points.txt +2 -0
- warlockcode_wartools_ai-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from datetime import datetime, timedelta, timezone
|
|
5
|
+
from typing import Any, Dict
|
|
6
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
7
|
+
|
|
8
|
+
from .._lib.common import clean_number, format_in_timezone, parse_iso_datetime
|
|
9
|
+
from .._lib.errors import ToolExecutionError
|
|
10
|
+
from .context import Handler, ToolContext
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def time_now(ctx: ToolContext) -> Any:
|
|
14
|
+
inp = ctx.input
|
|
15
|
+
tz = inp.get("timezone") if isinstance(inp.get("timezone"), str) and inp.get("timezone") else "UTC"
|
|
16
|
+
now = datetime.now(timezone.utc)
|
|
17
|
+
fmt = format_in_timezone(now, tz)
|
|
18
|
+
return {
|
|
19
|
+
"iso": fmt["iso"],
|
|
20
|
+
"unixMs": int(now.timestamp() * 1000),
|
|
21
|
+
"date": fmt["date"],
|
|
22
|
+
"time": fmt["time"],
|
|
23
|
+
"weekday": fmt["weekday"],
|
|
24
|
+
"timezone": tz,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def time_diff(ctx: ToolContext) -> Any:
|
|
29
|
+
inp = ctx.input
|
|
30
|
+
start_dt = parse_iso_datetime(str(inp.get("start") or ""))
|
|
31
|
+
end_dt = parse_iso_datetime(str(inp.get("end") or ""))
|
|
32
|
+
diff_sec_float = (end_dt - start_dt).total_seconds()
|
|
33
|
+
total_seconds = round(diff_sec_float)
|
|
34
|
+
total_hours = clean_number(round(diff_sec_float / 3600.0, 4))
|
|
35
|
+
total_days = clean_number(round(diff_sec_float / 86400.0, 4))
|
|
36
|
+
abs_sec = abs(total_seconds)
|
|
37
|
+
d, rem = divmod(abs_sec, 86400)
|
|
38
|
+
h, rem = divmod(rem, 3600)
|
|
39
|
+
m, s = divmod(rem, 60)
|
|
40
|
+
sign = "-" if total_seconds < 0 else ""
|
|
41
|
+
return {
|
|
42
|
+
"totalSeconds": total_seconds,
|
|
43
|
+
"totalHours": total_hours,
|
|
44
|
+
"totalDays": total_days,
|
|
45
|
+
"humanReadable": f"{sign}{d}d {h}h {m}m {s}s",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def time_add(ctx: ToolContext) -> Any:
|
|
50
|
+
inp = ctx.input
|
|
51
|
+
try:
|
|
52
|
+
amount = int(inp.get("amount")) # type: ignore[arg-type]
|
|
53
|
+
except Exception:
|
|
54
|
+
raise ToolExecutionError("INVALID_INPUT", "amount must be a number.")
|
|
55
|
+
unit = str(inp.get("unit") or "")
|
|
56
|
+
base = parse_iso_datetime(str(inp["baseDate"])) if inp.get("baseDate") else datetime.now(timezone.utc)
|
|
57
|
+
if unit == "minutes":
|
|
58
|
+
result = base + timedelta(minutes=amount)
|
|
59
|
+
elif unit == "hours":
|
|
60
|
+
result = base + timedelta(hours=amount)
|
|
61
|
+
elif unit == "days":
|
|
62
|
+
result = base + timedelta(days=amount)
|
|
63
|
+
elif unit == "weeks":
|
|
64
|
+
result = base + timedelta(weeks=amount)
|
|
65
|
+
elif unit == "months":
|
|
66
|
+
month = base.month - 1 + amount
|
|
67
|
+
year = base.year + month // 12
|
|
68
|
+
month = month % 12 + 1
|
|
69
|
+
day = min(base.day, 28)
|
|
70
|
+
result = base.replace(year=year, month=month, day=day)
|
|
71
|
+
else:
|
|
72
|
+
raise ToolExecutionError("INVALID_INPUT", "unit must be minutes, hours, days, weeks, or months.")
|
|
73
|
+
tz = inp.get("timezone") if isinstance(inp.get("timezone"), str) and inp.get("timezone") else "UTC"
|
|
74
|
+
fmt = format_in_timezone(result, tz)
|
|
75
|
+
return {"resultIso": fmt["iso"], "resultDate": fmt["date"], "weekday": fmt["weekday"]}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def time_convert_tz(ctx: ToolContext) -> Any:
|
|
79
|
+
inp = ctx.input
|
|
80
|
+
dt_raw = str(inp.get("dateTime") or "")
|
|
81
|
+
from_tz = str(inp.get("fromTimezone") or "UTC")
|
|
82
|
+
to_tz = str(inp.get("toTimezone") or "UTC")
|
|
83
|
+
if not dt_raw:
|
|
84
|
+
raise ToolExecutionError("INVALID_INPUT", "dateTime is required.")
|
|
85
|
+
if re.search(r"([Zz]|[+-]\d{2}:?\d{2})$", dt_raw):
|
|
86
|
+
instant = parse_iso_datetime(dt_raw)
|
|
87
|
+
else:
|
|
88
|
+
naive = datetime.fromisoformat(dt_raw.replace(" ", "T"))
|
|
89
|
+
try:
|
|
90
|
+
instant = naive.replace(tzinfo=ZoneInfo(from_tz))
|
|
91
|
+
except ZoneInfoNotFoundError:
|
|
92
|
+
raise ToolExecutionError("INVALID_TIMEZONE", f'Unknown IANA timezone "{from_tz}".')
|
|
93
|
+
from_info = format_in_timezone(instant, from_tz)
|
|
94
|
+
to_info = format_in_timezone(instant, to_tz)
|
|
95
|
+
return {"convertedIso": to_info["iso"], "offsetChange": f"{from_info['offsetIso']} -> {to_info['offsetIso']}"}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
HANDLERS: Dict[str, Handler] = {
|
|
99
|
+
"time.now": time_now,
|
|
100
|
+
"time.diff": time_diff,
|
|
101
|
+
"time.add": time_add,
|
|
102
|
+
"time.convert_tz": time_convert_tz,
|
|
103
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
|
|
5
|
+
from .._lib.errors import ToolExecutionError
|
|
6
|
+
from .._lib.timekit import format_iso_date, parse_iso_date, weekday_iso
|
|
7
|
+
|
|
8
|
+
MAX_SPAN_DAYS = 36500
|
|
9
|
+
MAX_ADD = 10000
|
|
10
|
+
MAX_HOLIDAYS = 1000
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _bad(msg: str) -> ToolExecutionError:
|
|
14
|
+
return ToolExecutionError("INVALID_INPUT", msg)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _date_arg(v: Any, name: str) -> int:
|
|
18
|
+
if not isinstance(v, str):
|
|
19
|
+
raise _bad(f"{name} must be a YYYY-MM-DD string.")
|
|
20
|
+
d = parse_iso_date(v)
|
|
21
|
+
if d is None:
|
|
22
|
+
raise _bad(f"{name} must be a valid YYYY-MM-DD date.")
|
|
23
|
+
return d
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _is_int(v: Any) -> bool:
|
|
27
|
+
if isinstance(v, bool):
|
|
28
|
+
return False
|
|
29
|
+
if isinstance(v, int):
|
|
30
|
+
return True
|
|
31
|
+
return isinstance(v, float) and v == int(v)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def business_days(ctx: Any) -> Dict[str, Any]:
|
|
35
|
+
inp = ctx.input
|
|
36
|
+
start = _date_arg(inp.get("start"), "start")
|
|
37
|
+
has_end = inp.get("end") is not None
|
|
38
|
+
has_add = inp.get("add") is not None
|
|
39
|
+
if has_end == has_add:
|
|
40
|
+
raise _bad("Provide exactly one of end or add.")
|
|
41
|
+
|
|
42
|
+
weekend = {6, 7}
|
|
43
|
+
if inp.get("weekend") is not None:
|
|
44
|
+
raw = inp["weekend"]
|
|
45
|
+
if not isinstance(raw, list):
|
|
46
|
+
raise _bad("weekend must be an array of ISO weekdays 1-7.")
|
|
47
|
+
weekend = set()
|
|
48
|
+
for w in raw:
|
|
49
|
+
if not _is_int(w) or int(w) < 1 or int(w) > 7:
|
|
50
|
+
raise _bad("weekend must contain integers 1-7.")
|
|
51
|
+
weekend.add(int(w))
|
|
52
|
+
if len(weekend) >= 7:
|
|
53
|
+
raise _bad("weekend cannot cover every weekday.")
|
|
54
|
+
holidays = set()
|
|
55
|
+
if inp.get("holidays") is not None:
|
|
56
|
+
hs = inp["holidays"]
|
|
57
|
+
if not isinstance(hs, list):
|
|
58
|
+
raise _bad("holidays must be an array of YYYY-MM-DD strings.")
|
|
59
|
+
if len(hs) > MAX_HOLIDAYS:
|
|
60
|
+
raise _bad(f"holidays supports at most {MAX_HOLIDAYS} entries.")
|
|
61
|
+
for i, h in enumerate(hs):
|
|
62
|
+
holidays.add(_date_arg(h, f"holidays[{i}]"))
|
|
63
|
+
|
|
64
|
+
def is_business(d: int) -> bool:
|
|
65
|
+
return weekday_iso(d) not in weekend and d not in holidays
|
|
66
|
+
|
|
67
|
+
if has_end:
|
|
68
|
+
end = _date_arg(inp.get("end"), "end")
|
|
69
|
+
if "inclusive" in inp and inp["inclusive"] is not None and not isinstance(inp["inclusive"], bool):
|
|
70
|
+
raise _bad("inclusive must be a boolean.")
|
|
71
|
+
inclusive = inp.get("inclusive") is True
|
|
72
|
+
if abs(end - start) > MAX_SPAN_DAYS:
|
|
73
|
+
raise _bad(f"Range exceeds {MAX_SPAN_DAYS} days.")
|
|
74
|
+
lo, hi = min(start, end), max(start, end)
|
|
75
|
+
last = hi if inclusive else hi - 1
|
|
76
|
+
count = sum(1 for d in range(lo, last + 1) if is_business(d))
|
|
77
|
+
return {
|
|
78
|
+
"start": format_iso_date(start),
|
|
79
|
+
"end": format_iso_date(end),
|
|
80
|
+
"inclusive": inclusive,
|
|
81
|
+
"businessDays": count if end >= start else -count,
|
|
82
|
+
"calendarDays": end - start,
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if inp.get("inclusive") is not None:
|
|
86
|
+
raise _bad("inclusive only applies with end.")
|
|
87
|
+
add = inp.get("add")
|
|
88
|
+
if not _is_int(add):
|
|
89
|
+
raise _bad("add must be an integer.")
|
|
90
|
+
n = int(add)
|
|
91
|
+
if abs(n) > MAX_ADD:
|
|
92
|
+
raise _bad(f"add must be within +/-{MAX_ADD}.")
|
|
93
|
+
step = 1 if n >= 0 else -1
|
|
94
|
+
remaining = abs(n)
|
|
95
|
+
cur = start
|
|
96
|
+
while remaining > 0:
|
|
97
|
+
cur += step
|
|
98
|
+
if is_business(cur):
|
|
99
|
+
remaining -= 1
|
|
100
|
+
return {
|
|
101
|
+
"start": format_iso_date(start),
|
|
102
|
+
"added": n,
|
|
103
|
+
"result": format_iso_date(cur),
|
|
104
|
+
"resultWeekday": weekday_iso(cur),
|
|
105
|
+
"calendarDays": cur - start,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
HANDLERS = {"time.business_days": business_days}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from typing import Any, Dict
|
|
5
|
+
|
|
6
|
+
from .._lib.errors import ToolExecutionError
|
|
7
|
+
from .context import Handler, ToolContext
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def trace_log_event(ctx: ToolContext) -> Any:
|
|
11
|
+
inp = ctx.input
|
|
12
|
+
step = str(inp.get("step") or "")
|
|
13
|
+
message = str(inp.get("message") or "")
|
|
14
|
+
if not step or not message:
|
|
15
|
+
raise ToolExecutionError("INVALID_INPUT", "step and message are required.")
|
|
16
|
+
level = str(inp.get("level")) if inp.get("level") in ("info", "warn", "error") else "info"
|
|
17
|
+
ts = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
18
|
+
count = ctx.trace_sink.record(
|
|
19
|
+
ctx.session_id,
|
|
20
|
+
{
|
|
21
|
+
"timestamp": ts,
|
|
22
|
+
"level": level,
|
|
23
|
+
"step": step,
|
|
24
|
+
"message": message,
|
|
25
|
+
"metadata": inp.get("metadata") if isinstance(inp.get("metadata"), dict) else None,
|
|
26
|
+
},
|
|
27
|
+
)
|
|
28
|
+
return {"recorded": True, "timestamp": ts, "eventCount": count}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
HANDLERS: Dict[str, Handler] = {
|
|
32
|
+
"trace.log_event": trace_log_event,
|
|
33
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Any, Dict, List
|
|
5
|
+
|
|
6
|
+
from .._lib.common import parse_iso_datetime
|
|
7
|
+
from .._lib.errors import ToolExecutionError
|
|
8
|
+
from .context import Handler, ToolContext
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def validate_batch_rules(ctx: ToolContext) -> Any:
|
|
12
|
+
inp = ctx.input
|
|
13
|
+
records = inp.get("records") if isinstance(inp.get("records"), list) else []
|
|
14
|
+
rules = inp.get("rules") if isinstance(inp.get("rules"), dict) else {}
|
|
15
|
+
errors: List[Dict[str, Any]] = []
|
|
16
|
+
valid_count = 0
|
|
17
|
+
for idx, rec in enumerate(records):
|
|
18
|
+
ok = True
|
|
19
|
+
rec_obj = rec if isinstance(rec, dict) else {}
|
|
20
|
+
for field, rule in rules.items():
|
|
21
|
+
if not isinstance(rule, dict):
|
|
22
|
+
continue
|
|
23
|
+
val = rec_obj.get(field)
|
|
24
|
+
if rule.get("required") and (val is None or val == ""):
|
|
25
|
+
errors.append({"index": idx, "field": field, "message": "Field is required"})
|
|
26
|
+
ok = False
|
|
27
|
+
continue
|
|
28
|
+
if val is None:
|
|
29
|
+
continue
|
|
30
|
+
if isinstance(rule.get("min"), (int, float)) and float(val) < float(rule["min"]):
|
|
31
|
+
errors.append({"index": idx, "field": field, "message": f"Must be >= {rule['min']}"})
|
|
32
|
+
ok = False
|
|
33
|
+
if isinstance(rule.get("max"), (int, float)) and float(val) > float(rule["max"]):
|
|
34
|
+
errors.append({"index": idx, "field": field, "message": f"Must be <= {rule['max']}"})
|
|
35
|
+
ok = False
|
|
36
|
+
if rule.get("email") and not re.match(r"^[^\s@]+@[^\s@]+\.[^\s@]+$", str(val)):
|
|
37
|
+
errors.append({"index": idx, "field": field, "message": "Invalid email format"})
|
|
38
|
+
ok = False
|
|
39
|
+
if rule.get("iso_date"):
|
|
40
|
+
try:
|
|
41
|
+
parse_iso_datetime(str(val))
|
|
42
|
+
except ToolExecutionError:
|
|
43
|
+
errors.append({"index": idx, "field": field, "message": "Invalid ISO date"})
|
|
44
|
+
ok = False
|
|
45
|
+
if isinstance(rule.get("enum"), list) and val not in rule["enum"]:
|
|
46
|
+
errors.append({"index": idx, "field": field, "message": f"Must be one of: {', '.join(map(str, rule['enum']))}"})
|
|
47
|
+
ok = False
|
|
48
|
+
if isinstance(rule.get("regex"), str) and not re.search(rule["regex"], str(val)):
|
|
49
|
+
errors.append({"index": idx, "field": field, "message": f"Does not match pattern {rule['regex']}"})
|
|
50
|
+
ok = False
|
|
51
|
+
if ok:
|
|
52
|
+
valid_count += 1
|
|
53
|
+
return {"validCount": valid_count, "invalidCount": len(records) - valid_count, "errors": errors}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
HANDLERS: Dict[str, Handler] = {
|
|
57
|
+
"validate.batch_rules": validate_batch_rules,
|
|
58
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import urllib.parse
|
|
6
|
+
from typing import Any, Dict, List, Optional
|
|
7
|
+
|
|
8
|
+
from .._lib.errors import ToolExecutionError
|
|
9
|
+
from .._lib.html import html_to_markdown, strip_html
|
|
10
|
+
from .._lib.net import safe_fetch_text
|
|
11
|
+
from .context import Handler, ToolContext
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def web_fetch_markdown(ctx: ToolContext) -> Any:
|
|
15
|
+
inp, security = ctx.input, ctx.security
|
|
16
|
+
max_chars = min(int(inp.get("maxChars") or security.max_output_chars or 16000), 32000)
|
|
17
|
+
include_links = inp.get("includeLinks") is not False
|
|
18
|
+
res = safe_fetch_text(str(inp.get("url") or ""), security)
|
|
19
|
+
title, md = html_to_markdown(res["body"], include_links)
|
|
20
|
+
truncated = len(md) > max_chars
|
|
21
|
+
out = md[:max_chars] if truncated else md
|
|
22
|
+
return {"url": res["finalUrl"], "title": title, "markdown": out, "truncated": truncated, "charCount": len(out)}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def web_fetch_json(ctx: ToolContext) -> Any:
|
|
26
|
+
inp, security = ctx.input, ctx.security
|
|
27
|
+
res = safe_fetch_text(str(inp.get("url") or ""), security, inp.get("headers"), inp.get("timeoutMs"))
|
|
28
|
+
try:
|
|
29
|
+
parsed = json.loads(res["body"])
|
|
30
|
+
except Exception:
|
|
31
|
+
raise ToolExecutionError("INVALID_JSON_RESPONSE", "Remote endpoint did not return valid JSON.")
|
|
32
|
+
return {"statusCode": res["statusCode"], "data": parsed, "contentType": res["contentType"]}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def web_extract_links(ctx: ToolContext) -> Any:
|
|
36
|
+
inp, security = ctx.input, ctx.security
|
|
37
|
+
same_domain_only = bool(inp.get("sameDomainOnly"))
|
|
38
|
+
filter_pattern = str(inp.get("filterPattern") or "")
|
|
39
|
+
res = safe_fetch_text(str(inp.get("url") or ""), security)
|
|
40
|
+
base_host = urllib.parse.urlparse(res["finalUrl"]).hostname or ""
|
|
41
|
+
links: List[Dict[str, str]] = []
|
|
42
|
+
for match in re.finditer(r'<a[^>]*href=["\']([^"\'#][^"\']*)["\'][^>]*>([\s\S]*?)</a>', res["body"], re.IGNORECASE):
|
|
43
|
+
if len(links) >= 100:
|
|
44
|
+
break
|
|
45
|
+
resolved = urllib.parse.urljoin(res["finalUrl"], match.group(1))
|
|
46
|
+
r_host = urllib.parse.urlparse(resolved).hostname or ""
|
|
47
|
+
if same_domain_only and r_host != base_host:
|
|
48
|
+
continue
|
|
49
|
+
text = strip_html(match.group(2))
|
|
50
|
+
if filter_pattern and filter_pattern not in resolved and filter_pattern not in text:
|
|
51
|
+
continue
|
|
52
|
+
links.append({"text": text or resolved, "href": resolved})
|
|
53
|
+
return {"baseUrl": res["finalUrl"], "links": links, "count": len(links)}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def web_extract_metadata(ctx: ToolContext) -> Any:
|
|
57
|
+
inp, security = ctx.input, ctx.security
|
|
58
|
+
res = safe_fetch_text(str(inp.get("url") or ""), security)
|
|
59
|
+
body = res["body"]
|
|
60
|
+
|
|
61
|
+
def get_meta(attr: str) -> Optional[str]:
|
|
62
|
+
m = re.search(rf'<meta[^>]+(?:name|property)=["\']{re.escape(attr)}["\'][^>]+content=["\']([^"\']*)["\']', body, re.IGNORECASE)
|
|
63
|
+
return m.group(1) if m else None
|
|
64
|
+
|
|
65
|
+
title_m = re.search(r"<title[^>]*>([\s\S]*?)</title>", body, re.IGNORECASE)
|
|
66
|
+
lang_m = re.search(r'<html[^>]+lang=["\']([^"\']+)["\']', body, re.IGNORECASE)
|
|
67
|
+
return {
|
|
68
|
+
"title": strip_html(title_m.group(1)) if title_m else "",
|
|
69
|
+
"description": get_meta("description") or get_meta("og:description") or "",
|
|
70
|
+
"author": get_meta("author"),
|
|
71
|
+
"publishedAt": get_meta("article:published_time"),
|
|
72
|
+
"language": lang_m.group(1) if lang_m else None,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
HANDLERS: Dict[str, Handler] = {
|
|
77
|
+
"web.fetch_markdown": web_fetch_markdown,
|
|
78
|
+
"web.fetch_json": web_fetch_json,
|
|
79
|
+
"web.extract_links": web_extract_links,
|
|
80
|
+
"web.extract_metadata": web_extract_metadata,
|
|
81
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import hmac
|
|
5
|
+
import os
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Any, Dict, Optional
|
|
9
|
+
|
|
10
|
+
from .models import SecurityConfig
|
|
11
|
+
from .registry import WarTools
|
|
12
|
+
from .stores import FileTraceSink, JsonFileKvStore
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def handle_mcp_message(kit: WarTools, msg: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
16
|
+
req_id = msg.get("id")
|
|
17
|
+
method = msg.get("method")
|
|
18
|
+
if method == "notifications/initialized":
|
|
19
|
+
return None
|
|
20
|
+
if method == "ping":
|
|
21
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": {}}
|
|
22
|
+
if method == "initialize":
|
|
23
|
+
return {
|
|
24
|
+
"jsonrpc": "2.0",
|
|
25
|
+
"id": req_id,
|
|
26
|
+
"result": {
|
|
27
|
+
"protocolVersion": "2024-11-05",
|
|
28
|
+
"serverInfo": {"name": "wartools-ai-python", "version": "0.1.1"},
|
|
29
|
+
"capabilities": {"tools": {}},
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
if method == "tools/list":
|
|
33
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": kit.get_tool_definitions()}}
|
|
34
|
+
if method == "wartools/approval":
|
|
35
|
+
# Out-of-band host channel: disabled unless WARTOOLS_ADMIN_TOKEN is set; never advertised to the model.
|
|
36
|
+
admin = os.environ.get("WARTOOLS_ADMIN_TOKEN")
|
|
37
|
+
if not admin:
|
|
38
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}
|
|
39
|
+
aparams = msg.get("params") or {}
|
|
40
|
+
tok = aparams.get("token")
|
|
41
|
+
if not isinstance(tok, str) or not hmac.compare_digest(tok.encode("utf-8"), admin.encode("utf-8")):
|
|
42
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32001, "message": "Unauthorized"}}
|
|
43
|
+
decision = aparams.get("decision")
|
|
44
|
+
if decision not in ("approve", "deny"):
|
|
45
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32602, "message": "decision must be approve or deny"}}
|
|
46
|
+
approval_id = str(aparams.get("id") or "")
|
|
47
|
+
done = kit.approve(approval_id) if decision == "approve" else kit.deny(approval_id)
|
|
48
|
+
return {"jsonrpc": "2.0", "id": req_id, "result": {"ok": done, "id": approval_id, "decision": decision}}
|
|
49
|
+
if method == "tools/call":
|
|
50
|
+
params = msg.get("params") or {}
|
|
51
|
+
name = str(params.get("name") or "")
|
|
52
|
+
args = params.get("arguments") if isinstance(params.get("arguments"), dict) else {}
|
|
53
|
+
envelope = kit.execute(name, args)
|
|
54
|
+
return {
|
|
55
|
+
"jsonrpc": "2.0",
|
|
56
|
+
"id": req_id,
|
|
57
|
+
"result": {
|
|
58
|
+
"content": [{"type": "text", "text": json.dumps(envelope)}],
|
|
59
|
+
"isError": not envelope["ok"],
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def start_stdio_server(kit: WarTools) -> None:
|
|
66
|
+
for raw_line in sys.stdin:
|
|
67
|
+
line = raw_line.strip()
|
|
68
|
+
if not line:
|
|
69
|
+
continue
|
|
70
|
+
try:
|
|
71
|
+
msg = json.loads(line)
|
|
72
|
+
resp = handle_mcp_message(kit, msg)
|
|
73
|
+
if resp is not None and "id" in msg:
|
|
74
|
+
sys.stdout.write(json.dumps(resp) + "\n")
|
|
75
|
+
sys.stdout.flush()
|
|
76
|
+
except Exception:
|
|
77
|
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}) + "\n")
|
|
78
|
+
sys.stdout.flush()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def main() -> None:
|
|
82
|
+
parser = argparse.ArgumentParser(description="WarToolsAI Python MCP Server")
|
|
83
|
+
parser.add_argument("--preset", default="none")
|
|
84
|
+
parser.add_argument("--enable", default="")
|
|
85
|
+
parser.add_argument("--fs-root", default="./workspace")
|
|
86
|
+
parser.add_argument("--store-file", default="")
|
|
87
|
+
parser.add_argument("--trace-file", default="")
|
|
88
|
+
parser.add_argument("--approval", choices=["required", "off"], default="required")
|
|
89
|
+
args = parser.parse_args()
|
|
90
|
+
|
|
91
|
+
enable = [s.strip() for s in args.enable.split(",") if s.strip()]
|
|
92
|
+
store = JsonFileKvStore(args.store_file) if args.store_file else None
|
|
93
|
+
trace_sink = FileTraceSink(args.trace_file) if args.trace_file else None
|
|
94
|
+
kit = WarTools.create(
|
|
95
|
+
preset=args.preset,
|
|
96
|
+
enable=enable,
|
|
97
|
+
security=SecurityConfig(fs_root=args.fs_root),
|
|
98
|
+
store=store,
|
|
99
|
+
trace_sink=trace_sink,
|
|
100
|
+
runtime={"approval": {"mode": args.approval}},
|
|
101
|
+
)
|
|
102
|
+
start_stdio_server(kit)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if __name__ == "__main__":
|
|
106
|
+
main()
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any, Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
8
|
+
|
|
9
|
+
class _BaseSchema(BaseModel):
|
|
10
|
+
model_config = ConfigDict(populate_by_name=True, extra="allow")
|
|
11
|
+
|
|
12
|
+
class SecurityConfig(_BaseSchema):
|
|
13
|
+
fs_root: str = Field(default="./workspace", alias="fsRoot")
|
|
14
|
+
http_allow_domains: List[str] = Field(default_factory=list, alias="httpAllowDomains")
|
|
15
|
+
http_block_domains: List[str] = Field(default_factory=list, alias="httpBlockDomains")
|
|
16
|
+
allow_private_test_loopback: bool = Field(default=False, alias="allowPrivateTestLoopback")
|
|
17
|
+
max_output_chars: int = Field(default=16000, alias="maxOutputChars")
|
|
18
|
+
timeout_ms: int = Field(default=10000, alias="timeoutMs")
|
|
19
|
+
|
|
20
|
+
class WarToolError(_BaseSchema):
|
|
21
|
+
code: str
|
|
22
|
+
message: str
|
|
23
|
+
recoverable: bool = True
|
|
24
|
+
|
|
25
|
+
class WarToolMeta(_BaseSchema):
|
|
26
|
+
duration_ms: int = Field(default=1, alias="durationMs")
|
|
27
|
+
approval_id: Optional[str] = Field(default=None, alias="approvalId")
|
|
28
|
+
approval_expires_at: Optional[str] = Field(default=None, alias="approvalExpiresAt")
|
|
29
|
+
truncated: bool = False
|
|
30
|
+
|
|
31
|
+
class WarToolEnvelope(_BaseSchema):
|
|
32
|
+
def model_dump(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: # type: ignore[override]
|
|
33
|
+
d = super().model_dump(*args, **kwargs)
|
|
34
|
+
meta = d.get("meta")
|
|
35
|
+
if isinstance(meta, dict):
|
|
36
|
+
for k in ("approvalId", "approvalExpiresAt", "approval_id", "approval_expires_at"):
|
|
37
|
+
if k in meta and meta[k] is None:
|
|
38
|
+
del meta[k]
|
|
39
|
+
return d
|
|
40
|
+
|
|
41
|
+
ok: bool
|
|
42
|
+
tool: str
|
|
43
|
+
data: Optional[Any] = None
|
|
44
|
+
error: Optional[WarToolError] = None
|
|
45
|
+
meta: WarToolMeta
|
|
46
|
+
|
|
47
|
+
except ImportError:
|
|
48
|
+
@dataclass
|
|
49
|
+
class SecurityConfig: # type: ignore[no-redef]
|
|
50
|
+
fs_root: str = "./workspace"
|
|
51
|
+
http_allow_domains: List[str] = field(default_factory=list)
|
|
52
|
+
http_block_domains: List[str] = field(default_factory=list)
|
|
53
|
+
allow_private_test_loopback: bool = False
|
|
54
|
+
max_output_chars: int = 16000
|
|
55
|
+
timeout_ms: int = 10000
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_dict(cls, raw: Optional[Dict[str, Any]]) -> "SecurityConfig":
|
|
59
|
+
raw = raw or {}
|
|
60
|
+
return cls(
|
|
61
|
+
fs_root=raw.get("fsRoot", raw.get("fs_root", "./workspace")),
|
|
62
|
+
http_allow_domains=list(raw.get("httpAllowDomains", raw.get("http_allow_domains", [])) or []),
|
|
63
|
+
http_block_domains=list(raw.get("httpBlockDomains", raw.get("http_block_domains", [])) or []),
|
|
64
|
+
allow_private_test_loopback=bool(
|
|
65
|
+
raw.get("allowPrivateTestLoopback", raw.get("allow_private_test_loopback", False))
|
|
66
|
+
),
|
|
67
|
+
max_output_chars=int(raw.get("maxOutputChars", raw.get("max_output_chars", 16000))),
|
|
68
|
+
timeout_ms=int(raw.get("timeoutMs", raw.get("timeout_ms", 10000))),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class WarToolError: # type: ignore[no-redef]
|
|
73
|
+
code: str
|
|
74
|
+
message: str
|
|
75
|
+
recoverable: bool = True
|
|
76
|
+
|
|
77
|
+
def model_dump(self, by_alias: bool = True) -> Dict[str, Any]:
|
|
78
|
+
return {"code": self.code, "message": self.message, "recoverable": self.recoverable}
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class WarToolMeta: # type: ignore[no-redef]
|
|
82
|
+
duration_ms: int = 1
|
|
83
|
+
approval_id: Optional[str] = None
|
|
84
|
+
approval_expires_at: Optional[str] = None
|
|
85
|
+
truncated: bool = False
|
|
86
|
+
|
|
87
|
+
def model_dump(self, by_alias: bool = True) -> Dict[str, Any]:
|
|
88
|
+
out: Dict[str, Any] = {"durationMs": self.duration_ms, "truncated": self.truncated}
|
|
89
|
+
if self.approval_id is not None:
|
|
90
|
+
out["approvalId"] = self.approval_id
|
|
91
|
+
if self.approval_expires_at is not None:
|
|
92
|
+
out["approvalExpiresAt"] = self.approval_expires_at
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
@dataclass
|
|
96
|
+
class WarToolEnvelope: # type: ignore[no-redef]
|
|
97
|
+
ok: bool
|
|
98
|
+
tool: str
|
|
99
|
+
data: Optional[Any]
|
|
100
|
+
error: Optional[WarToolError]
|
|
101
|
+
meta: WarToolMeta
|
|
102
|
+
|
|
103
|
+
def model_dump(self, by_alias: bool = True) -> Dict[str, Any]:
|
|
104
|
+
return {
|
|
105
|
+
"ok": self.ok,
|
|
106
|
+
"tool": self.tool,
|
|
107
|
+
"data": self.data,
|
|
108
|
+
"error": self.error.model_dump(by_alias=by_alias) if self.error else None,
|
|
109
|
+
"meta": self.meta.model_dump(by_alias=by_alias),
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def coerce_security_config(raw: Any) -> SecurityConfig:
|
|
114
|
+
if isinstance(raw, SecurityConfig):
|
|
115
|
+
return raw
|
|
116
|
+
if hasattr(SecurityConfig, "model_validate"):
|
|
117
|
+
return SecurityConfig.model_validate(raw or {}) # type: ignore[attr-defined]
|
|
118
|
+
return SecurityConfig.from_dict(raw if isinstance(raw, dict) else {}) # type: ignore[attr-defined]
|
|
File without changes
|