Методика оценки: судья по эталону мерит точность, полноту и галлюцинации, Q = 100 × (0,4·Т + 0,4·П + 0,2·Г); прогонщик DeepSeek Harness и тесты оценки
67df8f6 verified Download runners/dsh/desk/server.py from synaptex/workpermit: direct link, hf CLI and curl.
- Browser
- Download file 24.5 kB
-
https://huggingface.co/datasets/synaptex/workpermit/resolve/main/runners/dsh/desk/server.py
- Command line
-
hf download hf://datasets/synaptex/workpermit/runners/dsh/desk/server.py
-
curl -L -o server.py https://huggingface.co/datasets/synaptex/workpermit/resolve/main/runners/dsh/desk/server.py
24.5 kB
| """Серверы MCP для агента общего назначения: подключённая система (двойник 1С, Jira или GitHub), долговременная память и | |
| органайзер человека. Агент DeepSeek Harness подключает их плагином ``dsh-mcp-client`` по Streamable HTTP, как подключал бы | |
| настоящие. | |
| Сервер работает в своём контейнере во внутренней сети Docker, рядом с агентом: агент видит только инструменты, а не код | |
| двойников и не файл состояния. Состояние (память, напоминания, автоматизации, доска, заметки) и журнал вызовов пишутся в | |
| папку ``--state``: по ним прогонщик снимает органайзер после задачи и выдачу подключённой системы для судьи. | |
| python server.py --port 8080 --state /state --time-zone Europe/Moscow [--system onec|jira|github] | |
| Адреса: ``POST /mcp/memory``, ``/mcp/organizer`` и ``/mcp/<system>``. Только стандартная библиотека Python. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import json | |
| import sys | |
| import threading | |
| import uuid | |
| from datetime import datetime, timedelta | |
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| from pathlib import Path | |
| from zoneinfo import ZoneInfo | |
| sys.path.insert(0, str(Path(__file__).parent)) | |
| import github # noqa: E402 | |
| import jira # noqa: E402 | |
| import onec # noqa: E402 | |
| PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05") | |
| REPEATS = ("none", "daily", "weekdays", "weekly", "monthly", "yearly") | |
| def _tool(name: str, description: str, properties: dict, required: list[str]) -> dict: | |
| return {"name": name, "description": description, | |
| "inputSchema": {"type": "object", "properties": properties, "required": required, "additionalProperties": False}} | |
| def _text(description: str) -> dict: | |
| return {"type": "string", "description": description} | |
| class ToolError(Exception): | |
| """Отказ инструмента: агент видит его текстом с пометкой ошибки.""" | |
| class Desk: | |
| """Состояние задачи и инструменты серверов.""" | |
| def __init__(self, state: Path, time_zone: str, system: str | None): | |
| self.state_dir, self.zone, self.system = state, ZoneInfo(time_zone), system | |
| self.lock = threading.Lock() | |
| self.data = {"memory": [], "reminders": [], "automations": [], "board_tasks": [], "notes": [], "next_id": 1} | |
| state.mkdir(parents=True, exist_ok=True) | |
| saved = state / "state.json" | |
| if saved.exists(): | |
| self.data = json.loads(saved.read_text(encoding="utf-8")) | |
| self.twin = onec.OneCBase() if system == "onec" else github.Repository() if system == "github" else None | |
| # ── Устройство серверов ────────────────────────────────────────────────────────────────────────────────── | |
| def servers(self) -> dict[str, dict]: | |
| zone = self.zone.key | |
| servers = { | |
| "memory": { | |
| "instructions": "Долговременная память о человеке, общая для всех разговоров с ним: сохраняй то, что пригодится " | |
| "в другом разговоре, и смотри её, когда речь может идти о прежнем.", | |
| "tools": [ | |
| _tool("remember", "Сохранить сведение о человеке или его работе.", {"text": _text("Сведение одной-двумя фразами.")}, ["text"]), | |
| _tool("recall", "Все сохранённые сведения с датой сохранения, по порядку.", {}, []), | |
| _tool("forget", "Удалить сведение по номеру.", {"id": {"type": "integer"}}, ["id"]), | |
| ], | |
| }, | |
| "organizer": { | |
| "instructions": f"Органайзер человека: напоминания, автоматизации (работа агента по расписанию), доска задач и заметки. " | |
| f"Время — местное время человека, пояс {zone}.", | |
| "tools": [ | |
| _tool("current_time", "Текущие дата и время у человека.", {}, []), | |
| _tool("create_reminder", "Поставить напоминание человеку.", { | |
| "text": _text("О чём напомнить."), | |
| "at": _text("Когда: «ГГГГ-ММ-ДДTЧЧ:ММ» местного времени или «ЧЧ:ММ» — ближайшее такое время."), | |
| "repeat": {"type": "string", "enum": list(REPEATS), "description": "Повтор; по умолчанию none."}}, ["text", "at"]), | |
| _tool("list_reminders", "Напоминания человека.", {}, []), | |
| _tool("delete_reminder", "Снять напоминание по номеру.", {"id": {"type": "integer"}}, ["id"]), | |
| _tool("create_automation", "Поставить работу агента по расписанию: в назначенное время агент выполнит задание и пришлёт итог.", { | |
| "instruction": _text("Что сделать."), | |
| "at": _text("Когда: «ГГГГ-ММ-ДДTЧЧ:ММ» местного времени или «ЧЧ:ММ» — ближайшее такое время."), | |
| "repeat": {"type": "string", "enum": list(REPEATS), "description": "Повтор; по умолчанию none."}}, ["instruction", "at"]), | |
| _tool("list_automations", "Автоматизации человека.", {}, []), | |
| _tool("delete_automation", "Снять автоматизацию по номеру.", {"id": {"type": "integer"}}, ["id"]), | |
| _tool("create_board_task", "Поставить задачу на доску.", { | |
| "title": _text("Название задачи."), "description": _text("Описание."), | |
| "due": _text("Срок: «ГГГГ-ММ-ДД» или «ГГГГ-ММ-ДДTЧЧ:ММ» местного времени.")}, ["title"]), | |
| _tool("list_board_tasks", "Задачи на доске.", {}, []), | |
| _tool("update_board_task", "Изменить задачу доски по номеру.", { | |
| "id": {"type": "integer"}, "title": _text("Новое название."), "description": _text("Новое описание."), | |
| "due": _text("Новый срок.")}, ["id"]), | |
| _tool("delete_board_task", "Удалить задачу доски по номеру.", {"id": {"type": "integer"}}, ["id"]), | |
| _tool("create_note", "Записать заметку.", {"title": _text("Название."), "text": _text("Текст.")}, ["title", "text"]), | |
| _tool("list_notes", "Все заметки.", {}, []), | |
| _tool("search_notes", "Заметки, в названии или тексте которых есть слова запроса.", {"query": _text("Слова поиска.")}, ["query"]), | |
| _tool("update_note", "Изменить заметку по номеру.", {"id": {"type": "integer"}, "title": _text("Новое название."), | |
| "text": _text("Новый текст.")}, ["id"]), | |
| _tool("delete_note", "Удалить заметку по номеру.", {"id": {"type": "integer"}}, ["id"]), | |
| ], | |
| }, | |
| } | |
| if self.system == "onec": | |
| servers["onec"] = {"instructions": "Подключённая база 1С «Торговля» по стандартному интерфейсу OData, только чтение.", "tools": [ | |
| _tool("odata_get", "GET к стандартному интерфейсу OData базы 1С. Ответ — тело как есть.", {"path": _text( | |
| "Адрес после /odata/standard.odata/: «$metadata», «Catalog_Номенклатура?$format=json&$top=10», " | |
| "«AccumulationRegister_ТоварыНаСкладах/Balance(Period=datetime'2024-04-01T00:00:00')?$format=json».")}, ["path"])]} | |
| elif self.system == "jira": | |
| servers["jira"] = {"instructions": "Подключённая Jira компании по REST API, только чтение.", "tools": [ | |
| _tool("api_get", "GET к REST API Jira. Ответ — тело как есть.", {"path": _text( | |
| "Адрес от корня сайта: «rest/api/2/issue/DEV-7», «rest/api/2/issue/DEV-7/comment?startAt=0&maxResults=50», " | |
| "«rest/api/3/search/jql?jql=project=DEV».")}, ["path"])]} | |
| elif self.system == "github": | |
| servers["github"] = {"instructions": "Подключённый репозиторий GitHub acme/warehouse по REST API, только чтение.", "tools": [ | |
| _tool("api_get", "GET к REST API GitHub. Ответ — тело как есть; содержимое файла (content в base64) приходит " | |
| "расшифрованным в поле text.", {"path": _text( | |
| "Адрес от корня API: «repos/acme/warehouse», «repos/acme/warehouse/git/trees/main?recursive=1», " | |
| "«repos/acme/warehouse/contents/README.md», «repos/acme/warehouse/issues/7/comments?per_page=100&page=1».")}, ["path"])]} | |
| return servers | |
| # ── Вызов инструмента ──────────────────────────────────────────────────────────────────────────────────── | |
| def call(self, server: str, tool: str, arguments: dict) -> str: | |
| with self.lock: | |
| try: | |
| result, failed = getattr(self, f"_{server}_{tool}")(**arguments), False | |
| except ToolError as error: | |
| result, failed = str(error), True | |
| except TypeError as error: | |
| result, failed = f"Неверные параметры: {error}", True | |
| self._save() | |
| with (self.state_dir / "calls.jsonl").open("a", encoding="utf-8") as log: | |
| log.write(json.dumps({"server": server, "tool": tool, "arguments": arguments, "result": result, "error": failed}, | |
| ensure_ascii=False) + "\n") | |
| if failed: | |
| raise ToolError(result) | |
| return result | |
| def _save(self) -> None: | |
| temporary = self.state_dir / "state.json.tmp" | |
| temporary.write_text(json.dumps(self.data, ensure_ascii=False, indent=1), encoding="utf-8") | |
| temporary.replace(self.state_dir / "state.json") | |
| def _now(self) -> datetime: | |
| return datetime.now(self.zone).replace(second=0, microsecond=0, tzinfo=None) | |
| def _id(self) -> int: | |
| self.data["next_id"] += 1 | |
| return self.data["next_id"] - 1 | |
| def _find(self, kind: str, id: int) -> dict: | |
| found = next((x for x in self.data[kind] if x["id"] == id), None) | |
| if found is None: | |
| raise ToolError(f"Записи с номером {id} нет.") | |
| return found | |
| def _moment(self, at: str) -> str: | |
| """Местное время «ГГГГ-ММ-ДДTЧЧ:ММ»; «ЧЧ:ММ» — ближайшее такое время от текущего.""" | |
| at = at.strip().replace(" ", "T") | |
| try: | |
| if len(at) == 5 and at[2] == ":": | |
| time = datetime.strptime(at, "%H:%M").time() | |
| moment = datetime.combine(self._now().date(), time) | |
| return (moment if moment > self._now() else moment + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M") | |
| return datetime.fromisoformat(at[:16]).strftime("%Y-%m-%dT%H:%M") | |
| except ValueError: | |
| raise ToolError(f"Время «{at}» не разобрано: нужно «ГГГГ-ММ-ДДTЧЧ:ММ» или «ЧЧ:ММ».") from None | |
| def _listing(items: list[dict], empty: str) -> str: | |
| return json.dumps(items, ensure_ascii=False, indent=1) if items else empty | |
| # память | |
| def _memory_remember(self, text: str) -> str: | |
| item = {"id": self._id(), "saved": self._now().strftime("%Y-%m-%dT%H:%M"), "text": text} | |
| self.data["memory"].append(item) | |
| return f"Сохранено под номером {item['id']}." | |
| def _memory_recall(self) -> str: | |
| return self._listing(self.data["memory"], "Память пуста.") | |
| def _memory_forget(self, id: int) -> str: | |
| self.data["memory"].remove(self._find("memory", id)) | |
| return f"Сведение {id} удалено." | |
| # органайзер | |
| def _organizer_current_time(self) -> str: | |
| now = datetime.now(self.zone) | |
| return f"{now:%Y-%m-%d %H:%M}, {['понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота', 'воскресенье'][now.weekday()]}, пояс {self.zone.key} (UTC{now:%z})" | |
| def _scheduled(self, kind: str, text: str, at: str, repeat: str | None) -> str: | |
| repeat = repeat or "none" | |
| if repeat not in REPEATS: | |
| raise ToolError(f"Повтор «{repeat}» не из {', '.join(REPEATS)}.") | |
| item = {"id": self._id(), "text": text, "at": self._moment(at), "repeat": repeat} | |
| self.data[kind].append(item) | |
| return f"Поставлено под номером {item['id']}: {item['at']}" + ("" if repeat == "none" else f", повтор {repeat}") + "." | |
| def _organizer_create_reminder(self, text: str, at: str, repeat: str = "none") -> str: | |
| return self._scheduled("reminders", text, at, repeat) | |
| def _organizer_list_reminders(self) -> str: | |
| return self._listing(self.data["reminders"], "Напоминаний нет.") | |
| def _organizer_delete_reminder(self, id: int) -> str: | |
| self.data["reminders"].remove(self._find("reminders", id)) | |
| return f"Напоминание {id} снято." | |
| def _organizer_create_automation(self, instruction: str, at: str, repeat: str = "none") -> str: | |
| return self._scheduled("automations", instruction, at, repeat) | |
| def _organizer_list_automations(self) -> str: | |
| return self._listing(self.data["automations"], "Автоматизаций нет.") | |
| def _organizer_delete_automation(self, id: int) -> str: | |
| self.data["automations"].remove(self._find("automations", id)) | |
| return f"Автоматизация {id} снята." | |
| def _due(self, due: str | None) -> str | None: | |
| if not due: | |
| return None | |
| due = due.strip() | |
| return self._moment(due if "T" in due or " " in due else due + "T00:00") | |
| def _organizer_create_board_task(self, title: str, description: str = "", due: str | None = None) -> str: | |
| item = {"id": self._id(), "title": title, "description": description, "due": self._due(due)} | |
| self.data["board_tasks"].append(item) | |
| return f"Задача {item['id']} на доске" + (f", срок {item['due']}" if item["due"] else "") + "." | |
| def _organizer_list_board_tasks(self) -> str: | |
| return self._listing(self.data["board_tasks"], "Доска пуста.") | |
| def _organizer_update_board_task(self, id: int, title: str | None = None, description: str | None = None, due: str | None = None) -> str: | |
| item = self._find("board_tasks", id) | |
| if title is not None: | |
| item["title"] = title | |
| if description is not None: | |
| item["description"] = description | |
| if due is not None: | |
| item["due"] = self._due(due) | |
| return f"Задача {id} изменена." | |
| def _organizer_delete_board_task(self, id: int) -> str: | |
| self.data["board_tasks"].remove(self._find("board_tasks", id)) | |
| return f"Задача {id} удалена." | |
| def _organizer_create_note(self, title: str, text: str) -> str: | |
| item = {"id": self._id(), "title": title, "text": text} | |
| self.data["notes"].append(item) | |
| return f"Заметка {item['id']} записана." | |
| def _organizer_list_notes(self) -> str: | |
| return self._listing(self.data["notes"], "Заметок нет.") | |
| def _organizer_search_notes(self, query: str) -> str: | |
| words = [w for w in query.lower().split() if w] | |
| found = [n for n in self.data["notes"] if any(w in (n["title"] + " " + n["text"]).lower() for w in words)] | |
| return self._listing(found, "Подходящих заметок нет.") | |
| def _organizer_update_note(self, id: int, title: str | None = None, text: str | None = None) -> str: | |
| item = self._find("notes", id) | |
| if title is not None: | |
| item["title"] = title | |
| if text is not None: | |
| item["text"] = text | |
| return f"Заметка {id} изменена." | |
| def _organizer_delete_note(self, id: int) -> str: | |
| self.data["notes"].remove(self._find("notes", id)) | |
| return f"Заметка {id} удалена." | |
| # подключённые системы | |
| def _onec_odata_get(self, path: str) -> str: | |
| return _response(*self.twin.answer("http://base/trade/odata/standard.odata/" + path.lstrip("/"))) | |
| def _jira_api_get(self, path: str) -> str: | |
| return _response(*jira.answer("https://jira.example/" + path.lstrip("/"))) | |
| def _github_api_get(self, path: str) -> str: | |
| status, kind, body = self.twin.answer("https://api.github.com/" + path.lstrip("/")) | |
| try: | |
| value = json.loads(body) | |
| except ValueError: | |
| value = None | |
| if isinstance(value, dict) and value.get("encoding") == "base64" and "content" in value: | |
| value["text"] = base64.b64decode(value.pop("content")).decode("utf-8", errors="replace") | |
| value.pop("encoding") | |
| body = json.dumps(value, ensure_ascii=False) | |
| return _response(status, kind, body) | |
| def _response(status: int, kind: str, body: str) -> str: | |
| """Ответ системы агенту: код и тело как есть. Отказ системы — тоже ответ, а не сбой инструмента.""" | |
| return f"HTTP {status}\n{body}" | |
| # ── Протокол MCP поверх HTTP ───────────────────────────────────────────────────────────────────────────────────── | |
| def handle(desk: Desk, server: str, message) -> dict | None: | |
| """Ответ JSON-RPC на сообщение; уведомление ответа не получает.""" | |
| if not isinstance(message, dict): | |
| return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid Request"}} | |
| if "id" not in message: | |
| return None | |
| method, params, servers = message.get("method"), message.get("params") or {}, desk.servers() | |
| def result(value): | |
| return {"jsonrpc": "2.0", "id": message["id"], "result": value} | |
| def error(code, text): | |
| return {"jsonrpc": "2.0", "id": message["id"], "error": {"code": code, "message": text}} | |
| if method == "initialize": | |
| asked = params.get("protocolVersion") | |
| return result({"protocolVersion": asked if asked in PROTOCOLS else PROTOCOLS[0], "capabilities": {"tools": {"listChanged": False}}, | |
| "serverInfo": {"name": f"workpermit-{server}", "version": "1.0.0"}, "instructions": servers[server]["instructions"]}) | |
| if method == "ping": | |
| return result({}) | |
| if method == "tools/list": | |
| return result({"tools": servers[server]["tools"]}) | |
| if method == "tools/call": | |
| name = params.get("name") | |
| if name not in {t["name"] for t in servers[server]["tools"]}: | |
| return error(-32602, f"Инструмента {name} нет.") | |
| try: | |
| text = desk.call(server, name, params.get("arguments") or {}) | |
| return result({"content": [{"type": "text", "text": text}], "isError": False}) | |
| except ToolError as failure: | |
| return result({"content": [{"type": "text", "text": str(failure)}], "isError": True}) | |
| return error(-32601, f"Метод {method} не поддерживается.") | |
| def make_handler(desk: Desk): | |
| class Handler(BaseHTTPRequestHandler): | |
| protocol_version = "HTTP/1.1" | |
| def _server(self) -> str | None: | |
| name = self.path.split("?")[0].rstrip("/").removeprefix("/mcp/") | |
| return name if name in desk.servers() else None | |
| def _reply(self, status: int, body: bytes = b"", kind: str = "application/json", headers: dict | None = None) -> None: | |
| self.send_response(status) | |
| for key, value in (headers or {}).items(): | |
| self.send_header(key, value) | |
| if body: | |
| self.send_header("Content-Type", kind) | |
| self.send_header("Content-Length", str(len(body))) | |
| self.end_headers() | |
| self.wfile.write(body) | |
| def do_POST(self) -> None: # noqa: N802 | |
| server = self._server() | |
| if server is None: | |
| return self._reply(404, b'{"error":"no such server"}') | |
| try: | |
| payload = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"null") | |
| except ValueError: | |
| return self._reply(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}).encode()) | |
| batch = isinstance(payload, list) | |
| answers = [a for a in (handle(desk, server, m) for m in (payload if batch else [payload])) if a is not None] | |
| headers = {} | |
| if any(isinstance(m, dict) and m.get("method") == "initialize" for m in (payload if batch else [payload])): | |
| headers["Mcp-Session-Id"] = uuid.uuid4().hex | |
| if not answers: | |
| return self._reply(202, headers=headers) | |
| self._reply(200, json.dumps(answers if batch else answers[0], ensure_ascii=False).encode("utf-8"), headers=headers) | |
| def do_GET(self) -> None: # noqa: N802 | |
| # Поток событий от сервера не нужен: уведомлений у этих серверов нет. | |
| self._reply(405, headers={"Allow": "POST, DELETE"}) | |
| def do_DELETE(self) -> None: # noqa: N802 | |
| self._reply(200) | |
| def log_message(self, format: str, *args) -> None: # noqa: A002 | |
| sys.stderr.write(f"{self.command} {self.path} {args[1] if len(args) > 1 else ''}\n") | |
| return Handler | |
| def main(argv: list[str]) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--port", type=int, default=8080) | |
| parser.add_argument("--state", required=True) | |
| parser.add_argument("--time-zone", default="Europe/Moscow") | |
| parser.add_argument("--system", choices=["onec", "jira", "github"]) | |
| args = parser.parse_args(argv[1:]) | |
| desk = Desk(Path(args.state), args.time_zone, args.system) | |
| httpd = ThreadingHTTPServer(("0.0.0.0", args.port), make_handler(desk)) | |
| (Path(args.state) / "ready").write_text("ok", encoding="utf-8") | |
| httpd.serve_forever() | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main(sys.argv)) | |