"""Download and verify a DOKIVO sample result. Python 3, standard library only.""" import argparse import base64 import hashlib import json import os from pathlib import Path import sys import time from urllib.error import HTTPError, URLError from urllib.request import build_opener, HTTPRedirectHandler, Request from uuid import UUID SITE = "https://dokivo.ru" MCP = SITE + "/mcp" SOURCE = SITE + "/qa/editor-sample.pdf" DEMO = SITE + "/examples/verified/mcp/" class NoRedirect(HTTPRedirectHandler): def redirect_request(self, *args): return None http = build_opener(NoRedirect()) def fetch(url, headers=None, payload=None): data = json.dumps(payload).encode() if payload is not None else None req = Request(url, data=data, headers=headers or {}) with http.open(req, timeout=30) as response: return response.read(), response.headers def checked_hash(data, result): digest = hashlib.sha256(data).hexdigest() if len(data) != result["size"] or digest != result["sha256"]: raise ValueError("Размер или SHA-256 расходятся с метаданными результата.") return digest def run_with_mcp(key, request_id): headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"} auth = {"Authorization": "Bearer " + key} sequence = 0 def rpc(method, params): nonlocal sequence sequence += 1 raw, received = fetch(MCP, headers, {"jsonrpc": "2.0", "id": sequence, "method": method, "params": params}) message = json.loads(raw) if message.get("id") != sequence or "error" in message: raise ValueError("Ошибка JSON-RPC при вызове " + method) return message["result"], received def tool(name, args): reply, _ = rpc("tools/call", {"name": name, "arguments": args}) if reply.get("isError"): raise ValueError(reply["content"][0]["text"]) return json.loads(reply["content"][0]["text"]) hello, received = rpc("initialize", {"protocolVersion": "2025-11-25", "capabilities": {}, "clientInfo": {"name": "dokivo-file-example", "version": "1"}}) headers["MCP-Protocol-Version"] = hello["protocolVersion"] if received.get("Mcp-Session-Id"): headers["Mcp-Session-Id"] = received["Mcp-Session-Id"] fetch(MCP, headers, {"jsonrpc": "2.0", "method": "notifications/initialized"}) catalog, _ = rpc("tools/list", {}) required = {"dokivo_create_run", "dokivo_get_run", "dokivo_get_result"} if not required.issubset(item["name"] for item in catalog["tools"]): raise ValueError("В каталоге MCP отсутствует нужный инструмент.") source, _ = fetch(SOURCE) headers.update(auth) created = tool("dokivo_create_run", { "operation": "compress-pdf", "options": {"compression": "balanced"}, "files": [{"name": "sample.pdf", "mimeType": "application/pdf", "contentBase64": base64.b64encode(source).decode("ascii")}], "idempotencyKey": "verify-pdf-" + str(request_id), }) run_id = str(UUID(created["runId"])) args = {"runId": run_id} deadline = time.monotonic() + 180 while time.monotonic() < deadline: state = tool("dokivo_get_run", args)["run"]["state"] if state == "succeeded": break if state not in {"queued", "running"}: raise ValueError("Состояние запуска: " + state) time.sleep(2) else: raise ValueError("Истекло время ожидания. Повторите с тем же идентификатором.") reply = tool("dokivo_get_result", args) result = reply["result"] expected_url = SITE + "/api/v1/runs/" + run_id + "/artifacts/result" if reply["runId"] != run_id or not result["available"] or result["downloadUrl"] != expected_url: raise ValueError("Ссылка на доступный результат этого запуска не подтверждена.") data, _ = fetch(result["downloadUrl"], auth) return data, result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--run", type=UUID, metavar="UUID", help="Process the sample with your DOKIVO_API_KEY") parser.add_argument("--output", type=Path, help="Write verified bytes to a new PDF file") args = parser.parse_args() if args.run: key = os.environ.get("DOKIVO_API_KEY") if not key: parser.error("--run requires DOKIVO_API_KEY") data, result = run_with_mcp(key, args.run) else: raw, _ = fetch(DEMO + "receipt.json") result = json.loads(raw)["result"] if result["publicCopy"] != DEMO + "accepted-result.pdf": raise ValueError("Неожиданный адрес учебного файла.") data, _ = fetch(result["publicCopy"]) digest = checked_hash(data, result) if args.output: with args.output.open("xb") as stream: stream.write(data) print(f"OK {len(data)} bytes SHA-256 {digest}") if __name__ == "__main__": try: main() except (HTTPError, URLError, OSError, TimeoutError, ValueError, KeyError) as error: sys.exit(str(error))