"""A stand-in specialist, built only from kovrex.ai/for-specialists.md. It exists to test that guide the way a specialist's builders will meet it: as people who have the document and nothing else. It shares no code with Kovrex. What it does: 1. Makes an Ed25519 key on first start and keeps it on disk. 2. Serves an Agent Card that carries the public key. 3. Registers itself with Kovrex once, when CONTACT_EMAIL is set. 4. Polls its registration, and shows where it stands on its front page. 5. Refuses every other request unless it carries a valid token from Kovrex. 6. Answers conversations as section 6 of the guide describes, as A2A over JSON-RPC, keeping its tasks in memory: - SendMessage: one JSON reply holding a completed task. The answer is "Echo: " and then which message this is from this client, counted per client_id. - SendStreamingMessage: an event stream: working, the same answer in three or four pieces a moment apart, then completed. - The text "ask" on a new task: it asks "What should I repeat?" and waits (input required). The next message on that task is echoed and completes it. - The text "fail": a JSON-RPC error, to show a refusal carried through. - The text "long" on a new task: it answers that this will take a while (section 9 of the guide): a task in the working state marked deferred, with an estimate, and ends the stream or returns. After LONG_DELAY seconds it posts a progress note and then the result, a text and a small file, to the return address Kovrex put in the request, with the token Kovrex put there. - The text "never": the same deferral, and nothing is ever delivered, so Kovrex ends the job at its deadline and sends CancelTask. - The text "metrics": the normal echo, with run metrics (section 10 of the guide) in the metadata of the final status or task: version, model, tokens, time, cost and two parts. "long metrics" is "long" with the metrics on the delivered result. "bad metrics" reports figures of the wrong types, and "huge metrics" a report far too large: Kovrex must drop both and still carry the answer. Kovrex passes none of it on. - The text "no": a refusal as section 9 describes, the rejected state with a reason. - GetTask and CancelTask over the tasks it holds (Kovrex does not send GetTask). - Any other method: a JSON-RPC error. It logs one line per request: the method, Kovrex's request ID, and the outcome. Never message text, headers, or tokens. 7. Uses Kovrex's two memory tools as section 7 of the guide describes, by plain HTTP to KOVREX_URL/mcp, each call signed with a fresh token from its own key and given 10 seconds: - A new message starting "remember:" calls propose_memory with the rest of the text, this client's ID, and Echo's own contextId. The answer says it has asked, and that the client must keep it before it is remembered. - A new message that is exactly "what do you remember" (a question mark is allowed) calls recall and answers with what the client has kept, marking any memory the client corrected. - Any other message that starts a conversation (no contextId) calls recall first, as "Using memory well" in section 7 advises, and the echo ends by saying how many things Echo remembers about the client, if any. If recall fails, the echo is given without it. Echo does not keep what it recalled. - Echo keeps its own list of what it has asked to remember for each client, and does not ask for the same thing twice: Kovrex has no call that lists a specialist's suggestions that are still waiting. - If Kovrex refuses or cannot be reached, Echo still completes the task and its answer says what went wrong. - No other message calls a tool. An answer to Echo's own question ("ask") is echoed as before, whatever it says. 8. Takes and sends files as section 8 of the guide describes: - The card declares text, PDF and PNG in its skill's inputModes, so Kovrex sends it those, once Kovrex has read the card again (see refresh_card). - A message with a file arrives with an address in place of the bytes. Echo reads it with a signed GET (only at Kovrex's own /v1/files/ address), checks the SHA-256 against the part's metadata and the X-Content-SHA256 header, and answers with the file's name, type and size. - The text "file" is answered with a small text file in a raw part. - Once its listing is open, it asks Kovrex to read its card again at each start (POST /v1/card/refresh), so the file types above are known. It logs one more line per tool call: the tool's name, Kovrex's request ID for the message that caused it, and the outcome (ok and a count, refused, or unreachable). Never the memory text. Settings, all from the environment: PUBLIC_URL where this service is reachable, e.g. https://x.up.railway.app CONTACT_NAME the person at the publisher who will confirm CONTACT_EMAIL their email. Registration does not start until this is set. KOVREX_URL default https://kovrex.ai PUBLISHER_NAME default "Kovrex Test" PUBLISHER_SLUG default "kovrex-test" SPECIALIST_SLUG default "echo" DOCUMENTATION_URL optional: a link to the publisher's own page, put on the card as documentationUrl. Kovrex shows it only if it is https and on the publisher's own domain; unset, the card names none. DATA_DIR where the key and state are kept. Default ./data PORT default 8080 LONG_DELAY seconds before "long" delivers its result. Default 5 """ import base64 import hashlib import html import http.client import json import math import os import re import socket import threading import time import urllib.error import urllib.request import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey KOVREX_URL = os.environ.get("KOVREX_URL", "https://kovrex.ai").rstrip("/") PUBLIC_URL = os.environ.get("PUBLIC_URL", "").rstrip("/") PUBLISHER_NAME = os.environ.get("PUBLISHER_NAME", "Kovrex Test") PUBLISHER_SLUG = os.environ.get("PUBLISHER_SLUG", "kovrex-test") SPECIALIST_SLUG = os.environ.get("SPECIALIST_SLUG", "echo") CONTACT_NAME = os.environ.get("CONTACT_NAME", "").strip() CONTACT_EMAIL = os.environ.get("CONTACT_EMAIL", "").strip() DATA_DIR = Path(os.environ.get("DATA_DIR", "./data")) PORT = int(os.environ.get("PORT", "8080")) LONG_DELAY = float(os.environ.get("LONG_DELAY", "5")) # A link to the publisher's own page, shown on Echo's page if it is on Echo's own # domain (see "A link to your own page" in the guide). Echo has none by default. DOCUMENTATION_URL = os.environ.get("DOCUMENTATION_URL", "").strip() ADDRESS = f"{PUBLISHER_SLUG}/{SPECIALIST_SLUG}" EXTENSION = "https://kovrex.ai/ext/registration/v1" TERMS = ( "Echo is a test specialist run by Kovrex. It repeats what it is sent and gives no " "advice of any kind.\n\nIt keeps nothing about a client beyond what Kovrex holds." ) # --- base64url, as the guide writes it: no padding --------------------------- def b64(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def unb64(text: str) -> bytes: return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) # --- section 1 of the guide: the key ------------------------------------------ def load_key() -> Ed25519PrivateKey: """Make the key once and keep it. The private half never leaves this disk.""" DATA_DIR.mkdir(parents=True, exist_ok=True) path = DATA_DIR / "key" if path.exists(): return Ed25519PrivateKey.from_private_bytes(unb64(path.read_text().strip())) key = Ed25519PrivateKey.generate() raw = key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption() ) path.touch(mode=0o600) path.write_text(b64(raw)) return key def public_key(key: Ed25519PrivateKey) -> str: raw = key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) return b64(raw) KEY = load_key() PUBLIC_KEY = public_key(KEY) # --- section 2 of the guide: the Agent Card ----------------------------------- CARD = { "name": "Echo", "description": "A test specialist run by Kovrex. It repeats what it is sent.", "version": "0.1.0", "capabilities": { "streaming": True, "extensions": [{"uri": EXTENSION, "params": {"public_key": PUBLIC_KEY}}], }, "skills": [ { "id": "echo", "name": "Echo a message", "description": "Sends back what it was sent.", "tags": ["test"], # Section 8: the file types Echo supports, declared in its skill. # Kovrex refuses any other file before it reaches Echo. "inputModes": ["text/plain", "application/pdf", "image/png"], } ], "defaultInputModes": ["text/plain"], "defaultOutputModes": ["text/plain"], } if DOCUMENTATION_URL: CARD["documentationUrl"] = DOCUMENTATION_URL # --- "Signing a call" in the guide ---------------------------------------------- def token() -> str: now = int(time.time()) header = {"alg": "EdDSA", "typ": "JWT", "kid": PUBLIC_KEY} claims = {"aud": KOVREX_URL, "iat": now, "exp": now + 300, "jti": str(uuid.uuid4())} signed = b64(json.dumps(header).encode()) + "." + b64(json.dumps(claims).encode()) return signed + "." + b64(KEY.sign(signed.encode())) def call(method: str, path: str, body=None, signed=False): """One call to Kovrex. Returns (status, parsed JSON or an error description).""" request = urllib.request.Request(KOVREX_URL + path, method=method) request.add_header("Content-Type", "application/json") request.add_header("User-Agent", "Kovrex-Stand-In-Specialist/1") if signed: request.add_header("Authorization", "Bearer " + token()) data = json.dumps(body).encode() if body is not None else None try: with urllib.request.urlopen(request, data=data, timeout=30) as response: return response.status, json.loads(response.read()) except urllib.error.HTTPError as error: try: return error.code, json.loads(error.read()) except ValueError: return error.code, {"error": {"code": "unreadable", "message": "not JSON"}} except (urllib.error.URLError, TimeoutError, ValueError) as error: return 0, {"error": {"code": "unreachable", "message": str(error)}} # --- sections 3 and 5 of the guide: register once, then poll -------------------- STATE_PATH = DATA_DIR / "state.json" STATE_LOCK = threading.Lock() def read_state() -> dict: try: return json.loads(STATE_PATH.read_text()) except (OSError, ValueError): return {} def write_state(state: dict) -> None: with STATE_LOCK: STATE_PATH.write_text(json.dumps(state, indent=2)) def registration_request() -> dict: return { "publisher": {"name": PUBLISHER_NAME, "slug": PUBLISHER_SLUG}, "contact": {"name": CONTACT_NAME or "Kovrex", "email": CONTACT_EMAIL}, "specialist": {"slug": SPECIALIST_SLUG, "a2a_url": PUBLIC_URL, "public_key": PUBLIC_KEY}, "settings": { # Nothing is free: a specialist asks for the minimum, and Kovrex # marks Echo free itself. "passes": [{"unit": "month", "amount_cents": 5000, "currency": "usd"}], "memory": {"days": 30, "held_by": "kovrex"}, "access": "open", "listed": False, }, "terms": TERMS, } def register_and_watch() -> None: """Register once. Never retry on its own: each try emails a person.""" state = read_state() if "id" not in state: if not CONTACT_EMAIL or not PUBLIC_URL: state["note"] = "Waiting: set CONTACT_EMAIL and PUBLIC_URL to register." write_state(state) return # Each try emails a person, and Kovrex allows three an hour for one # address. So after a refusal, wait an hour before trying again, and # only try on a restart. if time.time() - state.get("attempted_at", 0) < 3600: write_state(state) return # Wait until this service answers on its public address, since Kovrex # fetches the card from there the moment the request arrives. time.sleep(float(os.environ.get("REGISTER_DELAY", "20"))) status, reply = call("POST", "/v1/registrations", registration_request()) state["attempted_at"] = int(time.time()) if status != 201: state["note"] = ( f"Registration refused ({status}): {json.dumps(reply.get('error', reply))}. " "It will be tried again on a restart, an hour or more from now." ) write_state(state) return state.update( id=reply["id"], code=reply["code"], status=reply["status"], expires_at=reply["expires_at"], address=reply["specialist"], email_sent=reply.get("email_sent"), note="Registered. Waiting for the contact to confirm.", ) write_state(state) # "Poll no more than once a minute." while state.get("status") in ("pending", "confirmed"): time.sleep(float(os.environ.get("POLL_SECONDS", "60"))) status, reply = call("GET", f"/v1/registrations/{state['id']}", signed=True) state["checked_at"] = int(time.time()) if status == 200: state["status"] = reply["status"] state["note"] = { "pending": "Waiting for the contact to confirm.", "confirmed": "Confirmed. Waiting for Kovrex to approve.", "open": "Open. Clients can connect.", "declined": "The contact declined. Nothing was listed.", "expired": "Expired with no answer.", }.get(reply["status"], reply["status"]) else: state["note"] = f"Status check failed ({status}): {json.dumps(reply.get('error', reply))}" write_state(state) def refresh_card() -> None: """Section 8: once the listing is open, ask Kovrex to read the card again, so a change to it (the file types Echo takes) is known. Done once at each start, after the server is up to be fetched from; Kovrex allows it once a minute.""" time.sleep(float(os.environ.get("REFRESH_AFTER_SECONDS", "5"))) if read_state().get("status") != "open": return status, reply = call("POST", "/v1/card/refresh", signed=True) if status == 200: print(f"card refresh -> read again, takes {', '.join(reply.get('accepts_files', [])) or 'no files'}", flush=True) else: print(f"card refresh -> {status} {plain(reply.get('error', {}).get('code', ''), 40)}", flush=True) # --- "Knowing a request is from Kovrex" in the guide ---------------------------- class KovrexKeys: """Kovrex's published keys: cached for an hour, refetched for an unknown kid at most once a minute.""" def __init__(self): self.keys = {} self.fetched_at = 0.0 self.lock = threading.Lock() def fetch(self) -> None: try: with urllib.request.urlopen(KOVREX_URL + "/.well-known/jwks.json", timeout=10) as response: document = json.loads(response.read()) self.keys = { key["kid"]: key["x"] for key in document["keys"] if key.get("kty") == "OKP" and key.get("crv") == "Ed25519" } except (urllib.error.URLError, TimeoutError, ValueError, KeyError): pass # keep what we had self.fetched_at = time.time() def get(self, kid: str): with self.lock: age = time.time() - self.fetched_at if age > 3600 or (kid not in self.keys and age > 60): self.fetch() return self.keys.get(kid) KOVREX_KEYS = KovrexKeys() SEEN = {} # jti -> exp SEEN_LOCK = threading.Lock() def from_kovrex(token_text: str, body: bytes, now: int, keys=KOVREX_KEYS, address=ADDRESS) -> bool: """The eight checks in the guide. True only if every one passes.""" try: header_part, claims_part, signature_part = token_text.split(".") header = json.loads(unb64(header_part)) claims = json.loads(unb64(claims_part)) if header["alg"] != "EdDSA": return False x = keys.get(header["kid"]) # the key comes from Kovrex's document, never the token if x is None: return False Ed25519PublicKey.from_public_bytes(unb64(x)).verify( unb64(signature_part), f"{header_part}.{claims_part}".encode() ) ok = ( claims["iss"] == KOVREX_URL and claims["aud"] == f"{KOVREX_URL}/{address}" and claims["exp"] > now and claims["iat"] <= now + 30 and 0 < claims["exp"] - claims["iat"] <= 300 and claims["body_sha256"] == b64(hashlib.sha256(body).digest()) ) if not ok: return False with SEEN_LOCK: for jti in [jti for jti, exp in SEEN.items() if exp <= now]: del SEEN[jti] if claims["jti"] in SEEN: return False SEEN[claims["jti"]] = claims["exp"] return True except (ValueError, KeyError, TypeError, InvalidSignature): return False # --- section 6 of the guide: conversations ------------------------------------- CLIENT_EXTENSION = "https://kovrex.ai/ext/client/v1" DEFERRED = "https://kovrex.ai/ext/deferred/v1" RUN = "https://kovrex.ai/ext/run/v1" WORKING = "TASK_STATE_WORKING" INPUT_REQUIRED = "TASK_STATE_INPUT_REQUIRED" COMPLETED = "TASK_STATE_COMPLETED" CANCELED = "TASK_STATE_CANCELED" REJECTED = "TASK_STATE_REJECTED" FINISHED = (COMPLETED, CANCELED, "TASK_STATE_FAILED", "TASK_STATE_REJECTED") METHODS = ("SendMessage", "SendStreamingMessage", "GetTask", "CancelTask") PAUSE = float(os.environ.get("STREAM_PAUSE", "0.3")) # between the events of a stream MAX_TASKS = 10_000 # All in memory, and all lost on a restart. Echo is a test. TASKS = {} # Echo's task ID -> {"id", "contextId", "client_id", "state", "text", "question"} CONTEXTS = {} # Echo's context ID -> the client_id it belongs to COUNTS = {} # client_id -> how many messages that client has sent SUGGESTED = {} # client_id -> what Echo has asked to remember, as plain lower-case text TALK_LOCK = threading.Lock() class Refusal(Exception): """Answered as a JSON-RPC error, as in "Saying no".""" def __init__(self, code: int, message: str): super().__init__(message) self.code = code self.message = message def agent_message(context_id: str, text: str) -> dict: return { "messageId": f"echo-msg-{uuid.uuid4().hex}", "contextId": context_id, "role": "ROLE_AGENT", "parts": [{"text": text}], } def deferral_mark() -> dict: """What Echo says when it answers later: the mark, an estimate and a maximum.""" return { "deferred": True, "expected_seconds": max(1, int(LONG_DELAY * 3)), "maximum_seconds": 600, "note": "Echo is taking its time, on purpose.", } def run_metrics(kind: str) -> dict: """What Echo reports an answer cost (section 10 of the guide). Made up.""" if kind == "bad": # every figure the wrong type or out of range return {"version": 7, "model": ["x"], "input_tokens": "lots", "output_tokens": -5, "duration_ms": 1.5, "cost_usd": "free", "parts": "none", "mystery": True} if kind == "huge": # far over the size Kovrex keeps return {"version": "v" * 5000, "model": "echo-model", "input_tokens": 10, "notes": "x" * 40_000} return { "version": "echo-1", "model": "echo-model", "input_tokens": 120, "output_tokens": 80, "duration_ms": 1500, "cost_usd": 0.0004, "parts": [ {"name": "read", "input_tokens": 120, "output_tokens": 10, "duration_ms": 300}, {"name": "answer", "input_tokens": 0, "output_tokens": 70, "duration_ms": 1200}, ], } def task_view(task: dict) -> dict: """A task as the guide shows it. Call with TALK_LOCK held.""" status = {"state": task["state"]} if task["state"] == INPUT_REQUIRED and task.get("question"): status["message"] = task["question"] if task["state"] == REJECTED and task.get("reason"): status["message"] = task["reason"] view = {"id": task["id"], "contextId": task["contextId"], "status": status} if task.get("deferred") and task["state"] == WORKING: # Section 9: a task in the working state, marked as deferred. status["message"] = agent_message(task["contextId"], "This will take a while.") view["metadata"] = {DEFERRED: deferral_mark()} if task.get("metrics") and task["state"] == COMPLETED: view.setdefault("metadata", {})[RUN] = run_metrics(task["metrics"]) artifacts = [] if task["text"]: artifacts.append({"artifactId": "answer", "parts": [{"text": task["text"]}]}) if task.get("file") and task["state"] == COMPLETED: artifacts.append({"artifactId": "file", "parts": [task["file"]]}) if artifacts: view["artifacts"] = artifacts return view # --- section 8 of the guide: files --------------------------------------------- FILE_PREFIX = KOVREX_URL + "/v1/files/" FILE_LIMIT = 30_000_000 # a little over the 25 MB Kovrex allows one file def file_to_send() -> dict: """The small text file Echo sends when it is asked for "file": a part that holds the bytes in base64, with a filename and a mediaType.""" data = b"Echo was asked for a file, and this is it.\n" return {"raw": base64.b64encode(data).decode(), "filename": "echo.txt", "mediaType": "text/plain"} def read_file(part: dict, request_id: str) -> str: """Read one file Kovrex sent, with a signed GET, and say what it was. Echo fetches only Kovrex's own address, whatever the part says.""" url = part.get("url") name = plain(part.get("filename") or "a file", 80) expected = (part.get("metadata") or {}).get("sha256") if not isinstance(url, str) or not url.startswith(FILE_PREFIX): return f"{name}: not one of Kovrex's file addresses, so Echo did not fetch it." request = urllib.request.Request(url, method="GET") request.add_header("Authorization", "Bearer " + token()) request.add_header("User-Agent", "Kovrex-Stand-In-Specialist/1") try: with urllib.request.urlopen(request, timeout=TOOL_TIMEOUT) as response: data = response.read(FILE_LIMIT + 1) sent_hash = response.headers.get("X-Content-SHA256", "") media_type = response.headers.get("Content-Type", "") except urllib.error.HTTPError as error: print(f"file {request_id} -> refused {error.code}", flush=True) return f"{name}: Kovrex answered {error.code}, so Echo could not read it." except (urllib.error.URLError, TimeoutError, OSError): print(f"file {request_id} -> unreachable", flush=True) return f"{name}: Echo could not reach Kovrex to read it." if len(data) > FILE_LIMIT: return f"{name}: larger than Echo reads." actual = hashlib.sha256(data).hexdigest() checked = actual == expected and actual == sent_hash print(f"file {request_id} -> read, {'sha256 ok' if checked else 'sha256 does not match'}", flush=True) kind = plain(media_type.split(";")[0], 80) verdict = "SHA-256 checked" if checked else "SHA-256 does NOT match" return f"{name} ({kind}, {len(data)} bytes, {verdict})" def files_answer(text: str, number: int, parts: list, request_id: str) -> str: read = "; ".join(read_file(part, request_id) for part in parts) return f"Echo: {text} This is message {number} from this client. Received: {read}." # --- section 9 of the guide: long-running tasks --------------------------------- DELIVERY_PREFIX = KOVREX_URL + "/v1/deliveries/" class Defer: """accept_message returns this in place of an answer when Echo answers later.""" DEFER = Defer() class Reject: """accept_message returns this in place of an answer when Echo says no.""" REJECT = Reject() def return_address(params) -> dict: """The return address and token Kovrex put in the request (section 9). Kept with the task, if Echo defers it, and used for nothing else. Echo posts only to an address on Kovrex's own site, whatever the request says.""" configuration = params.get("configuration") if isinstance(params, dict) else None push = None if isinstance(configuration, dict): push = configuration.get("taskPushNotificationConfig") or configuration.get("pushNotificationConfig") if not isinstance(push, dict): return {} url, token_text = push.get("url"), push.get("token") if not isinstance(url, str) or not url.startswith(DELIVERY_PREFIX) or not isinstance(token_text, str): return {} return {"url": url, "token": token_text} def post_event(push: dict, event: dict, request_id: str, what: str) -> bool: """Post one event to the return address, with the token in the header A2A libraries use. Retries a few times with a growing pause on anything that may pass: the job may not be open yet (401), Kovrex may be busy (429, 503), or restarting. Stops at once on 410 (the job ended) and 400/422. Never logs the token or what was sent.""" body = json.dumps(event).encode() for attempt in range(5): request = urllib.request.Request(push["url"], method="POST", data=body) request.add_header("Content-Type", "application/json") request.add_header("A2A-Notification-Token", push["token"]) request.add_header("User-Agent", "Kovrex-Stand-In-Specialist/1") try: with urllib.request.urlopen(request, timeout=30) as response: print(f"delivery {request_id} -> {what}, {response.status}", flush=True) return True except urllib.error.HTTPError as error: print(f"delivery {request_id} -> {what}, refused {error.code}", flush=True) if error.code in (400, 410, 422): return False except (urllib.error.URLError, TimeoutError, OSError): print(f"delivery {request_id} -> {what}, unreachable", flush=True) time.sleep(1 + attempt) return False def deliver_later(task: dict, request_id: str) -> None: """Echo's "long": after LONG_DELAY seconds, a progress note and then the result, a text and a small file, posted to Kovrex. Stops if the task is cancelled or Kovrex says the job has ended.""" push = task.get("push") if not push: print(f"delivery {request_id} -> no return address in the request", flush=True) return task_id, context_id = task["id"], task["contextId"] time.sleep(LONG_DELAY / 2) with TALK_LOCK: if task["state"] != WORKING: return progress = {"statusUpdate": {"taskId": task_id, "contextId": context_id, "status": { "state": WORKING, "message": agent_message(context_id, "Halfway there.")}}} if not post_event(push, progress, request_id, "progress"): return time.sleep(LONG_DELAY / 2) with TALK_LOCK: if task["state"] != WORKING: return task["text"] = task["answer"] task["file"] = file_to_send() task["state"] = COMPLETED view = task_view(task) post_event(push, {"task": view}, request_id, "result") def accept_message(params) -> tuple: """Take in one message. Returns (task, answer), where answer is None if Echo asked a question instead. The task is left working, or waiting for input. For a message that uses memory, answer is a function instead: call it with Kovrex's request ID, outside TALK_LOCK, and it calls the tool and returns the answer's text.""" message = params.get("message") if isinstance(params, dict) else None try: parts = message["parts"] # A part is text, or a file: an address, with its name, type, size and # SHA-256 (section 8). A message may be only files. text = "".join(part["text"] for part in parts if "text" in part) files = [part for part in parts if "url" in part] client_id = message["metadata"][CLIENT_EXTENSION]["client_id"] if not parts or not isinstance(client_id, str) or not client_id: raise ValueError task_id, context_id = message.get("taskId"), message.get("contextId") except (KeyError, TypeError, ValueError, AttributeError): raise Refusal(-32602, "Echo could not read that message: it needs text or file parts and a client ID.") word = text.strip().lower() with TALK_LOCK: COUNTS[client_id] = number = COUNTS.get(client_id, 0) + 1 if word == "fail": raise Refusal(-32004, "Echo was asked to fail, so it refused this message.") answer = f"Echo: {text} This is message {number} from this client." if files: # Fetching takes the network, so it happens later, not while # holding the lock. answer = lambda request_id: files_answer(text, number, files, request_id) if task_id is not None: # Kovrex is continuing a task Echo started, with Echo's own ID. task = TASKS.get(task_id) if task is None or task["client_id"] != client_id: raise Refusal(-32001, "Echo has no such task.") if task["state"] != INPUT_REQUIRED: raise Refusal(-32602, "That task is not waiting for an answer. Send a new message without its task ID.") task["state"] = WORKING task["question"] = None return task, answer starts_conversation = context_id is None if starts_conversation: context_id = f"echo-conversation-{uuid.uuid4().hex}" elif not isinstance(context_id, str) or CONTEXTS.get(context_id, client_id) != client_id: raise Refusal(-32602, "Echo has no such conversation for this client.") # A context ID Echo no longer knows (it forgets on a restart) is taken # up again as it is, so the conversation carries on. CONTEXTS[context_id] = client_id while len(TASKS) >= MAX_TASKS: del TASKS[next(iter(TASKS))] task = { "id": f"echo-task-{uuid.uuid4().hex}", "contextId": context_id, "client_id": client_id, "state": WORKING, "text": "", "question": None, } TASKS[task["id"]] = task if word == "ask": task["state"] = INPUT_REQUIRED task["question"] = agent_message(context_id, "What should I repeat?") return task, None if word == "file": task["file"] = file_to_send() kind = {"metrics": "good", "long metrics": "good", "bad metrics": "bad", "huge metrics": "huge"}.get(word) if kind: task["metrics"] = kind if word == "long metrics": word = "long" if word in ("long", "never"): # Section 9: answer later. The return address is kept with the task. task["deferred"] = word task["push"] = return_address(params) task["answer"] = f"Echo: {text} This is message {number} from this client. It took a while." return task, DEFER if word == "no": # Section 9, "Saying no to a job": the rejected state, with the reason. task["state"] = REJECTED task["reason"] = agent_message( context_id, "Echo does not take this on. Ask again, or send something else." ) return task, REJECT command = memory_command(text) if command is not None: # Section 7. The tool is called later, not while holding the lock. return task, lambda request_id: memory_answer(command, client_id, context_id, request_id) if starts_conversation: # Section 7, "Using memory well": recall when a conversation starts. return task, lambda request_id: with_memories(answer, client_id, request_id) return task, answer # --- section 7 of the guide: memory --------------------------------------------- TOOL_TIMEOUT = 10 # seconds, well inside the 30 Kovrex gives a stream to begin TOOL_REPLY_LIMIT = 4_000_000 def plain(value, limit: int = 300) -> str: """Kovrex's own words, on one line and cut short, to put in an answer.""" text = " ".join(str(value).split()) return text if len(text) <= limit else text[:limit - 1] + "…" def tool_reply(name: str, arguments: dict) -> tuple: """One tools/call. Returns (structured answer or None, problem or None, outcome for the log).""" body = json.dumps({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": arguments}, }).encode() request = urllib.request.Request(KOVREX_URL + "/mcp", data=body, method="POST") request.add_header("Authorization", "Bearer " + token()) # a fresh one every call request.add_header("Content-Type", "application/json") request.add_header("Accept", "application/json, text/event-stream") request.add_header("MCP-Protocol-Version", "2025-11-25") request.add_header("User-Agent", "Kovrex-Stand-In-Specialist/1") try: with urllib.request.urlopen(request, timeout=TOOL_TIMEOUT) as response: status, raw = response.status, response.read(TOOL_REPLY_LIMIT + 1) except urllib.error.HTTPError as error: status, raw = error.code, b"" except (OSError, http.client.HTTPException): return None, "Kovrex could not be reached.", "unreachable" if status != 200: problem = { 401: "Kovrex did not accept Echo's token.", 429: "Echo has called Kovrex too many times in the last minute.", 503: "Kovrex cannot read or store memories right now.", }.get(status, f"Kovrex answered with status {status}.") return None, problem, f"refused, {status}" unreadable = (None, "Kovrex's answer could not be read.", "refused, unreadable answer") try: reply = json.loads(raw) if "error" in reply: # a JSON-RPC error, such as "tool not found" code = reply["error"].get("code") said = plain(reply["error"].get("message") or "no reason given") return None, f"Kovrex said: {said}", f"refused, error {code if isinstance(code, int) else '?'}" result = reply["result"] if result.get("isError"): # the tool refused, and says why as text content = result.get("content") or [{}] said = plain(content[0].get("text") or "no reason given") return None, f"Kovrex said: {said}", "refused" structured = result["structuredContent"] if not isinstance(structured, dict): return unreadable count = 1 if "memories" in structured: memories = structured["memories"] if not isinstance(memories, list) or not all( isinstance(memory, dict) and isinstance(memory.get("text"), str) for memory in memories ): return unreadable count = len(memories) return structured, None, f"ok, {count}" except (ValueError, KeyError, TypeError, AttributeError, IndexError): return unreadable def call_tool(name: str, arguments: dict, request_id: str = "-") -> tuple: """Call one of Kovrex's tools. Returns (structured answer, None), or (None, what went wrong in plain words). Never raises.""" try: structured, problem, outcome = tool_reply(name, arguments) except Exception: # whatever happens, the conversation carries on structured, problem, outcome = None, "Echo could not call Kovrex.", "unreachable" # The tool, the request it was for, and the outcome. Never the memory text. print(f"tool {name} {request_id} -> {outcome}", flush=True) return structured, problem def memory_command(text: str): """("propose", the text to remember), ("recall", None), or None.""" start = text.lstrip() if start[:9].lower() == "remember:": return "propose", start[9:].strip() word = text.strip().lower() if word.endswith("?"): word = word[:-1].rstrip() if word == "what do you remember": return "recall", None return None def memory_answer(command: tuple, client_id: str, context_id: str, request_id: str) -> str: """Call the tool the message asked for, and say what came of it.""" kind, text = command if kind == "propose": # Kovrex cannot list Echo's waiting suggestions, so Echo keeps its own list. same = " ".join(text.split()).lower() with TALK_LOCK: if same in SUGGESTED.get(client_id, set()): return "I have already asked to remember that, so I have not asked again." arguments = {"client_id": client_id, "text": text, "context_id": context_id} _, problem = call_tool("propose_memory", arguments, request_id) if problem: return f"I could not ask to remember that. {problem}" with TALK_LOCK: SUGGESTED.setdefault(client_id, set()).add(same) return "I have asked to remember that. It is not remembered yet: you must keep it first." structured, problem = call_tool("recall", {"client_id": client_id}, request_id) if problem: return f"I could not look up what I remember about you. {problem}" memories = structured.get("memories", []) if not memories: return "I remember nothing about you yet." lines = [f"I remember {len(memories)} thing{'' if len(memories) == 1 else 's'} about you:"] for memory in memories: # corrected: the client replaced Echo's wording with their own. lines.append(memory["text"] + (" (you corrected this)" if memory.get("corrected") is True else "")) return "\n".join(lines) def with_memories(answer: str, client_id: str, request_id: str) -> str: """The echo at the start of a conversation, after asking what the client has kept. If recall fails, the echo is given without it. What was recalled is used for this answer only, and not kept. `answer` may itself be a function that makes the text (a message with files reads them first).""" if callable(answer): answer = answer(request_id) structured, problem = call_tool("recall", {"client_id": client_id}, request_id) count = 0 if problem else len(structured.get("memories", [])) if count == 0: return answer return f"{answer} I remember {count} thing{'' if count == 1 else 's'} about you." def pieces(answer: str) -> list: """The answer in three or four pieces that join back to exactly the answer.""" words = answer.split(" ") size = math.ceil(len(words) / 4) groups = [" ".join(words[i:i + size]) for i in range(0, len(words), size)] return [group + " " for group in groups[:-1]] + groups[-1:] def find_task(params) -> dict: """For GetTask and CancelTask. Call with TALK_LOCK held.""" task_id = params.get("id") if isinstance(params, dict) else None if not isinstance(task_id, str): raise Refusal(-32602, "Echo needs the task's ID.") task = TASKS.get(task_id) if task is None: raise Refusal(-32001, "Echo has no such task.") return task def get_task(params) -> dict: with TALK_LOCK: return task_view(find_task(params)) def cancel_task(params) -> dict: with TALK_LOCK: task = find_task(params) if task["state"] in FINISHED: raise Refusal(-32002, "That task has already finished, so it cannot be cancelled.") task["state"] = CANCELED task["question"] = None return task_view(task) # --- the web server ------------------------------------------------------------- def front_page() -> bytes: state = read_state() rows = [ ("Specialist", "Echo"), ("Address on Kovrex", f"kovrex.ai/{ADDRESS}"), ("Public key", PUBLIC_KEY), ("Registration", state.get("status", "not registered")), ("Code to type on the Confirm page", state.get("code", "none yet")), ("Where it stands", state.get("note", "")), ] cells = "".join( f"{html.escape(name)}{html.escape(str(value))}" for name, value in rows ) page = f"""Echo, a stand-in specialist

