AI Hints
Home›MCP Tutorial›Async, State and Databases
MCP · Lesson 20 of 120

Tools with State

A notes server.

⏱ 2 min read▶ Video at 17:59🎓 Free
Watch this lesson in the MCP courseWatch on YouTube ↗Full MCP course

Tools can share data inside the server. A notes server keeps a list of notes. One tool adds a note, another lists them. Both tools see the same list.

Tools with State
From the video: Tools with State
  • Shared data
  • Add a note
  • List notes

A notes server

Notes is a list that lives as long as the server. Add note appends to it. List notes returns everything. We add two notes, then list them. Run it. Both notes are there.

notes.pypython
from mcp.server.mcpserver import MCPServer
from tester import call

mcp = MCPServer("notes")
notes: list[str] = []

@mcp.tool()
def add_note(text: str) -> str:
    """Save a note."""
    notes.append(text)
    return f"saved note {len(notes)}"

@mcp.tool()
def list_notes() -> list[str]:
    """List all saved notes."""
    return notes

for t in ["Call the Leeds store", "Order more helmets"]: call(mcp, "add_note", {"text": t})
print(call(mcp, "list_notes").structured_content["result"])
Output
['Call the Leeds store', 'Order more helmets']
Also uses tester.py
import asyncio
from mcp import Client

def call(server, tool, args=None, **options):
    async def go():
        async with Client(server, **options) as client:
            return await client.call_tool(tool, args or {})
    return asyncio.run(go())

def tools(server):
    async def go():
        async with Client(server) as client:
            return (await client.list_tools()).tools
    return asyncio.run(go())

Where state lives

State in memory is lost when the server stops. With standard IO, each host starts its own server, so state isn't shared between users. For real data, use a database.

keyvalue
Memorylost on restart
stdioone server per host
Real dataa database
Good fordemos and caches

Summary

Tools in one server can share state, but memory is lost on restart. Next, a database tool.

Key takeaways
  • Shared list
  • Add and list
  • Use a database
Next up: A Database Tool — SQLite