Learn › Local AI Agents: Hermes 3 and the Model Context Protocol › Capstone: A Production Local Research Agent

Capstone: A Production Local Research Agent

Advanced 🕐 15 min Lesson 12 of 12
What you'll learn
  • Assemble the complete notes_server.py with add_note, list_notes, get_note, search_notes, and the notes schema resource
  • Assemble the complete agent.py with all error handling, conversation memory, AsyncExitStack server management, and a debug flag
  • Run the capstone agent against at least three test queries that exercise the filesystem, fetch, and notes servers
  • Identify two ways to extend the agent: adding another MCP server to the SERVERS list and swapping the model in the MODEL constant

What You Are Building

This capstone assembles the components from every lesson in this track into a single production agent. The agent can:

  • Read and write files in a designated workspace via the filesystem MCP server
  • Fetch web pages by URL via the fetch MCP server
  • Store and retrieve structured research notes via your custom notes server
  • Remember previous conversations across sessions via persisted history
  • Recover from tool errors automatically
  • Handle malformed tool calls without crashing

Everything runs locally. No cloud requests leave your machine unless a tool explicitly fetches a URL.

Project Structure

The final project has four files:

mcp-agent/
├── notes_server.py        # your custom MCP server (Lessons 3 and 5)
├── agent.py               # the agent loop (Lessons 10 and 11)
├── workspace/             # directory the filesystem server can access
├── notes.json             # created automatically by notes_server.py
└── conversation_history.json  # created automatically by agent.py

The Complete notes_server.py

Incorporate all additions from Lessons 3 and 5:

import json
from datetime import datetime
from pathlib import Path
from typing import Optional
from fastmcp import FastMCP

mcp = FastMCP("Notes")
NOTES_FILE = Path("notes.json")


def _load() -> list:
    if not NOTES_FILE.exists():
        return []
    return json.loads(NOTES_FILE.read_text())


def _save(notes: list) -> None:
    NOTES_FILE.write_text(json.dumps(notes, indent=2))


@mcp.tool
def add_note(title: str, content: str, tags: Optional[str] = None) -> str:
    """Save a new research note. Optionally add comma-separated tags."""
    notes = _load()
    note = {
        "id": len(notes) + 1,
        "title": title,
        "content": content,
        "tags": [t.strip() for t in tags.split(",")] if tags else [],
        "created": datetime.now().isoformat(),
    }
    notes.append(note)
    _save(notes)
    return f"Note {note['id']} saved: {title}"


@mcp.tool
def list_notes(tag: Optional[str] = None) -> str:
    """List all saved notes. Optionally filter by tag."""
    notes = _load()
    if tag:
        notes = [n for n in notes if tag in n.get("tags", [])]
    if not notes:
        return "No notes found."
    lines = [f"[{n['id']}] {n['title']} ({n['created'][:10]})" for n in notes]
    return "
".join(lines)


@mcp.tool
def get_note(note_id: int) -> str:
    """Get the full content of a note by its ID. Call list_notes first to find valid IDs."""
    notes = _load()
    for note in notes:
        if note["id"] == note_id:
            tags = ", ".join(note.get("tags", [])) or "none"
            return f"# {note['title']}
Tags: {tags}
Date: {note['created']}

{note['content']}"
    raise ValueError(f"Note {note_id} not found. Call list_notes to see available IDs.")


@mcp.tool
def search_notes(query: str) -> str:
    """Search note titles and content for a keyword."""
    notes = _load()
    q = query.lower()
    matches = [n for n in notes if q in n["title"].lower() or q in n["content"].lower()]
    if not matches:
        return f"No notes matched {query!r}."
    lines = [f"[{n['id']}] {n['title']}" for n in matches]
    return "
".join(lines)


@mcp.resource("notes://schema")
def notes_schema() -> str:
    """The structure of a note stored by this server."""
    return "id (int), title (str), content (str), tags (list), created (ISO datetime)"


if __name__ == "__main__":
    mcp.run()

The Complete agent.py

import asyncio
import json
import re
import sys
from contextlib import AsyncExitStack
from pathlib import Path

import requests
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

OLLAMA_URL = "http://localhost:11434/v1/chat/completions"
MODEL = "hermes3"
MAX_TURNS = 15
HISTORY_FILE = Path("conversation_history.json")
WORKSPACE = Path("workspace")

SERVERS = [
    {"name": "notes", "cmd": "python", "args": ["notes_server.py"]},
    {
        "name": "filesystem",
        "cmd": "npx",
        "args": ["-y", "@modelcontextprotocol/server-filesystem", str(WORKSPACE.resolve())],
    },
    {"name": "fetch", "cmd": "npx", "args": ["-y", "@modelcontextprotocol/server-fetch"]},
]


def call_ollama(messages: list) -> str:
    resp = requests.post(
        OLLAMA_URL,
        json={"model": MODEL, "messages": messages, "temperature": 0.1, "stream": False},
        timeout=180,
    )
    resp.raise_for_status()
    return resp.json()["choices"][0]["message"]["content"]


def parse_tool_call(text: str) -> dict | None:
    match = re.search(r"<tool_call>s*({.*?})s*</tool_call>", text, re.DOTALL)
    if not match:
        return None
    try:
        return json.loads(match.group(1))
    except json.JSONDecodeError as e:
        return {"_parse_error": str(e)}


def mcp_tool_to_hermes(tool) -> dict:
    return {
        "type": "function",
        "function": {
            "name": tool.name,
            "description": tool.description or "",
            "parameters": tool.inputSchema,
        },
    }


