unitoolkit 0.7.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.
unitoolkit/mcp.py ADDED
@@ -0,0 +1,85 @@
1
+ """Minimal MCP server over stdio (JSON-RPC 2.0, newline-delimited). Stdlib only.
2
+
3
+ python -m unitoolkit.mcp
4
+
5
+ Register it in any MCP client, e.g. Claude Code:
6
+ claude mcp add unitoolkit -- python -m unitoolkit.mcp
7
+ Hermes (config.yaml):
8
+ mcp_servers: {unitoolkit: {command: python3, args: [-m, unitoolkit.mcp]}}
9
+
10
+ Lists the question-shaped core tools by default (agent.CORE); UNITOOLKIT_TOOLS=all lists all,
11
+ or give a comma list. Every tool is callable by name regardless of what is listed.
12
+ """
13
+ import json
14
+ import sys
15
+ import traceback
16
+
17
+ from . import __version__
18
+ from .tools import TOOLS, call, manifest
19
+
20
+ PROTOCOL = "2025-06-18"
21
+
22
+
23
+ def _reply(mid, result=None, error=None):
24
+ msg = {"jsonrpc": "2.0", "id": mid}
25
+ if error is not None:
26
+ msg["error"] = error
27
+ else:
28
+ msg["result"] = result
29
+ sys.stdout.write(json.dumps(msg, ensure_ascii=False) + "\n")
30
+ sys.stdout.flush()
31
+
32
+
33
+ def handle(req):
34
+ method, mid, params = req.get("method"), req.get("id"), req.get("params") or {}
35
+ if method == "initialize":
36
+ return {"protocolVersion": params.get("protocolVersion", PROTOCOL),
37
+ "capabilities": {"tools": {"listChanged": False}},
38
+ "serverInfo": {"name": "unitoolkit", "version": __version__},
39
+ "instructions": ("Read-only access to a student's own school systems: Canvas, "
40
+ "Ladok, the library, the timetable, and the subscribed research "
41
+ "databases. Start with `today` for 'what do I need to do', "
42
+ "`find_sources` for 'find me sources'. When anything fails, run "
43
+ "`doctor`: it names the fix, which is always a human action "
44
+ "(sign in once, renew a token). Never type a password. "
45
+ "Set UNITOOLKIT_TOOLS=all to list every tool.")}
46
+ if method == "tools/list":
47
+ from .agent import listed
48
+ return {"tools": manifest(listed(list(TOOLS)))}
49
+ if method == "tools/call":
50
+ name = params.get("name")
51
+ try:
52
+ out = call(name, params.get("arguments") or {})
53
+ return {"content": [{"type": "text",
54
+ "text": json.dumps(out, ensure_ascii=False, indent=1, default=str)}],
55
+ "isError": False}
56
+ except Exception as e: # tool errors are results, not protocol errors
57
+ return {"content": [{"type": "text", "text": f"{type(e).__name__}: {e}"}], "isError": True}
58
+ if method == "ping":
59
+ return {}
60
+ raise LookupError(method)
61
+
62
+
63
+ def main():
64
+ for line in sys.stdin:
65
+ line = line.strip()
66
+ if not line:
67
+ continue
68
+ try:
69
+ req = json.loads(line)
70
+ except ValueError:
71
+ _reply(None, error={"code": -32700, "message": "parse error"})
72
+ continue
73
+ if "id" not in req: # notification (e.g. notifications/initialized)
74
+ continue
75
+ try:
76
+ _reply(req["id"], handle(req))
77
+ except LookupError as e:
78
+ _reply(req["id"], error={"code": -32601, "message": f"method not found: {e}"})
79
+ except Exception as e:
80
+ _reply(req["id"], error={"code": -32603, "message": str(e),
81
+ "data": traceback.format_exc()[-800:]})
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
@@ -0,0 +1,147 @@
1
+ """Build the programme map: every course, its kursplan and kurslitteraturlista, downloaded.
2
+
3
+ Source: the public course-overview page on shh.se. Course names are plain text, and the
4
+ document links appear as unordered "Kursplan"/"Kurslitteraturlista" anchor pairs, so they
5
+ are NOT paired by position. Instead every document is downloaded and named by the course
6
+ code found inside it (the page's own index misaligns whenever a course omits a link).
7
+
8
+ Documents live in SharePoint as share links; `download.aspx?share=<docid>` returns the
9
+ real bytes to a logged-in browser (`unitoolkit.browser`). SHH publishes kursplaner as HTML
10
+ pages and kurslitteraturlistor as PDFs.
11
+
12
+ python -m unitoolkit.programme
13
+ """
14
+ import asyncio
15
+ import json
16
+ import pathlib
17
+ import re
18
+ import subprocess
19
+
20
+ from . import browser
21
+ from .sharepoint import fetch_share
22
+
23
+ LANDING = "https://www.shh.se/sv/utbildningar/grundniva/sjukskoterskeprogrammet-kurser/"
24
+ OUT = pathlib.Path("~/courses/programme").expanduser()
25
+ CODE_RE = re.compile(r"\b([0-9][A-ZÅÄÖ]{2,4}[0-9]+)\b")
26
+ COURSE_RE = re.compile(r"^(.+?),?\s*\(?([0-9][A-ZÅÄÖ]{2,4}[0-9]+)\)?,?\s*([\d.,]+)\s*hp\s*$")
27
+
28
+
29
+ async def _scrape(t):
30
+ from .browser import _eval, _session
31
+
32
+ async def steps(call):
33
+ await call("Page.enable")
34
+ await call("Page.navigate", url=LANDING)
35
+ await asyncio.sleep(4)
36
+ anchors = await _eval(call, (
37
+ "JSON.stringify([...document.querySelectorAll('a')]"
38
+ ".filter(a=>/^Kurs(plan|litteraturlista)$/.test(a.innerText.trim()))"
39
+ ".map(a=>[a.innerText.trim(),a.href]))"))
40
+ text = await _eval(call, "document.body.innerText")
41
+ return json.loads(anchors), text
42
+
43
+ return await _session(t["webSocketDebuggerUrl"], steps)
44
+
45
+
46
+ def _courses_from_text(text):
47
+ out = []
48
+ for line in text.split("\n"):
49
+ line = line.strip()
50
+ m = COURSE_RE.match(line)
51
+ if m:
52
+ out.append({"name": m.group(1).strip(), "code": m.group(2),
53
+ "hp": float(m.group(3).replace(",", "."))})
54
+ elif re.search(r"[0-9][A-ZÅÄÖ]{2,4}[0-9]", line):
55
+ code = CODE_RE.search(line)
56
+ out.append({"name": re.sub(r"\(?[0-9][A-ZÅÄÖ]{2,4}[0-9]+\)?,?.*$", "", line).strip(),
57
+ "code": code.group(1), "hp": None})
58
+ return out
59
+
60
+
61
+ def doc_text(path):
62
+ p = pathlib.Path(path)
63
+ if p.suffix in (".html", ".htm"):
64
+ raw = p.read_text(errors="ignore")
65
+ return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", raw))
66
+ if p.suffix == ".pdf":
67
+ try:
68
+ return subprocess.run(["pdftotext", "-q", str(p), "-"], capture_output=True,
69
+ text=True, timeout=60).stdout
70
+ except (OSError, subprocess.SubprocessError):
71
+ return ""
72
+ if p.suffix == ".docx":
73
+ try:
74
+ import html
75
+ import zipfile
76
+ x = zipfile.ZipFile(p).read("word/document.xml").decode("utf8", "ignore")
77
+ return html.unescape(re.sub(r"<[^>]+>", " ", x.replace("</w:p>", "\n")))
78
+ except Exception:
79
+ return ""
80
+ return ""
81
+
82
+
83
+ KNOWN_CODES = set()
84
+
85
+
86
+ def build(out=None):
87
+ global KNOWN_CODES, OUT
88
+ if out:
89
+ OUT = pathlib.Path(out).expanduser()
90
+ t = browser.new_tab(LANDING)
91
+ try:
92
+ anchors, text = asyncio.run(_scrape(t))
93
+ finally:
94
+ browser.close_tab(t["id"])
95
+ courses = _courses_from_text(text)
96
+ KNOWN_CODES = {c["code"] for c in courses}
97
+ OUT.mkdir(parents=True, exist_ok=True)
98
+ raw = OUT / "raw"
99
+ raw.mkdir(exist_ok=True)
100
+ got = []
101
+ for i, (kind, share) in enumerate(anchors):
102
+ body, ext = fetch_share(share)
103
+ if not body:
104
+ got.append({"kind": kind, "share": share, "error": "download failed"})
105
+ continue
106
+ kind_slug = "kursplan" if kind == "Kursplan" else "litteratur"
107
+ tmp = raw / f"_tmp_{i}.{ext}"
108
+ tmp.write_bytes(body)
109
+ text_ = doc_text(tmp)
110
+ codes = CODE_RE.findall(text_)
111
+ known = [c for c in codes if c in KNOWN_CODES]
112
+ code = (known or codes or [f"unknown{i}"])[0]
113
+ final = raw / f"{code}_{kind_slug}.{ext}"
114
+ if final.exists() and final.stat().st_size == tmp.stat().st_size:
115
+ tmp.unlink()
116
+ else:
117
+ tmp.rename(final)
118
+ got.append({"kind": kind, "code": code, "file": str(final), "bytes": len(body)})
119
+ for c in courses:
120
+ c["kursplan_file"] = next((g["file"] for g in got
121
+ if g.get("code") == c["code"] and g["kind"] == "Kursplan"), None)
122
+ c["litteratur_file"] = next((g["file"] for g in got
123
+ if g.get("code") == c["code"] and g["kind"] == "Kurslitteraturlista"), None)
124
+ (OUT / "programme.json").write_text(json.dumps({"courses": courses, "documents": got},
125
+ ensure_ascii=False, indent=1))
126
+ return courses, got
127
+
128
+
129
+ def report(courses):
130
+ lines = ["# Sjuksköterskeprogrammet 180 hp, kurskarta", "",
131
+ f"{len(courses)} kurser enligt shh.se. Kursplan och kurslitteraturlista hämtade från "
132
+ "programmets kursöversikt.", ""]
133
+ for i, c in enumerate(courses, 1):
134
+ lines.append(f"{i}. **{c['name']}** ({c['code']}): "
135
+ f"kursplan {'ja' if c.get('kursplan_file') else 'NEJ'}, "
136
+ f"litteratur {'ja' if c.get('litteratur_file') else 'NEJ'}")
137
+ return "\n".join(lines)
138
+
139
+
140
+ if __name__ == "__main__":
141
+ cs, docs = build()
142
+ md = report(cs)
143
+ (OUT / "KURSKARTA.md").write_text(md)
144
+ print(md)
145
+ print(f"\n{len(cs)} kurser, {sum(1 for c in cs if c.get('kursplan_file'))} kursplaner, "
146
+ f"{sum(1 for c in cs if c.get('litteratur_file'))} litteraturlistor, "
147
+ f"{sum(1 for d in docs if d.get('error'))} fel -> {OUT}")