Echo

A stand-in specialist that tests Kovrex's registration guide. Not a real service.

{cells}
""" return page.replace("Code to compare", 'Code to compare').encode() class Handler(BaseHTTPRequestHandler): server_version = "StandInSpecialist/1" def send(self, status: int, content_type: str, body: bytes) -> None: self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body) def json(self, status: int, value) -> None: self.send(status, "application/json", json.dumps(value).encode()) def do_GET(self): self.quiet = False path = self.path.split("?")[0] # The card is public. So are the health check and this test's own # front page, which shows nothing private. if path == "/.well-known/agent-card.json": return self.json(200, CARD) if path == "/healthz": return self.send(200, "text/plain", b"ok") if path == "/": return self.send(200, "text/html; charset=utf-8", front_page()) self.answer_kovrex(b"") def do_POST(self): length = int(self.headers.get("Content-Length") or 0) if length > 1_000_000: return self.json(413, {"error": "too large"}) # Hash the body as it arrived, before parsing it. self.answer_kovrex(self.rfile.read(length)) def answer_kovrex(self, body: bytes) -> None: """Everything but the card: 401 without a valid token from Kovrex.""" self.quiet = True # one line per request, written here # Kovrex's ID for this request, cut down to what such an ID can hold. request_id = re.sub(r"[^A-Za-z0-9_.-]", "", self.headers.get("Kovrex-Request-Id", ""))[:64] or "-" authorization = self.headers.get("Authorization", "") if not authorization.startswith("Bearer ") or not from_kovrex( authorization[7:].strip(), body, int(time.time()) ): self.send_response(401) self.send_header("WWW-Authenticate", "Bearer") self.send_header("Content-Length", "0") self.end_headers() return self.note("-", request_id, "401, no valid token from Kovrex") if self.command != "POST": self.send_response(405) self.send_header("Allow", "POST") self.send_header("Content-Length", "0") self.end_headers() return self.note("-", request_id, "405, not a POST") # From here on it is Kovrex speaking A2A as JSON-RPC (section 6 of the # guide). Every answer is 200, and a refusal is a JSON-RPC error. try: request = json.loads(body) if not isinstance(request, dict): raise ValueError except ValueError: return self.refuse(None, "-", request_id, Refusal(-32700, "Echo could not read the request as JSON.")) rpc_id, method, params = request.get("id"), request.get("method"), request.get("params") name = method if method in METHODS else "other" # never log what was sent try: if method == "SendMessage": task, answer = accept_message(params) if callable(answer): answer = answer(request_id) with TALK_LOCK: if isinstance(answer, str) and task["state"] == WORKING: task["text"], task["state"] = answer, COMPLETED view = task_view(task) self.json(200, {"jsonrpc": "2.0", "id": rpc_id, "result": {"task": view}}) self.note(name, request_id, view["status"]["state"]) if answer is DEFER and task["deferred"] == "long": # Answered later (section 9): the reply above has gone, so # Kovrex has the deferral before anything is delivered. threading.Thread(target=deliver_later, args=(task, request_id), daemon=True).start() elif method == "SendStreamingMessage": task, answer = accept_message(params) self.note(name, request_id, self.stream(rpc_id, task, answer, request_id)) elif method == "GetTask": view = get_task(params) self.json(200, {"jsonrpc": "2.0", "id": rpc_id, "result": view}) self.note(name, request_id, "found, " + view["status"]["state"]) elif method == "CancelTask": view = cancel_task(params) self.json(200, {"jsonrpc": "2.0", "id": rpc_id, "result": view}) self.note(name, request_id, view["status"]["state"]) else: raise Refusal(-32601, "Echo does not know that method.") except Refusal as refusal: self.refuse(rpc_id, name, request_id, refusal) def refuse(self, rpc_id, name: str, request_id: str, refusal: Refusal) -> None: error = {"code": refusal.code, "message": refusal.message} self.json(200, {"jsonrpc": "2.0", "id": rpc_id, "error": error}) self.note(name, request_id, f"error {refusal.code}") def stream(self, rpc_id, task: dict, answer, request_id: str = "-") -> str: """Answer with an event stream. Returns the outcome, for the log.""" task_id, context_id = task["id"], task["contextId"] def event(kind: str, value: dict) -> None: reply = {"jsonrpc": "2.0", "id": rpc_id, "result": {kind: value}} self.wfile.write(b"data: " + json.dumps(reply).encode() + b"\n\n") self.wfile.flush() def status(state: str, message=None, metadata=None) -> None: value = {"state": state} if message: value["message"] = message update = {"taskId": task_id, "contextId": context_id, "status": value} if metadata: update["metadata"] = metadata event("statusUpdate", update) # No Content-Length: the stream ends when the connection closes. self.close_connection = True self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Cache-Control", "no-store") self.send_header("Connection", "close") self.end_headers() try: if answer is None: # Echo is asking, and waits for the answer status(INPUT_REQUIRED, task["question"]) return INPUT_REQUIRED if answer is REJECT: # Echo says no, with its reason (section 9) status(REJECTED, task["reason"]) return REJECTED if answer is DEFER: # Section 9: working, marked as deferred, and the stream ends. # Echo then delivers to Kovrex's return address, or, for # "never", does nothing at all. view = task_view(task) event("statusUpdate", {"taskId": task_id, "contextId": context_id, "status": view["status"], "metadata": view["metadata"]}) if task["deferred"] == "long": threading.Thread(target=deliver_later, args=(task, request_id), daemon=True).start() return "deferred, " + task["deferred"] status(WORKING) if callable(answer): # a memory tool, called once Kovrex has its first event answer = answer(request_id) parts = pieces(answer) for index, text in enumerate(parts): time.sleep(PAUSE) with TALK_LOCK: if task["state"] != WORKING: # cancelled part-way break task["text"] += text update = {"taskId": task_id, "contextId": context_id} if index > 0: update["append"] = True if index == len(parts) - 1: update["lastChunk"] = True update["artifact"] = {"artifactId": "answer", "parts": [{"text": text}]} event("artifactUpdate", update) if task.get("file"): # A file in an artifact, in a part with the bytes (section 8). time.sleep(PAUSE) event("artifactUpdate", {"taskId": task_id, "contextId": context_id, "lastChunk": True, "artifact": {"artifactId": "file", "parts": [task["file"]]}}) time.sleep(PAUSE) with TALK_LOCK: if task["state"] == WORKING: task["state"] = COMPLETED state = task["state"] # Run metrics ride on the final status event (section 10). kind = task.get("metrics") status(state, metadata={RUN: run_metrics(kind)} if kind and state == COMPLETED else None) return state except OSError: # Kovrex went away. Nobody will read the rest, so stop the task. with TALK_LOCK: if task["state"] == WORKING: task["state"] = CANCELED return "stream cut short, the caller went away" def note(self, method: str, request_id: str, outcome: str) -> None: # The method, Kovrex's request ID, and the outcome. Never the message # text, the headers, or the token. print(f"{method} {request_id} -> {outcome}", flush=True) def log_message(self, format, *args): # The path only. Never headers: they can carry a token. if getattr(self, "quiet", False): return print(f"{self.command} {self.path.split('?')[0]} -> {args[1] if len(args) > 1 else ''}", flush=True) class Server(ThreadingHTTPServer): # Listen on IPv6 and IPv4 together; Railway's health check may use either. address_family = socket.AF_INET6 def server_bind(self): self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) super().server_bind() def main() -> None: print(f"Echo, at kovrex.ai/{ADDRESS}. Public key: {PUBLIC_KEY}", flush=True) threading.Thread(target=register_and_watch, daemon=True).start() threading.Thread(target=refresh_card, daemon=True).start() Server(("::", PORT), Handler).serve_forever() if __name__ == "__main__": main()