def build_system_prompt(all_tools: list) -> str:
    tools_json = json.dumps([mcp_tool_to_hermes(t) for t in all_tools], indent=2)
    return (
        "You are a function calling AI model. You are provided with function "
        "signatures within <tools></tools> XML tags. You may call one or more "
        "functions to assist with the user query. Do not make assumptions about "
        "what values to plug into functions.

"
        f"<tools>
{tools_json}
</tools>

"
        "For each function call return a JSON object with function name and "
        "arguments within <tool_call></tool_call> XML tags:
"
        "<tool_call>
"
        "{"name": "function_name", "arguments": {"arg1": "value1"}}
"
        "</tool_call>

"
        "If no tool is relevant, respond in natural language."
    )


def load_history() -> list:
    try:
        return json.loads(HISTORY_FILE.read_text())
    except (FileNotFoundError, json.JSONDecodeError):
        return []


def save_history(messages: list) -> None:
    persistent = [m for m in messages if m["role"] in ("user", "assistant")]
    HISTORY_FILE.write_text(json.dumps(persistent[-40:], indent=2))


async def run_agent(user_query: str, debug: bool = False):
    WORKSPACE.mkdir(exist_ok=True)
    async with AsyncExitStack() as stack:
        all_tools = []
        tool_registry = {}

        for srv in SERVERS:
            params = StdioServerParameters(command=srv["cmd"], args=srv["args"])
            read, write = await stack.enter_async_context(stdio_client(params))
            session = await stack.enter_async_context(ClientSession(read, write))
            await session.initialize()
            result = await session.list_tools()
            for tool in result.tools:
                all_tools.append(tool)
                tool_registry[tool.name] = session
            print(f"[{srv['name']}] {len(result.tools)} tools")

        system_prompt = build_system_prompt(all_tools)
        history = load_history()
        messages = [
            {"role": "system", "content": system_prompt},
            *history,
            {"role": "user", "content": user_query},
        ]

        for turn in range(MAX_TURNS):
            if debug:
                print(f"
[turn {turn + 1}] calling Ollama...")
            response = call_ollama(messages)
            messages.append({"role": "assistant", "content": response})

            if debug:
                print(f"[response] {response[:200]}...")

            tool_call = parse_tool_call(response)
            if tool_call is None:
                save_history(messages)
                return response

            if "_parse_error" in tool_call:
                messages.append({
                    "role": "user",
                    "content": "The tool_call JSON had a syntax error. Please retry with valid JSON.",
                })
                continue

            tool_name = tool_call["name"]
            tool_args = tool_call.get("arguments", {})
            print(f"[tool] {tool_name}({json.dumps(tool_args)})")

            session = tool_registry.get(tool_name)
            if session is None:
                tool_result = f"Error: tool {tool_name!r} not found."
            else:
                call_result = await session.call_tool(tool_name, arguments=tool_args)
                tool_result = (call_result.content[0].text
                               if call_result.content else "No output.")
                if call_result.isError:
                    print(f"[tool error] {tool_result}")

            messages.append({
                "role": "tool",
                "content": (
                    f"<tool_response>
"
                    f"{json.dumps({'name': tool_name, 'content': tool_result})}
"
                    f"</tool_response>"
                ),
            })

        save_history(messages)
        return "Reached the turn limit without a final answer."


if __name__ == "__main__":
    args = sys.argv[1:]
    debug = "--debug" in args
    args = [a for a in args if a != "--debug"]
    query = " ".join(args) or "What can you help me with?"
    answer = asyncio.run(run_agent(query, debug=debug))
    print("
--- Answer ---")
    print(answer)

Test Queries to Try

Once the agent is running, try these queries to exercise the full tool set:

python agent.py "Save a note titled MCP Summary with the key points from today"
python agent.py "List all my notes"
python agent.py "Fetch https://modelcontextprotocol.io and save a summary as a note"
python agent.py "Create a file called research.md in the workspace with a list of my notes"
python agent.py "What notes do I have about MCP?"

The last query uses conversation memory — it will find the note saved in an earlier session. Try the debug flag on a complex query to see the full reasoning chain:

python agent.py --debug "Read my notes, fetch the MCP docs, and write a comparison"

What You Have Built

This track covered the full local AI agent stack from first principles:

  • MCP foundations (L1–L2): architecture, participants, transports, and the JSON-RPC protocol underneath
  • Building servers (L3–L5): FastMCP setup, tool definitions with type-driven schemas, resources, and prompt templates
  • Testing and extending (L6): MCP Inspector for interactive testing, official MCP servers for filesystem and web access
  • Hermes 3 (L7–L8): pulling and configuring the model, the ChatML conversation format, and the exact tool_call and tool_response protocol
  • The agent (L9–L11): Python MCP clients with AsyncExitStack, schema translation, the agent loop, error handling, and conversation memory

The same pattern — an open-weight tool-calling model, MCP servers for capabilities, a Python agent loop — scales from a single-tool script to a multi-server agent handling complex research workflows. Swap Hermes 3 for any other Ollama-compatible tool-calling model; add more MCP servers from the official library or build your own; deploy the agent on a Vast.ai GPU for remote access from a web UI. The core architecture stays the same.

Key takeaways
  • The complete agent is four files: notes_server.py, agent.py, workspace/ directory, and two auto-generated JSON files — the architecture is minimal by design
  • Any MCP server from the official library is one SERVERS entry away — the agent discovers its tools automatically on startup and routes calls without any other changes
  • Swapping the model is one constant change: set MODEL to any Ollama model that supports tool calling, such as qwen2.5:7b or llama3.1:8b
  • The agent loop pattern taught in this track is model-agnostic and transport-agnostic — the same Python structure works with any tool-calling LLM and any mix of stdio and HTTP MCP servers
Learn more every week Get 5 hand-picked prompts + new AI tools every Monday. Free.