""" Bacs à sable MCP de L'Atlas : 5 petits serveurs à nous, données fictives, remis à zéro avant chaque scénario. - taches : liste de tâches (projets, échéances, priorités) - boutique : petite boutique (clients, commandes, adresses, produits) - agenda : agenda (événements, contacts, créneaux libres) - notes : notes et dossiers - support : support client (tickets, agents, base d'aide) Rien ne sort de ce fichier : aucun réseau, aucun disque, aucun outil réel. Tout l'état vit en mémoire. Python 3.9+, bibliothèque standard seulement. Utilisable : - directement (Bac(["boutique"]).appeler("get_order", {...})), c'est ce que fait l'agent de mesure ; - comme vrai serveur MCP en stdio : python3 bac_a_sable.py boutique (voir mcp_stdio en bas). Date fictive du bac à sable : mardi 10 mars 2026. """ import copy import json import re import sys VERSION = "1.1.0" AUJOURDHUI = "2026-03-10" JOUR_SEMAINE = "Tuesday" DATE = r"^\d{4}-\d{2}-\d{2}$" DATEHEURE = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$" class ErreurOutil(Exception): pass def _s(props, req=None): return {"type": "object", "properties": props, "required": req or [], "additionalProperties": False} STR = {"type": "string"} # ------------------------------------------------------------------------------------------ données fictives DONNEES = { "taches": { "projects": {"home": "Home", "work": "Work", "garden": "Garden"}, "tasks": { "T-1": {"id": "T-1", "title": "Pay electricity bill", "project": "home", "due_date": "2026-03-12", "priority": "high", "status": "open"}, "T-2": {"id": "T-2", "title": "Book dentist appointment", "project": "home", "due_date": None, "priority": "medium", "status": "open"}, "T-3": {"id": "T-3", "title": "Prepare quarterly report", "project": "work", "due_date": "2026-03-13", "priority": "high", "status": "open"}, "T-4": {"id": "T-4", "title": "Reply to supplier quote", "project": "work", "due_date": "2026-03-09", "priority": "medium", "status": "open"}, "T-5": {"id": "T-5", "title": "Update team wiki", "project": "work", "due_date": None, "priority": "low", "status": "open"}, "T-6": {"id": "T-6", "title": "Plant tomato seedlings", "project": "garden", "due_date": "2026-03-20", "priority": "medium", "status": "open"}, "T-7": {"id": "T-7", "title": "Fix garden hose", "project": "garden", "due_date": None, "priority": "low", "status": "open"}, "T-8": {"id": "T-8", "title": "Renew car insurance", "project": "home", "due_date": "2026-03-05", "priority": "high", "status": "done"}, "T-9": {"id": "T-9", "title": "Send invoice to Acme", "project": "work", "due_date": "2026-03-06", "priority": "high", "status": "done"}, "T-10": {"id": "T-10", "title": "Buy birthday gift for Lena", "project": "home", "due_date": "2026-03-14", "priority": "medium", "status": "open"}, }, "suivant": 11, }, "boutique": { "customers": { "C-101": {"id": "C-101", "name": "Paul Martin", "email": "paul.martin@example.com", "phone": "+33 6 11 22 33 44", "city": "Lyon"}, "C-102": {"id": "C-102", "name": "Paula Mertens", "email": "paula.mertens@example.com", "phone": "+32 470 12 34 56", "city": "Brussels"}, "C-103": {"id": "C-103", "name": "Sofia Rossi", "email": "sofia.rossi@example.com", "phone": "+39 333 123 4567", "city": "Turin"}, "C-104": {"id": "C-104", "name": "Ahmed Benali", "email": "ahmed.benali@example.com", "phone": "+33 7 55 66 77 88", "city": "Marseille"}, "C-105": {"id": "C-105", "name": "Emma Dubois", "email": "emma.dubois@example.com", "phone": "+33 6 98 76 54 32", "city": "Nantes"}, "C-106": {"id": "C-106", "name": "Paul Garnier", "email": "paul.garnier@example.com", "phone": "+33 6 01 02 03 04", "city": "Lille"}, }, "products": { "P-1": {"id": "P-1", "name": "Ceramic mug", "price": 12.0, "stock": 40}, "P-2": {"id": "P-2", "name": "Linen tea towel", "price": 9.5, "stock": 25}, "P-3": {"id": "P-3", "name": "Coffee grinder", "price": 79.0, "stock": 0}, "P-4": {"id": "P-4", "name": "French press", "price": 34.0, "stock": 12}, "P-5": {"id": "P-5", "name": "Cast iron teapot", "price": 45.0, "stock": 3}, "P-6": {"id": "P-6", "name": "Bamboo serving tray", "price": 22.0, "stock": 8}, }, "orders": { "O-1041": {"id": "O-1041", "customer_id": "C-101", "status": "delivered", "date": "2026-02-20", "items": [{"product_id": "P-1", "quantity": 2}], "total": 24.0, "shipping_address": {"street": "4 rue Mercière", "city": "Lyon", "postal_code": "69002", "country": "France"}, "notes": [], "refunded": 0.0}, "O-1042": {"id": "O-1042", "customer_id": "C-101", "status": "processing", "date": "2026-03-08", "items": [{"product_id": "P-4", "quantity": 1}, {"product_id": "P-2", "quantity": 2}], "total": 53.0, "shipping_address": {"street": "4 rue Mercière", "city": "Lyon", "postal_code": "69002", "country": "France"}, "notes": [], "refunded": 0.0}, "O-1043": {"id": "O-1043", "customer_id": "C-103", "status": "processing", "date": "2026-03-09", "items": [{"product_id": "P-5", "quantity": 1}], "total": 45.0, "shipping_address": {"street": "Via Roma 12", "city": "Turin", "postal_code": "10121", "country": "Italy"}, "notes": [], "refunded": 0.0}, "O-1044": {"id": "O-1044", "customer_id": "C-104", "status": "shipped", "date": "2026-03-05", "items": [{"product_id": "P-6", "quantity": 1}, {"product_id": "P-1", "quantity": 1}], "total": 34.0, "shipping_address": {"street": "18 boulevard Longchamp", "city": "Marseille", "postal_code": "13001", "country": "France"}, "notes": [], "refunded": 0.0}, "O-1045": {"id": "O-1045", "customer_id": "C-105", "status": "processing", "date": "2026-03-09", "items": [{"product_id": "P-1", "quantity": 4}], "total": 48.0, "shipping_address": {"street": "7 quai de la Fosse", "city": "Nantes", "postal_code": "44000", "country": "France"}, "notes": [], "refunded": 0.0}, "O-1046": {"id": "O-1046", "customer_id": "C-106", "status": "processing", "date": "2026-03-10", "items": [{"product_id": "P-2", "quantity": 1}], "total": 9.5, "shipping_address": {"street": "2 place du Théâtre", "city": "Lille", "postal_code": "59000", "country": "France"}, "notes": [], "refunded": 0.0}, "O-1047": {"id": "O-1047", "customer_id": "C-102", "status": "cancelled", "date": "2026-03-01", "items": [{"product_id": "P-3", "quantity": 1}], "total": 79.0, "shipping_address": {"street": "Rue Neuve 30", "city": "Brussels", "postal_code": "1000", "country": "Belgium"}, "notes": [], "refunded": 0.0}, "O-1048": {"id": "O-1048", "customer_id": "C-105", "status": "delivered", "date": "2026-02-27", "items": [{"product_id": "P-5", "quantity": 1}], "total": 45.0, "shipping_address": {"street": "7 quai de la Fosse", "city": "Nantes", "postal_code": "44000", "country": "France"}, "notes": [], "refunded": 0.0}, }, }, "agenda": { "contacts": { "lena.weber@example.com": {"name": "Lena Weber", "email": "lena.weber@example.com", "team": "Design"}, "omar.haddad@example.com": {"name": "Omar Haddad", "email": "omar.haddad@example.com", "team": "Sales"}, "julie.moreau@example.com": {"name": "Julie Moreau", "email": "julie.moreau@example.com", "team": "Engineering"}, "julien.petit@example.com": {"name": "Julien Petit", "email": "julien.petit@example.com", "team": "Finance"}, "kenji.sato@example.com": {"name": "Kenji Sato", "email": "kenji.sato@example.com", "team": "Engineering"}, }, "events": { "E-1": {"id": "E-1", "title": "Team standup", "start": "2026-03-10T09:00", "end": "2026-03-10T09:30", "attendees": ["julie.moreau@example.com", "kenji.sato@example.com"]}, "E-2": {"id": "E-2", "title": "Budget review", "start": "2026-03-10T14:00", "end": "2026-03-10T15:00", "attendees": ["julien.petit@example.com"]}, "E-3": {"id": "E-3", "title": "Design critique", "start": "2026-03-11T10:00", "end": "2026-03-11T11:00", "attendees": ["lena.weber@example.com"]}, "E-4": {"id": "E-4", "title": "Lunch with Omar", "start": "2026-03-11T12:30", "end": "2026-03-11T13:30", "attendees": ["omar.haddad@example.com"]}, "E-5": {"id": "E-5", "title": "Sprint planning", "start": "2026-03-12T09:00", "end": "2026-03-12T11:00", "attendees": ["julie.moreau@example.com", "kenji.sato@example.com"]}, "E-6": {"id": "E-6", "title": "Client call - Acme", "start": "2026-03-12T15:00", "end": "2026-03-12T15:45", "attendees": ["omar.haddad@example.com"]}, "E-7": {"id": "E-7", "title": "Dentist", "start": "2026-03-13T08:30", "end": "2026-03-13T09:15", "attendees": []}, "E-8": {"id": "E-8", "title": "Quarterly report deadline review", "start": "2026-03-13T16:00", "end": "2026-03-13T17:00", "attendees": ["julien.petit@example.com"]}, }, "suivant": 9, }, "notes": { "folders": ["inbox", "recipes", "work", "travel", "archive"], "notes": { "N-1": {"id": "N-1", "title": "Pancake recipe", "folder": "recipes", "content": "200 g flour, 2 eggs, 300 ml milk, a pinch of salt. Rest the batter 30 minutes."}, "N-2": {"id": "N-2", "title": "Lisbon trip ideas", "folder": "travel", "content": "Tram 28, Belem tower, pasteis de nata at Manteigaria. Hotel budget: 120 EUR per night."}, "N-3": {"id": "N-3", "title": "Meeting notes 2026-03-03", "folder": "work", "content": "Decided: migrate billing to the new provider by April. Owner: Julien. Risk: data export format."}, "N-4": {"id": "N-4", "title": "Wifi password guest", "folder": "inbox", "content": "Network: Maison-Invites. Password: tulipe-2026."}, "N-5": {"id": "N-5", "title": "Books to read", "folder": "inbox", "content": "- The Overstory\n- Piranesi"}, "N-6": {"id": "N-6", "title": "Old project Orion", "folder": "work", "content": "Project Orion was closed in 2025. Keep for reference."}, "N-7": {"id": "N-7", "title": "Tomato sauce", "folder": "recipes", "content": "Olive oil, garlic, 800 g tomatoes, basil. Simmer 40 minutes."}, "N-8": {"id": "N-8", "title": "Packing list", "folder": "travel", "content": "Passport, charger, adapter, rain jacket."}, }, "suivant": 9, }, "support": { "agents": { "A-1": {"id": "A-1", "name": "Nadia", "team": "billing"}, "A-2": {"id": "A-2", "name": "Tom", "team": "shipping"}, "A-3": {"id": "A-3", "name": "Ines", "team": "technical"}, }, "kb": { "KB-1": {"id": "KB-1", "title": "How to reset your password", "body": "Go to Settings > Security and click 'Reset password'. A link valid for 24 hours is sent by email."}, "KB-2": {"id": "KB-2", "title": "Delivery times", "body": "Standard delivery takes 3 to 5 business days in France and 5 to 8 days elsewhere in Europe."}, "KB-3": {"id": "KB-3", "title": "Refund policy", "body": "Delivered items can be returned within 30 days. Refunds are issued within 5 business days."}, "KB-4": {"id": "KB-4", "title": "Changing a shipping address", "body": "The address can be changed while the order is still processing. Once shipped, it cannot be changed."}, }, "tickets": { "K-201": {"id": "K-201", "customer_email": "paul.martin@example.com", "subject": "Wrong address on my order O-1042", "status": "open", "priority": "normal", "assignee": None, "messages": [{"from": "customer", "text": "Hello, I moved. Please ship order O-1042 to 25 avenue Jean Jaurès, 69007 Lyon, France instead."}]}, "K-202": {"id": "K-202", "customer_email": "emma.dubois@example.com", "subject": "Cannot log in", "status": "open", "priority": "normal", "assignee": None, "messages": [{"from": "customer", "text": "I forgot my password and cannot log in. How can I reset it?"}]}, "K-203": {"id": "K-203", "customer_email": "ahmed.benali@example.com", "subject": "Where is my parcel?", "status": "open", "priority": "normal", "assignee": None, "messages": [{"from": "customer", "text": "My order O-1044 was shipped on March 5. When will it arrive?"}]}, "K-204": {"id": "K-204", "customer_email": "sofia.rossi@example.com", "subject": "Charged twice", "status": "open", "priority": "normal", "assignee": None, "messages": [{"from": "customer", "text": "My card was charged twice for order O-1043. Please fix this urgently."}]}, "K-205": {"id": "K-205", "customer_email": "paula.mertens@example.com", "subject": "Thanks!", "status": "pending", "priority": "low", "assignee": "A-2", "messages": [{"from": "customer", "text": "All good, thank you for cancelling my order."}]}, "K-206": {"id": "K-206", "customer_email": "emma.dubois@example.com", "subject": "Broken teapot", "status": "open", "priority": "normal", "assignee": None, "messages": [{"from": "customer", "text": "The teapot from order O-1048 arrived cracked. I would like a refund."}]}, }, }, } # ------------------------------------------------------------------------------------------ petits outils def _norm(v): return v.strip().casefold() if isinstance(v, str) else v VIDES = {"the", "and", "for", "with", "about", "from", "that", "this", "my", "our", "your", "all", "any", "note", "notes", "task", "tasks"} def _mots(texte): """Mots utiles d'une recherche, réduits à leur début (fixing -> fix, meetings -> meeti).""" r = [] for m in re.findall(r"[\w@.\-]+", _norm(texte)): m = m.strip(".-") if len(m) >= 3 and m not in VIDES: r.append(m[:max(3, len(m) - 3)] if len(m) > 5 else m) return r def _score(texte, *champs): """Recherche plein texte comme un vrai serveur : phrase exacte d'abord, sinon nombre de mots trouvés.""" tout = " ".join(_norm(c or "") for c in champs) if _norm(texte) and _norm(texte) in tout: return 1000 return sum(1 for m in _mots(texte) if m in tout) def _trier(texte, items, *cles): sc = [(_score(texte, *[it.get(k) for k in cles]), i, it) for i, it in enumerate(items)] return [it for s, i, it in sorted(sc, key=lambda x: (-x[0], x[1])) if s > 0] def _cherche(texte, *champs): return _score(texte, *champs) > 0 def _date(v, nom): if not isinstance(v, str) or not re.match(DATE, v): raise ErreurOutil(f"{nom} must be a date in the form YYYY-MM-DD") return v def _dateheure(v, nom): if not isinstance(v, str) or not re.match(DATEHEURE, v): raise ErreurOutil(f"{nom} must be a local date-time in the form YYYY-MM-DDTHH:MM") return v[:16] def _minutes(dh): j, h = dh.split("T") return int(j.replace("-", "")) * 1440 + int(h[:2]) * 60 + int(h[3:5]) def _hhmm(m): m %= 1440 return f"{m // 60:02d}:{m % 60:02d}" def _plus(dh, minutes): total = int(dh[11:13]) * 60 + int(dh[14:16]) + minutes if total >= 1440: raise ErreurOutil("events must end on the same day") return f"{dh[:10]}T{_hhmm(total)}" # ------------------------------------------------------------------------------------------ serveurs class Serveur: nom = "" description = "" OUTILS = [] # [(nom, description, schéma)] def __init__(self, etat): self.e = etat def outils(self): return [{"name": n, "description": d, "inputSchema": s} for n, d, s in self.OUTILS] class Taches(Serveur): nom = "taches" description = "To-do list with projects, due dates and priorities." PRIO = {"type": "string", "enum": ["low", "medium", "high"]} OUTILS = [ ("list_projects", "List the projects of the to-do list.", _s({})), ("list_tasks", "List tasks, optionally filtered by project id and status.", _s({"project": STR, "status": {"type": "string", "enum": ["open", "done"]}})), ("search_tasks", "Search tasks whose title contains the query.", _s({"query": STR}, ["query"])), ("create_task", "Create a task. due_date is YYYY-MM-DD.", _s({"title": STR, "project": STR, "due_date": STR, "priority": PRIO}, ["title", "project"])), ("update_task", "Change the title, project, due date (YYYY-MM-DD) or priority of a task.", _s({"task_id": STR, "title": STR, "project": STR, "due_date": STR, "priority": PRIO}, ["task_id"])), ("complete_task", "Mark a task as done.", _s({"task_id": STR}, ["task_id"])), ("delete_task", "Delete a task permanently.", _s({"task_id": STR}, ["task_id"])), ] def _t(self, i): t = self.e["tasks"].get(str(i).strip().upper()) if not t: raise ErreurOutil(f"task {i} not found") return t def _p(self, p): p = _norm(p) for k, v in self.e["projects"].items(): if p in (k, _norm(v)): return k raise ErreurOutil(f"project {p} not found; use list_projects") def list_projects(self, a): return {"projects": [{"id": k, "name": v} for k, v in self.e["projects"].items()]} def list_tasks(self, a): r = list(self.e["tasks"].values()) if a.get("project"): p = self._p(a["project"]); r = [t for t in r if t["project"] == p] if a.get("status"): r = [t for t in r if t["status"] == a["status"]] return {"tasks": r} def search_tasks(self, a): return {"tasks": _trier(a["query"], list(self.e["tasks"].values()), "title")} def create_task(self, a): i = f"T-{self.e['suivant']}"; self.e["suivant"] += 1 t = {"id": i, "title": a["title"].strip(), "project": self._p(a["project"]), "due_date": _date(a["due_date"], "due_date") if a.get("due_date") else None, "priority": a.get("priority") or "medium", "status": "open"} self.e["tasks"][i] = t return {"created": t} def update_task(self, a): t = self._t(a["task_id"]) if "title" in a: t["title"] = a["title"].strip() if "project" in a: t["project"] = self._p(a["project"]) if "due_date" in a: t["due_date"] = _date(a["due_date"], "due_date") if "priority" in a: t["priority"] = a["priority"] return {"updated": t} def complete_task(self, a): t = self._t(a["task_id"]); t["status"] = "done" return {"completed": t} def delete_task(self, a): t = self._t(a["task_id"]); del self.e["tasks"][t["id"]] return {"deleted": t["id"]} class Boutique(Serveur): nom = "boutique" description = "Small online shop back office: customers, orders, shipping addresses, products." OUTILS = [ ("search_customers", "Find customers by name or email.", _s({"query": STR}, ["query"])), ("get_customer", "Get a customer by id.", _s({"customer_id": STR}, ["customer_id"])), ("list_orders", "List orders, optionally for one customer id and/or one status.", _s({"customer_id": STR, "status": {"type": "string", "enum": ["processing", "shipped", "delivered", "cancelled"]}})), ("get_order", "Get the full details of an order.", _s({"order_id": STR}, ["order_id"])), ("update_shipping_address", "Change the shipping address of an order that is still processing.", _s({"order_id": STR, "street": STR, "city": STR, "postal_code": STR, "country": STR}, ["order_id", "street", "city", "postal_code", "country"])), ("cancel_order", "Cancel an order that is still processing.", _s({"order_id": STR, "reason": STR}, ["order_id", "reason"])), ("refund_order", "Refund a delivered order, fully or partially (amount in EUR, defaults to the order total).", _s({"order_id": STR, "amount": {"type": "number", "minimum": 0}, "reason": STR}, ["order_id", "reason"])), ("add_item_to_order", "Add a product to an order that is still processing.", _s({"order_id": STR, "product_id": STR, "quantity": {"type": "integer", "minimum": 1}}, ["order_id", "product_id", "quantity"])), ("add_order_note", "Add an internal note to an order.", _s({"order_id": STR, "note": STR}, ["order_id", "note"])), ("search_products", "Find products by name, with price and stock.", _s({"query": STR}, ["query"])), ] def _o(self, i): o = self.e["orders"].get(str(i).strip().upper()) if not o: raise ErreurOutil(f"order {i} not found") return o def search_customers(self, a): return {"customers": _trier(a["query"], list(self.e["customers"].values()), "name", "email")} def get_customer(self, a): c = self.e["customers"].get(str(a["customer_id"]).strip().upper()) if not c: raise ErreurOutil(f"customer {a['customer_id']} not found") return c def list_orders(self, a): r = list(self.e["orders"].values()) if a.get("customer_id"): r = [o for o in r if o["customer_id"] == str(a["customer_id"]).strip().upper()] if a.get("status"): r = [o for o in r if o["status"] == a["status"]] return {"orders": [{k: o[k] for k in ("id", "customer_id", "status", "date", "total")} for o in r]} def get_order(self, a): o = self._o(a["order_id"]) d = copy.deepcopy(o) for it in d["items"]: it["name"] = self.e["products"][it["product_id"]]["name"] return d def update_shipping_address(self, a): o = self._o(a["order_id"]) if o["status"] != "processing": raise ErreurOutil(f"order {o['id']} is {o['status']}: the address can no longer be changed") o["shipping_address"] = {k: a[k].strip() for k in ("street", "city", "postal_code", "country")} return {"updated": o["id"], "shipping_address": o["shipping_address"]} def cancel_order(self, a): o = self._o(a["order_id"]) if o["status"] != "processing": raise ErreurOutil(f"order {o['id']} is {o['status']}: only processing orders can be cancelled") o["status"] = "cancelled"; o["notes"].append("Cancelled: " + a["reason"]) for it in o["items"]: self.e["products"][it["product_id"]]["stock"] += it["quantity"] return {"cancelled": o["id"]} def refund_order(self, a): o = self._o(a["order_id"]) if o["status"] != "delivered": raise ErreurOutil(f"order {o['id']} is {o['status']}: only delivered orders can be refunded") m = float(a["amount"]) if a.get("amount") is not None else o["total"] - o["refunded"] if m <= 0 or o["refunded"] + m > o["total"] + 1e-9: raise ErreurOutil(f"refund amount must be between 0 and {o['total'] - o['refunded']:.2f}") o["refunded"] = round(o["refunded"] + m, 2); o["notes"].append("Refund: " + a["reason"]) return {"refunded": o["id"], "amount": round(m, 2), "total_refunded": o["refunded"]} def add_item_to_order(self, a): o = self._o(a["order_id"]) if o["status"] != "processing": raise ErreurOutil(f"order {o['id']} is {o['status']}: items can no longer be added") p = self.e["products"].get(str(a["product_id"]).strip().upper()) if not p: raise ErreurOutil(f"product {a['product_id']} not found") q = int(a["quantity"]) if p["stock"] < q: raise ErreurOutil(f"not enough stock for {p['name']} ({p['stock']} left)") p["stock"] -= q for it in o["items"]: if it["product_id"] == p["id"]: it["quantity"] += q; break else: o["items"].append({"product_id": p["id"], "quantity": q}) o["total"] = round(o["total"] + q * p["price"], 2) return {"updated": o["id"], "total": o["total"]} def add_order_note(self, a): o = self._o(a["order_id"]); o["notes"].append(a["note"].strip()) return {"order_id": o["id"], "notes": o["notes"]} def search_products(self, a): return {"products": _trier(a["query"], list(self.e["products"].values()), "name")} class Agenda(Serveur): nom = "agenda" description = "Calendar: events, contacts and free slots (local time)." OUTILS = [ ("list_events", "List events between two dates (YYYY-MM-DD, inclusive).", _s({"start_date": STR, "end_date": STR}, ["start_date", "end_date"])), ("search_contacts", "Find contacts by name, email or team.", _s({"query": STR}, ["query"])), ("find_free_slots", "Find free slots of a given length on a day, between 09:00 and 18:00.", _s({"date": STR, "duration_minutes": {"type": "integer", "minimum": 5}}, ["date", "duration_minutes"])), ("create_event", "Create an event. start is YYYY-MM-DDTHH:MM; attendees are email addresses.", _s({"title": STR, "start": STR, "duration_minutes": {"type": "integer", "minimum": 5}, "attendees": {"type": "array", "items": STR}}, ["title", "start", "duration_minutes"])), ("move_event", "Move an event to a new start time (YYYY-MM-DDTHH:MM), keeping its length.", _s({"event_id": STR, "new_start": STR}, ["event_id", "new_start"])), ("add_attendee", "Invite one more person (email) to an event.", _s({"event_id": STR, "email": STR}, ["event_id", "email"])), ("cancel_event", "Cancel (delete) an event.", _s({"event_id": STR}, ["event_id"])), ] def _ev(self, i): e = self.e["events"].get(str(i).strip().upper()) if not e: raise ErreurOutil(f"event {i} not found") return e def _conflit(self, debut, fin, sauf=None): for e in self.e["events"].values(): if e["id"] != sauf and _minutes(e["start"]) < _minutes(fin) and _minutes(debut) < _minutes(e["end"]): return e return None def _email(self, m): m = _norm(m) if m not in self.e["contacts"]: raise ErreurOutil(f"{m} is not a known contact; use search_contacts") return m def list_events(self, a): d, f = _date(a["start_date"], "start_date"), _date(a["end_date"], "end_date") r = [e for e in self.e["events"].values() if d <= e["start"][:10] <= f] return {"events": sorted(r, key=lambda e: e["start"])} def search_contacts(self, a): return {"contacts": _trier(a["query"], list(self.e["contacts"].values()), "name", "email", "team")} def find_free_slots(self, a): j = _date(a["date"], "date"); n = int(a["duration_minutes"]) occ = sorted((_minutes(e["start"]) % 1440, _minutes(e["end"]) % 1440) for e in self.e["events"].values() if e["start"][:10] == j) libres, t = [], 9 * 60 for d, f in occ + [(18 * 60, 18 * 60)]: if d - t >= n: libres.append({"start": f"{j}T{_hhmm(t)}", "end": f"{j}T{_hhmm(d)}"}) t = max(t, f) return {"date": j, "free_slots": libres} def create_event(self, a): debut = _dateheure(a["start"], "start"); fin = _plus(debut, int(a["duration_minutes"])) c = self._conflit(debut, fin) if c: raise ErreurOutil(f"conflicts with {c['id']} '{c['title']}' ({c['start'][11:]}-{c['end'][11:]})") i = f"E-{self.e['suivant']}"; self.e["suivant"] += 1 e = {"id": i, "title": a["title"].strip(), "start": debut, "end": fin, "attendees": [self._email(m) for m in a.get("attendees") or []]} self.e["events"][i] = e return {"created": e} def move_event(self, a): e = self._ev(a["event_id"]) debut = _dateheure(a["new_start"], "new_start") fin = _plus(debut, _minutes(e["end"]) - _minutes(e["start"])) c = self._conflit(debut, fin, e["id"]) if c: raise ErreurOutil(f"conflicts with {c['id']} '{c['title']}' ({c['start'][11:]}-{c['end'][11:]})") e["start"], e["end"] = debut, fin return {"moved": e} def add_attendee(self, a): e = self._ev(a["event_id"]); m = self._email(a["email"]) if m not in e["attendees"]: e["attendees"].append(m) return {"event": e} def cancel_event(self, a): e = self._ev(a["event_id"]); del self.e["events"][e["id"]] return {"cancelled": e["id"]} class Notes(Serveur): nom = "notes" description = "Personal notes organised in folders." OUTILS = [ ("list_folders", "List the note folders.", _s({})), ("list_notes", "List notes (id, title, folder), optionally in one folder.", _s({"folder": STR})), ("search_notes", "Search notes whose title or content contains the query.", _s({"query": STR}, ["query"])), ("read_note", "Read the full content of a note.", _s({"note_id": STR}, ["note_id"])), ("create_note", "Create a note in a folder.", _s({"title": STR, "folder": STR, "content": STR}, ["title", "folder", "content"])), ("append_to_note", "Append text at the end of a note (on a new line).", _s({"note_id": STR, "text": STR}, ["note_id", "text"])), ("move_note", "Move a note to another folder.", _s({"note_id": STR, "folder": STR}, ["note_id", "folder"])), ("rename_note", "Change the title of a note.", _s({"note_id": STR, "title": STR}, ["note_id", "title"])), ("delete_note", "Delete a note permanently.", _s({"note_id": STR}, ["note_id"])), ] def _n(self, i): n = self.e["notes"].get(str(i).strip().upper()) if not n: raise ErreurOutil(f"note {i} not found") return n def _f(self, f): f = _norm(f) if f not in self.e["folders"]: raise ErreurOutil(f"folder {f} does not exist; use list_folders") return f def list_folders(self, a): return {"folders": self.e["folders"]} def list_notes(self, a): f = self._f(a["folder"]) if a.get("folder") else None return {"notes": [{"id": n["id"], "title": n["title"], "folder": n["folder"]} for n in self.e["notes"].values() if f is None or n["folder"] == f]} def search_notes(self, a): return {"notes": [{"id": n["id"], "title": n["title"], "folder": n["folder"]} for n in _trier(a["query"], list(self.e["notes"].values()), "title", "content")]} def read_note(self, a): return self._n(a["note_id"]) def create_note(self, a): i = f"N-{self.e['suivant']}"; self.e["suivant"] += 1 n = {"id": i, "title": a["title"].strip(), "folder": self._f(a["folder"]), "content": a["content"]} self.e["notes"][i] = n return {"created": {"id": i, "title": n["title"], "folder": n["folder"]}} def append_to_note(self, a): n = self._n(a["note_id"]); n["content"] = n["content"].rstrip("\n") + "\n" + a["text"] return {"updated": n["id"]} def move_note(self, a): n = self._n(a["note_id"]); n["folder"] = self._f(a["folder"]) return {"moved": n["id"], "folder": n["folder"]} def rename_note(self, a): n = self._n(a["note_id"]); n["title"] = a["title"].strip() return {"renamed": n["id"], "title": n["title"]} def delete_note(self, a): n = self._n(a["note_id"]); del self.e["notes"][n["id"]] return {"deleted": n["id"]} class Support(Serveur): nom = "support" description = "Customer support desk: tickets, agents and help articles." OUTILS = [ ("list_tickets", "List tickets, optionally filtered by status and/or customer email.", _s({"status": {"type": "string", "enum": ["open", "pending", "solved"]}, "customer_email": STR})), ("get_ticket", "Get a ticket with its messages.", _s({"ticket_id": STR}, ["ticket_id"])), ("search_help_articles", "Search the help center articles.", _s({"query": STR}, ["query"])), ("reply_to_ticket", "Send a reply to the customer on a ticket.", _s({"ticket_id": STR, "message": STR}, ["ticket_id", "message"])), ("set_ticket_status", "Change the status of a ticket.", _s({"ticket_id": STR, "status": {"type": "string", "enum": ["open", "pending", "solved"]}}, ["ticket_id", "status"])), ("set_ticket_priority", "Change the priority of a ticket.", _s({"ticket_id": STR, "priority": {"type": "string", "enum": ["low", "normal", "high", "urgent"]}}, ["ticket_id", "priority"])), ("list_agents", "List support agents and their team.", _s({})), ("assign_ticket", "Assign a ticket to an agent id.", _s({"ticket_id": STR, "agent_id": STR}, ["ticket_id", "agent_id"])), ] def _k(self, i): k = self.e["tickets"].get(str(i).strip().upper()) if not k: raise ErreurOutil(f"ticket {i} not found") return k def list_tickets(self, a): r = list(self.e["tickets"].values()) if a.get("status"): r = [k for k in r if k["status"] == a["status"]] if a.get("customer_email"): r = [k for k in r if k["customer_email"] == _norm(a["customer_email"])] return {"tickets": [{x: k[x] for x in ("id", "customer_email", "subject", "status", "priority", "assignee")} for k in r]} def get_ticket(self, a): return self._k(a["ticket_id"]) def search_help_articles(self, a): return {"articles": _trier(a["query"], list(self.e["kb"].values()), "title", "body")} def reply_to_ticket(self, a): k = self._k(a["ticket_id"]); k["messages"].append({"from": "agent", "text": a["message"].strip()}) return {"ticket_id": k["id"], "messages": len(k["messages"])} def set_ticket_status(self, a): k = self._k(a["ticket_id"]); k["status"] = a["status"] return {"ticket_id": k["id"], "status": k["status"]} def set_ticket_priority(self, a): k = self._k(a["ticket_id"]); k["priority"] = a["priority"] return {"ticket_id": k["id"], "priority": k["priority"]} def list_agents(self, a): return {"agents": list(self.e["agents"].values())} def assign_ticket(self, a): k = self._k(a["ticket_id"]) ag = str(a["agent_id"]).strip().upper() if ag not in self.e["agents"]: raise ErreurOutil(f"agent {a['agent_id']} not found; use list_agents") k["assignee"] = ag return {"ticket_id": k["id"], "assignee": ag} SERVEURS = {c.nom: c for c in (Taches, Boutique, Agenda, Notes, Support)} # ------------------------------------------------------------------------------------------ validation des arguments _TYPES = {"string": lambda v: isinstance(v, str), "integer": lambda v: isinstance(v, int) and not isinstance(v, bool) or (isinstance(v, float) and v.is_integer()), "number": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool), "array": lambda v: isinstance(v, list), "object": lambda v: isinstance(v, dict)} def verifier_args(args, sch): """Rend la liste des erreurs (anglais, renvoyées au modèle comme le ferait un vrai serveur).""" if not isinstance(args, dict): return ["arguments must be a JSON object"] err = [] props = sch.get("properties", {}) for r in sch.get("required", []): if r not in args or args[r] is None: err.append(f"missing required argument '{r}'") for k, v in args.items(): if k not in props: err.append(f"unknown argument '{k}'") continue p = props[k] if v is None: continue t = p.get("type") if t and not _TYPES[t](v): err.append(f"argument '{k}' must be of type {t}") elif "enum" in p and v not in p["enum"]: err.append(f"argument '{k}' must be one of {p['enum']}") elif "minimum" in p and v < p["minimum"]: err.append(f"argument '{k}' must be >= {p['minimum']}") elif t == "array" and "items" in p and not all(_TYPES[p["items"]["type"]](x) for x in v): err.append(f"items of '{k}' must be of type {p['items']['type']}") return err # ------------------------------------------------------------------------------------------ bac à sable d'un scénario class Bac: """Un ou plusieurs serveurs, état neuf (copie des données fictives). Une instance par essai.""" def __init__(self, noms): self.serveurs = {} self.routes = {} for n in noms: s = SERVEURS[n](copy.deepcopy(DONNEES[n])) self.serveurs[n] = s for nom, _, sch in s.OUTILS: self.routes[nom] = (s, sch) self.journal = [] def outils(self): return [o for s in self.serveurs.values() for o in s.outils()] def etat(self): return {n: s.e for n, s in self.serveurs.items()} def appeler(self, nom, args): """Rend (résultat, erreur) ; jamais d'exception. L'erreur est un texte comme celui d'un vrai serveur MCP.""" if isinstance(args, str): try: args = json.loads(args) if args.strip() else {} except Exception: args = None if args is None: args = {} if nom not in self.routes: res, err = None, f"unknown tool '{nom}'" else: s, sch = self.routes[nom] errs = verifier_args(args, sch) if errs: res, err = None, "invalid arguments: " + "; ".join(errs) else: try: res, err = getattr(s, nom)({k: v for k, v in args.items() if v is not None}), None except ErreurOutil as e: res, err = None, str(e) except Exception as e: # un bug du bac à sable ne doit pas casser l'essai res, err = None, f"internal error: {type(e).__name__}" self.journal.append({"outil": nom, "arguments": args, "erreur": err}) return res, err # ------------------------------------------------------------------------------------------ contrôle de l'état final def _chemin(etat, chemin): n = etat for p in chemin.split("/"): if isinstance(n, dict) and p in n: n = n[p] elif isinstance(n, list) and p.isdigit() and int(p) < len(n): n = n[int(p)] else: return None return n def _vaut(v, attendu): if isinstance(attendu, (int, float)) and not isinstance(attendu, bool) and isinstance(v, (int, float)): return abs(v - attendu) < 0.005 return _norm(v) == _norm(attendu) def _correspond(obj, ou): for k, att in ou.items(): if k.endswith("~"): v = obj.get(k[:-1]) txt = json.dumps(v, ensure_ascii=False) if not isinstance(v, str) else v if not all(_norm(m) in _norm(txt) for m in (att if isinstance(att, list) else [att])): return False elif k.endswith("[]"): v = obj.get(k[:-2]) or [] if not all(_norm(m) in [_norm(x) for x in v] for m in (att if isinstance(att, list) else [att])): return False elif not _vaut(obj.get(k), att): return False return True def controle(c, etat, reponse): """Un contrôle déclaratif → vrai/faux. Types : egal, contient, trouve, absent, compte, reponse.""" t = c["t"] if t == "egal": return _vaut(_chemin(etat, c["chemin"]), c["valeur"]) if t == "contient": v = _chemin(etat, c["chemin"]) txt = _norm(v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)) alts = c["un_de"] if "un_de" in c else [c["valeur"]] return any(all(_norm(m) in txt for m in (alt if isinstance(alt, list) else [alt])) for alt in alts) if t in ("trouve", "absent", "compte"): coll = _chemin(etat, c["collection"]) or {} items = list(coll.values()) if isinstance(coll, dict) else list(coll) n = sum(1 for o in items if isinstance(o, dict) and _correspond(o, c.get("ou", {}))) return n > 0 if t == "trouve" else n == 0 if t == "absent" else n == c["n"] if t == "reponse": r = _norm(reponse or "").replace(" ", " ").replace(" ", " ") return any(all(_norm(m) in r for m in (alt if isinstance(alt, list) else [alt])) for alt in c["un_de"]) raise ValueError(f"contrôle inconnu {t}") def juger(scenario, etat, reponse): """→ {verdict: reussi|partiel|rate, objectifs: [bool], gardes: [bool]}""" obj = [controle(c, etat, reponse) for c in scenario["objectifs"]] gar = [controle(c, etat, reponse) for c in scenario.get("gardes", [])] if not all(gar): v = "rate" elif all(obj): v = "reussi" elif any(obj): v = "partiel" else: v = "rate" return {"verdict": v, "objectifs": obj, "gardes": gar} # ------------------------------------------------------------------------------------------ vrai serveur MCP (stdio) def mcp_stdio(nom): """python3 bac_a_sable.py : serveur MCP minimal en stdio (JSON-RPC, une ligne par message).""" bac = Bac([nom]) for ligne in sys.stdin: try: m = json.loads(ligne) except Exception: continue i, meth, p = m.get("id"), m.get("method"), m.get("params") or {} if i is None: continue if meth == "initialize": r = {"protocolVersion": p.get("protocolVersion", "2025-06-18"), "capabilities": {"tools": {}}, "serverInfo": {"name": f"latlas-bac-a-sable-{nom}", "version": VERSION}} elif meth == "tools/list": r = {"tools": bac.outils()} elif meth == "tools/call": res, err = bac.appeler(p.get("name"), p.get("arguments") or {}) r = {"content": [{"type": "text", "text": json.dumps(res if err is None else {"error": err}, ensure_ascii=False)}], "isError": err is not None} elif meth == "ping": r = {} else: sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": i, "error": {"code": -32601, "message": "method not found"}}) + "\n"); sys.stdout.flush() continue sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": i, "result": r}, ensure_ascii=False) + "\n"); sys.stdout.flush() if __name__ == "__main__": if len(sys.argv) != 2 or sys.argv[1] not in SERVEURS: sys.exit("usage : python3 bac_a_sable.py " + "|".join(SERVEURS)) mcp_stdio(sys.argv[1])