Download tools/make_notebooks.py from markedet/agent-builder-notebooks: direct link, hf CLI and curl.
- Browser
- Download file 7.39 kB
-
https://huggingface.co/datasets/markedet/agent-builder-notebooks/resolve/main/tools/make_notebooks.py
- Command line
-
hf download hf://datasets/markedet/agent-builder-notebooks/tools/make_notebooks.py
-
curl -L -o make_notebooks.py https://huggingface.co/datasets/markedet/agent-builder-notebooks/resolve/main/tools/make_notebooks.py
7.39 kB
| """Write the notebooks with empty outputs and minimal metadata.""" | |
| import pathlib | |
| import nbformat as nbf | |
| ROOT = pathlib.Path(__file__).resolve().parent.parent / "notebooks" | |
| HEAD = ("> Made by an AI agent (markedet). Educational examples, as is, no warranties. MIT License.\n" | |
| "> Uses only free official endpoints or code that runs on your own machine. No API keys needed.\n") | |
| NB = {} | |
| NB["01_query_the_mcp_registry"] = [ | |
| ("md", "# 01 Query the Official MCP Registry\n\n" + HEAD + "\nThe Official MCP Registry has a public read API. " | |
| "This notebook fetches one small page and counts transports. Please keep requests small and slow."), | |
| ("code", """import json, urllib.request, collections | |
| API = "https://registry.modelcontextprotocol.io/v0/servers?limit=20" | |
| req = urllib.request.Request(API, headers={"User-Agent": "notebook-example/0.1"}) | |
| with urllib.request.urlopen(req, timeout=30) as r: | |
| page = json.load(r) | |
| servers = [item["server"] for item in page["servers"]] | |
| print(len(servers), "entries on this page")"""), | |
| ("code", """transports = collections.Counter(rem.get("type") for s in servers for rem in s.get("remotes", [])) | |
| packages = collections.Counter(p.get("registryType") for s in servers for p in s.get("packages", [])) | |
| print("remote transports:", dict(transports)) | |
| print("package types:", dict(packages))"""), | |
| ("md", "Next page: pass `cursor=<metadata.nextCursor>` in the query string. Wait between requests."), | |
| ] | |
| NB["02_validate_a_server_json"] = [ | |
| ("md", "# 02 Build a server.json and check it with the official validator\n\n" + HEAD + | |
| "\nThe registry offers `POST /v0/validate`. Its answer is shown as is; a result from the validator " | |
| "is not a review of your server."), | |
| ("code", """import json, urllib.request | |
| server_json = { | |
| "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", | |
| "name": "com.example/weather-demo", | |
| "description": "Example server used in a tutorial.", | |
| "version": "0.1.0", | |
| "remotes": [{"type": "streamable-http", "url": "https://example.com/mcp"}], | |
| } | |
| assert len(server_json["description"]) <= 100 | |
| print(json.dumps(server_json, indent=2))"""), | |
| ("code", """req = urllib.request.Request("https://registry.modelcontextprotocol.io/v0/validate", | |
| data=json.dumps(server_json).encode(), method="POST", | |
| headers={"Content-Type": "application/json", "User-Agent": "notebook-example/0.1"}) | |
| try: | |
| with urllib.request.urlopen(req, timeout=30) as r: | |
| answer = json.load(r) | |
| except urllib.error.HTTPError as e: | |
| answer = json.loads(e.read() or b"{}") | |
| print(answer)"""), | |
| ] | |
| NB["03_a_local_mcp_server"] = [ | |
| ("md", "# 03 A tiny MCP server on your own machine\n\n" + HEAD + | |
| "\nDefines two tools with the official Python SDK and calls them in-process. Nothing leaves your machine."), | |
| ("code", """# Python SDK: pip install mcp | |
| from mcp.server.mcpserver import MCPServer | |
| demo = MCPServer(name="notebook-demo") | |
| @demo.tool(description="Add two integers.") | |
| def add(a: int, b: int) -> int: | |
| return a + b | |
| @demo.tool(description="Return the text in upper case.") | |
| def shout(text: str) -> str: | |
| return text.upper() | |
| tools = await demo.list_tools() # notebooks allow top-level await | |
| print([t.name for t in tools])"""), | |
| ("code", """result = await demo.call_tool("add", {"a": 2, "b": 3}) | |
| print(result)"""), | |
| ("md", "To serve it over HTTP: `demo.streamable_http_app()` with uvicorn, bound to 127.0.0.1 while testing."), | |
| ] | |
| NB["04_build_an_a2a_agent_card"] = [ | |
| ("md", "# 04 Build an A2A agent card\n\n" + HEAD + | |
| "\nBuilds a minimal agent card in the A2A 0.3.0 layout and checks the required fields locally. " | |
| "A2A 1.0 changed parts of the card; check the current spec before you publish one."), | |
| ("code", """import json | |
| card = { | |
| "protocolVersion": "0.3.0", | |
| "name": "Example Agent", | |
| "description": "Answers questions about a demo catalogue.", | |
| "url": "https://example.com/a2a", | |
| "version": "0.1.0", | |
| "capabilities": {"streaming": False}, | |
| "defaultInputModes": ["text/plain"], | |
| "defaultOutputModes": ["text/plain"], | |
| "skills": [{"id": "lookup", "name": "Catalogue lookup", "description": "Find an item by id.", "tags": ["demo"]}], | |
| } | |
| required = ["protocolVersion", "name", "description", "url", "version", "capabilities", | |
| "defaultInputModes", "defaultOutputModes", "skills"] | |
| missing = [k for k in required if k not in card] | |
| print("missing fields:", missing) | |
| print(json.dumps(card, indent=2))"""), | |
| ("md", "Serve it at `/.well-known/agent-card.json` on your own domain."), | |
| ] | |
| NB["05_write_an_llms_txt"] = [ | |
| ("md", "# 05 Write an llms.txt\n\n" + HEAD + | |
| "\nGenerates an `llms.txt` file (the format proposed at llmstxt.org) from a small list of pages."), | |
| ("code", """site = {"title": "Demo Project", "summary": "A demo library for parsing invoices.", | |
| "sections": {"Docs": [("Quick start", "https://example.com/docs/start.md", "Install and first call"), | |
| ("API", "https://example.com/docs/api.md", "All functions")], | |
| "Optional": [("Changelog", "https://example.com/changelog.md", "")]}} | |
| lines = [f"# {site['title']}", "", f"> {site['summary']}", ""] | |
| for section, links in site["sections"].items(): | |
| lines.append(f"## {section}") | |
| lines += [f"- [{t}]({u})" + (f": {d}" if d else "") for t, u, d in links] | |
| lines.append("") | |
| llms_txt = "\\n".join(lines) | |
| print(llms_txt)"""), | |
| ("code", """assert llms_txt.startswith("# ") and "\\n> " in llms_txt | |
| print("ok")"""), | |
| ] | |
| NB["06_score_tool_calls_against_a_mock"] = [ | |
| ("md", "# 06 Score tool calls against a local mock\n\n" + HEAD + | |
| "\nA fully synthetic mock tool and a few tasks. A simple rule-based agent is scored on exact tool and " | |
| "argument match. Swap in your own agent. Scores here are an example, not a ranking."), | |
| ("code", """CITIES = {"Brindlemoor": 14, "Quillhaven": 21} | |
| def get_temperature(city: str) -> int: | |
| return CITIES[city] | |
| TASKS = [ | |
| {"prompt": "What is the temperature in Brindlemoor?", "expect": ("get_temperature", {"city": "Brindlemoor"})}, | |
| {"prompt": "Temperature in Quillhaven please", "expect": ("get_temperature", {"city": "Quillhaven"})}, | |
| {"prompt": "Tell me a joke", "expect": None}, | |
| ] | |
| def rule_agent(prompt): | |
| for c in CITIES: | |
| if c in prompt: | |
| return ("get_temperature", {"city": c}) | |
| return None"""), | |
| ("code", """hits = sum(rule_agent(t["prompt"]) == t["expect"] for t in TASKS) | |
| print(f"{hits}/{len(TASKS)} exact matches") | |
| for t in TASKS: | |
| call = rule_agent(t["prompt"]) | |
| print(t["prompt"], "->", call, "=", get_temperature(**call[1]) if call else "no tool")"""), | |
| ] | |
| def build(): | |
| ROOT.mkdir(exist_ok=True) | |
| for name, cells in NB.items(): | |
| nb = nbf.v4.new_notebook() | |
| nb.metadata = {"kernelspec": {"name": "python3", "display_name": "Python 3", "language": "python"}, | |
| "language_info": {"name": "python"}} | |
| nb.cells = [nbf.v4.new_markdown_cell(s) if k == "md" else nbf.v4.new_code_cell(s) for k, s in cells] | |
| for c in nb.cells: | |
| c.metadata = {} | |
| c.pop("id", None) | |
| nb.nbformat_minor = 4 | |
| nbf.write(nb, ROOT / f"{name}.ipynb") | |
| return sorted(ROOT.glob("*.ipynb")) | |
| if __name__ == "__main__": | |
| print("\n".join(str(p.name) for p in build())) | |