05. Memory and Model Context Protocol (MCP)#
A fast, conceptual revision guide for 05-memory-and-mcp. Focused on how agents remember and evolve (short-term context management, semantic/episodic/procedural long-term memory, hot-path updates) and how they connect to external tools and data cleanly and safely through the Model Context Protocol (MCP) — without boilerplate code clutter.
Why Agents Need Memory & The Five Design Questions#
Revision Notes#
Reference file: memory-and-mcp-notes/memory_explained.html
Concept#
LLMs are stateless — every API call is a fresh start, and the model forgets everything the moment it finishes replying. In an agentic system made of four pillars (Model, Tools, Planning & Reasoning, and Memory), memory is what the application stores and brings back at the right time so the agent achieves context continuity, personalization, and evolution from experience.
Key Mental Models#
- The Five Memory Design Questions: Before adding memory to any agent, decide five things:
- What to store — general facts, user preferences, summaries of past events, or behavioral/style rules.
- When & who forms it — updated live on every turn by the agent, or extracted later by a background job.
- Where to store it — in the prompt/state, a relational or document DB, a key-value store, or a vector store (storage choice dictates retrieval).
- How to retrieve it — exact ID filters, semantic similarity search, or recency filters.
- How much to keep — size caps, TTLs, and pruning/summarization policies so memory does not grow unbounded.
- Memory Taxonomy:
- Short-term memory — thread-scoped conversation state within one session.
- Long-term memory — persistent across sessions, split into Semantic (what is true), Episodic (what happened), and Procedural (how to act).
Writing Memory: Hot Path vs. Background#
Hot-path updates invoke an extractor before replying so new preferences take effect on the very same turn, whereas background jobs keep turn latency low by distilling facts asynchronously.
Trade-Offs & Pitfalls#
- Hot path guarantees same-turn accuracy (essential when a user says "keep it brief from now on"), but increases latency and token cost on every turn.
- Background extraction keeps user-facing latency low and amortizes LLM calls across turns, but delays cross-session availability until the background job runs.
Short-Term Memory & Context Management#
Revision Notes#
Reference files: memory-and-mcp-code/short_term_memory.ipynb, memory-and-mcp-notes/memory_explained.html, memory-and-mcp-notes/memory_mcp_code_explainer.html
Concept#
Short-term memory is thread-scoped: it holds the ongoing conversation history (plus uploaded files, retrieved documents, and intermediate artifacts) inside a single session. Because LLMs are stateless, "remembering" earlier turns works by re-sending previous messages on every call. In LangGraph, this lives in the graph's state and is persisted per thread_id by a checkpointer (InMemorySaver for local demos; database-backed checkpointers like PostgreSQL in production) so threads stay isolated and resumable.
Four Context-Management Strategies#
- Full Conversation Buffer:
- Appends every
HumanMessageandAIMessageto a list and sends the entire history each turn. - Preserves 100% of context, making it ideal for short chats, but grows linearly in token cost, latency, and eventually hits the context window limit.
- Appends every
- Trimming (Sliding Window):
- Keeps only the most recent messages within a token budget via
trim_messages(..., strategy="last", token_counter=count_tokens_approximately, start_on="human", allow_partial=False). - Crucial distinction: Trimming only changes what the model sees on this call — the underlying saved history remains intact.
- Automatic and zero extra LLM cost, but silently drops early facts (like the user's name or budget).
- Keeps only the most recent messages within a token budget via
- Deletion (Selective Removal):
- Removes specific messages by index/criteria (e.g., stripping verbose middle explanations or giant tool outputs while keeping turn 1's user info).
- Inside LangGraph, returning
RemoveMessage(id=...)lets theadd_messagesreducer permanently remove those messages from saved state. - Gives precise control, but requires explicit rules or heuristics to decide what is safe to drop.
- Summarization (Compression):
- When message count crosses a threshold, an LLM condenses older messages into a concise summary stored as a
SystemMessage, paired with the most recent turns verbatim. - Retains key facts (name, constraints, decisions) across long conversations, at the cost of extra LLM calls and potential loss of subtle details.
- When message count crosses a threshold, an LLM condenses older messages into a concise summary stored as a
Trade-Offs & Pitfalls#
- Recency vs. importance: Pure trimming favors recency and breaks when critical constraints were stated early; pure summarization can blur exact numbers or IDs.
- Practical production hybrid: Pin critical structured facts (name, budget, preferences) in long-term memory or a dedicated state field, summarize the middle of the thread, and keep the last few turns word-for-word.
- Message-role validity: When trimming, always enforce
start_on="human"andallow_partial=Falseso the model never receives an orphanedAIMessageor a half-cut message.
Code Reference#
import os
from getpass import getpass
# Prompt interactively in notebooks only when the API key isn't already exported,
# preventing credentials from being hard-coded in version-controlled cells.
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass("Enter your OpenAI API key: ")
# --- next cell ---
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
# reasoning_effort="none": answer straight away, no hidden "thinking" tokens
# (keeps multi-turn chat latency and token cost low when deep reasoning isn't needed).
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
# --- next cell ---
# In-memory short-term buffer: LLMs are stateless, so we must replay prior turns
# on every API call if we want the model to remember earlier context.
message_buffer = []
def chat(user_input):
"""Chat function that maintains conversation history."""
# Append the new user turn BEFORE invoking so the model sees the full history
message_buffer.append(HumanMessage(content=user_input))
# -> turn 0: [HumanMessage("Hi! My name is Alice...")]; turn 4: 9 messages total
response = llm.invoke(message_buffer)
# -> turn 0: AIMessage("Hi Alice! Welcome..."); turn 4: AIMessage("Your name is Alice!")
# Persist the AIMessage reply so future turns know what the assistant already said
message_buffer.append(response)
# -> len(message_buffer) grows 2 -> 4 -> 6 -> 8 -> 10 across the 5 turns
return response.content
def dump_memory():
"""Display all messages in the buffer."""
print("=" * 50)
print("MEMORY DUMP")
print("=" * 50)
# Truncate each message to 100 chars so the inspection view stays scannable
for i, msg in enumerate(message_buffer):
role = "Human" if isinstance(msg, HumanMessage) else "AI"
print(f"[{i}] {role}: {msg.content[:100]}{'...' if len(msg.content) > 100 else ''}")
print(f"\nTotal messages: {len(message_buffer)}")
print("=" * 50)
# --- next cell ---
# 5-turn conversation: turn 0 plants a personal fact ("Alice") and turn 4 tests
# whether the buffer preserved it across 3 unrelated intermediate turns.
conversations = [
"Hi! My name is Alice and I'm learning about AI.",
"What are the main types of machine learning?",
"Can you explain supervised learning with an example?",
"What's the difference between classification and regression?",
"Thanks! Can you remind me what my name is?"
]
for user_msg in conversations:
print(f"Human: {user_msg}")
response = chat(user_msg)
print(f"AI: {response}\n")
# --- next cell ---
# Full memory dump - all 10 messages (5 human + 5 AI) live in RAM for this session
dump_memory()
# ... (see full file: short_term_memory.ipynb)
Human: Hi! My name is Alice and I'm learning about AI.
AI: Hi Alice! Welcome to the world of AI. It's an exciting field—feel free to ask any questions as you learn!
Human: What are the main types of machine learning?
AI: The three main types of machine learning are supervised learning, unsupervised learning, and reinforcement learning.
Human: Can you explain supervised learning with an example?
AI: Supervised learning trains a model on labeled input-output pairs. For example, feeding emails labeled "spam" or "not spam" so the model learns to classify new emails.
Human: What's the difference between classification and regression?
AI: Classification predicts discrete categories (like spam vs. not spam), while regression predicts continuous numerical values (like house prices).
Human: Thanks! Can you remind me what my name is?
AI: Your name is Alice!
==================================================
MEMORY DUMP
==================================================
[0] Human: Hi! My name is Alice and I'm learning about AI.
[1] AI: Hi Alice! Welcome to the world of AI. It's an exciting field—feel free to ask any questions as you l...
[2] Human: What are the main types of machine learning?
[3] AI: The three main types of machine learning are supervised learning, unsupervised learning, and reinfor...
[4] Human: Can you explain supervised learning with an example?
[5] AI: Supervised learning trains a model on labeled input-output pairs. For example, feeding emails labele...
[6] Human: What's the difference between classification and regression?
[7] AI: Classification predicts discrete categories (like spam vs. not spam), while regression predicts cont...
[8] Human: Thanks! Can you remind me what my name is?
[9] AI: Your name is Alice!
Total messages: 10
==================================================
Long-Term Memory: Semantic, Episodic, and Procedural#
Revision Notes#
Reference files: memory-and-mcp-notes/memory_explained.html, memory-and-mcp-code/memory_demo_1.py
Concept#
Long-term memory persists across sessions and threads so an agent remembers users, domain facts, past outcomes, and proven workflows over days or months. In LangGraph, this is backed by a Store organized into namespaces (e.g., ("u_42", "profile")) so one user's memories never leak into another's.
The Three Types of Long-Term Memory#
- **Semantic Memory — *"What is true?"***
- Meaning: General world/domain facts and user attributes independent of a specific event (e.g., 30-day return policy, shipping times, product categories, "user is vegetarian").
- Why it matters: Prevents guessing, enforces policy consistency across conversations, and enables abstract reasoning over categories (e.g.,
Laptop → Electronics → 10-day return window). - Representations & storage:
- Symbolic / structured — key-value stores or knowledge graphs (RDF triples
(subject, relation, object)+ ontologies) in SQL or Document DBs for exact lookups and multi-hop reasoning. - Vector-based — embeddings in a Vector DB (FAISS, Pinecone, Chroma) for fuzzy meaning-based search without keyword overlap.
- Hybrid — knowledge graph for structure plus embeddings for flexible recall.
- Symbolic / structured — key-value stores or knowledge graphs (RDF triples
- **Episodic Memory — *"What happened last time?"***
- Meaning: Specific past events, interactions, and action trajectories with their outcomes (a diary of episodes).
- Why it matters: Enables reflection on past failures (don't repeat broken tool calls), case-based reasoning (few-shot learning from past successful trajectories), and personalization (e.g., "last order was late").
- Failure vs. success path pattern:
- Failed episode: Calling the courier's shipping API directly with store order
#78910→"Invalid ID format". - Succeeded episode: Validate/normalize ID first (
ORD-78910) → look up in the order DB → confirm status. - Retrieval: On a new tracking query, retrieve both episodes, compare outcomes, and follow the winning path.
- Failed episode: Calling the courier's shipping API directly with store order
- Representations & storage: Structured logs (SQL
episodes+stepstables), JSON documents (MongoDB/Firestore), vector embeddings for "similar past situations", or causal/temporal graphs.
- **Procedural Memory — *"How do I do this?"***
- Meaning: Reusable skills, step-by-step workflows, fallback logic, and refined system-prompt instructions.
- Why it matters: Ensures consistent multi-step execution without reinventing the wheel, supports adaptive fallbacks (e.g., primary DB → cache → shipping API), and enables skill chaining (composing smaller proven procedures into larger workflows like refunds).
- Representations & storage: IF-THEN rules, Finite State Machines (FSMs — a LangGraph
StateGraphwith conditional edges), neural RL policies, or hybrid plans stored in versioned SQL/Document DBs (versioning allows rollback when procedures evolve).
Combining All Three in memory_demo_1.py#
In memory_demo_1.py, sequential LangGraph nodes populate shared domain policies, user-specific history, and deterministic order-lookup procedures into AgentState before final synthesis.
Trade-Offs & Pitfalls#
- Transient failure trap in episodic memory: One failed episode does not always mean a tool path is broken (an API may have been temporarily down). Store why it failed and weigh multiple episodes rather than blindly banning a path after one error.
- Inspectability of procedural memory: For production LLM agents touching real customer actions, explicit readable workflows (LangGraph graphs, versioned JSON procedures, prompt instructions) are far safer to audit and test than opaque neural policies.
Code Reference#
import json
from typing import Any, Dict, TypedDict
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph
load_dotenv()
# The model that writes the final reply using the retrieved memory context
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
# Shared LangGraph state: each node reads the identifiers/query and populates its
# own memory slot (semantic_facts, user_context, order_details) before synthesis.
class AgentState(TypedDict):
user_id: str
user_query: str
order_id: str
semantic_facts: Dict[str, Any]
user_context: Dict[str, Any]
order_details: Dict[str, Any]
final_response: str
class MemoryDemo:
def __init__(self):
# Semantic Memory: shared, user-agnostic domain facts (policies, catalog)
# that stay the same regardless of who is asking.
self.semantic_memory = {
"company_policies": {
"return_period": "30 days",
"shipping_time": "3-5 business days",
"customer_service_hours": "9 AM - 6 PM EST"
},
"product_categories": {
"electronics": "Includes phones, laptops, accessories",
"clothing": "Includes shirts, pants, dresses",
"books": "Includes fiction, non-fiction, educational"
}
}
# Episodic Memory: user-specific history and preferences keyed by user_id,
# allowing the agent to personalize tone, detail level, and follow-ups.
self.episodic_memory = {
"user_123": {
"name": "Alice Johnson",
"preferred_contact": "email",
"recent_interactions": [
"Asked about return policy yesterday",
"Purchased electronics last week"
],
"preferences": {
"language": "English",
"detail_level": "detailed"
}
},
"user_456": {
"name": "Bob Smith",
"preferred_contact": "sms",
"recent_interactions": [
"Complained about delayed shipping last month",
"Frequently buys clothing items",
"Requested premium shipping upgrade"
# ... (see full file: memory_demo_1.py)
$ python memory_demo_1.py
--- User: user_123 (Alice Johnson) ---
Query: Can I still return the laptop I ordered?
[retrieve_semantic] Loaded company_policies (return_period=30 days)
[retrieve_episodic] Loaded profile for Alice Johnson (detail_level=detailed, preferred_contact=email)
[retrieve_order] Loaded order ORD-101 (status=delivered, 7 days ago)
Response:
Hi Alice! Yes, you can still return your laptop from order ORD-101. Our return window is 30 days from delivery, and since you purchased it last week, you are well within the window. I can send the return label and step-by-step instructions to your preferred email address.
--- User: user_456 (Bob Smith) ---
Query: Where is my jacket order?
[retrieve_episodic] Loaded profile for Bob Smith (detail_level=brief, preferred_contact=sms)
Response:
Hi Bob — your clothing order is in transit with express shipping (3-5 business days). We'll send tracking updates via SMS.
Self-Updating Memory on the Hot Path & Persistence#
Revision Notes#
Reference files: memory-and-mcp-code/memory_demo_2.py, memory-and-mcp-notes/memory_mcp_code_explainer.html
Concept#
Static memory dictionaries go stale the moment a user's needs change. memory_demo_2.py extends the 4-node LangGraph pipeline from memory_demo_1.py by inserting an update_memory node on the hot path so the agent detects preference changes mid-conversation, updates its episodic store immediately, records an audit trail, and persists the result to disk (episodic_memory.json).
How It Works#
Key Mental Models#
- Structured JSON extraction (
json_llm): Bindingresponse_format={"type": "json_object"}forces the preference detector to emit either a cleankey → new_valuedictionary or{}when no change was requested. - Defensive parsing: Always wrap
json.loads(...)in error handling and verifyisinstance(updates, dict)so malformed model output degrades safely to "no update" instead of crashing the turn. - Same-turn reflection: Because
update_memoryruns beforegenerate_responseand refreshesstate["user_context"], the very turn in which Alice says "keep your answers brief from now on" already produces a brief reply — and Turn 3 continues respecting it. - Audit trail (
preference_history): Logging both the prior value and the new value by turn lets you debug when and why an agent's behavior shifted.
Trade-Offs & Pitfalls#
- Per-turn overhead: Running
json_llmon every turn doubles the number of LLM calls even when no preference changed (the classic hot-path cost). - Flat JSON file limits: Writing the entire dictionary to
episodic_memory.jsonis great for transparency in demos, but production multi-user systems need atomic, concurrent storage (SQL/Document DB) with per-user locking or namespaces.
Code Reference#
import copy
import json
import os
from typing import Any, Dict, Optional, TypedDict
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph
load_dotenv()
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
# Same model, but forced to reply with a valid JSON object (used by the preference
# detector node so downstream code can safely parse & merge profile updates).
json_llm = llm.bind(response_format={"type": "json_object"})
# Extends Demo 1's state with `preference_update`, enabling a write-back loop
# where newly expressed user preferences are extracted and saved to disk.
class AgentState(TypedDict):
user_id: str
user_query: str
order_id: Optional[str]
semantic_facts: Dict[str, Any]
user_context: Dict[str, Any]
order_details: Dict[str, Any]
preference_update: Dict[str, Any] # newly detected preference changes
final_response: str
# Persist episodic memory alongside this script so learned preferences survive
# across separate process runs (true long-term memory).
EPISODIC_MEMORY_FILE = os.path.join(os.path.dirname(__file__), "episodic_memory.json")
# Seed profiles used to bootstrap episodic_memory.json on first run (copied with
# copy.deepcopy so in-memory mutations never corrupt the default template).
EPISODIC_MEMORY_DEFAULT = {
"user_123": {
"name": "Alice Johnson",
"preferred_contact": "email",
"recent_interactions": [
"Asked about return policy yesterday",
"Purchased electronics last week"
],
"preferences": {
"language": "English",
"detail_level": "detailed"
}
},
"user_456": {
"name": "Bob Smith",
"preferred_contact": "sms",
"recent_interactions": [
"Complained about delayed shipping last month",
"Frequently buys clothing items"
],
"preferences": {
"language": "English",
"detail_level": "brief",
"shipping_speed": "express"
}
}
}
class MemoryDemo:
# ... (see full file: memory_demo_2.py)
$ python memory_demo_2.py
[load] Loaded episodic memory from episodic_memory.json
User (user_123): From now on please keep your answers brief and text me updates via SMS.
[detect_preferences] Extracted update: {"preferred_contact": "sms", "preferences": {"detail_level": "brief"}}
[save_memory] Updated user_123 in episodic_memory.json
Response:
Got it, Alice! I've updated your preferences to brief replies and SMS notifications.
--- Next session (re-loaded from episodic_memory.json) ---
User (user_123): What is your return policy?
[retrieve_episodic] user_123 -> detail_level=brief, preferred_contact=sms
Response:
Returns are accepted within 30 days of delivery. Let me know if you'd like an SMS link to start one.
Model Context Protocol (MCP): Why It Exists & Architecture#
Revision Notes#
Reference file: memory-and-mcp-notes/mcp_explained.html
Concept#
An LLM by itself can only generate text; real usefulness comes from external tools and data. Model Context Protocol (MCP) — introduced by Anthropic in November 2024 and donated to the Linux Foundation's Agentic AI Foundation in December 2025 — is an open, vendor-neutral standard (inspired by LSP and built on JSON-RPC 2.0) that gives every AI app one uniform plug to discover and use external capabilities.
Key Mental Models#
- Solving the
M × N→M + Nintegration problem:- Without a standard,
MAI apps connecting toNdata sources/tools requireM × Ncustom, non-reusable bridges (e.g., 10 apps × 20 tools = 200 connectors). - With MCP, each app implements an MCP client once and each service implements an MCP server once (
M + N: 10 + 20 = 30). One server works across Claude Desktop, Cursor, VS Code, and custom apps.
- Without a standard,
- Three Distinct Roles (Host, Client, Server):
The AI Host owns the LLM loop and human-in-the-loop trust boundaries, isolating external servers behind 1:1 JSON-RPC Clients to turn M×N custom integrations into M+N reusable plugs.
- Host: The only component that talks directly to the LLM. It orchestrates the agentic loop, decides which resources to inject, asks the user for confirmation on risky actions, and enforces trust boundaries.
- Client: Lives inside the host with a strict 1:1 session per server so servers stay isolated from one another. Acts as both protocol translator (JSON-RPC framing) and gatekeeper (per-tool allow-lists, audit logging).
- Server: A lightweight capability provider exposing tools, resources, and prompts. The exact same server code can run locally over
stdio(subprocess) or remotely overStreamable HTTP(which replaces the deprecatedHTTP+SSEtransport).
Trade-Offs & Pitfalls#
stdioinherits host permissions: A localstdioserver runs as a process on your machine with access to your files, SSH keys, and environment — treat installing an untrusted MCP server like installing an arbitrary executable.- No built-in authentication: MCP servers do not enforce auth by default; remote HTTP servers must layer OAuth 2.1, and local deployments must enforce least privilege and narrow server scopes.
MCP's Three Core Capabilities: Tools, Resources, and Prompts#
Revision Notes#
Reference file: memory-and-mcp-notes/mcp_explained.html
Concept#
An MCP server exposes exactly three primitives — Tools, Resources, and Prompts — separated by a single security-defining question: "Who presses the button?"
The Control Split#
- Tools (
@mcp.tool()) — Model-Controlled:- Executable actions the LLM decides to invoke on its own (
tools/list,tools/call) — e.g., searching, creating tickets, querying APIs, writing files. - Can have real-world side effects, which is why tools require the strictest authorization, validation, and human-in-the-loop checks.
- Executable actions the LLM decides to invoke on its own (
- Resources (
@mcp.resource("uri")) — Application-Controlled:- Read-only contextual data identified by a URI (e.g.,
file:///notes.txt,data://config) returning text or base64 binary with amimeType(resources/list,resources/read). - Supports URI templates (RFC 6570, e.g.,
data://users/{user_id}) and change notifications (subscriptions/listenin spec 2026-07-28, replacing olderresources/subscribe). - Injected directly by the host app without spending a tool call or adding tool-schema overhead.
- Read-only contextual data identified by a URI (e.g.,
- Prompts (
@mcp.prompt()) — User-Controlled:- Named, parameterized message templates defined on the server (
prompts/list,prompts/get) that render into{role, content}starter messages (e.g.,/code_review). - Chosen explicitly by the user (e.g., via a slash menu), capturing expert phrasing outside app code without allowing the model to self-trigger them.
- Named, parameterized message templates defined on the server (
Trade-Offs & Pitfalls#
- Don't use tools for static read-only data: Exposing reference docs or configs as tools wastes schema tokens and forces extra tool-call round trips; expose them as resources instead.
- Prompt ≠ Tool: Rendering a prompt only produces starter messages for the host to send to the model — it does not execute actions or generate an LLM reply on its own.
MCP Protocol Lifecycle & Building with FastMCP#
Revision Notes#
Reference files: memory-and-mcp-code/fastmcp_demo_v1.ipynb, memory-and-mcp-notes/mcp_explained.html, memory-and-mcp-notes/memory_mcp_code_explainer.html
Concept#
FastMCP (from fastmcp import FastMCP, or MCPServer in the official mcp SDK) lets you build MCP servers in a FastAPI-like style: decorate plain Python functions with @mcp.tool(), and FastMCP automatically compiles function names, type hints, and docstrings into JSON-RPC handlers and JSON Schemas.
Protocol Lifecycle#
- Handshake / Capability Negotiation:
- Legacy 3-step handshake:
initializerequest → server capabilities response →notifications/initialized(a JSON-RPC notification with noid). Allowed clients and servers to evolve independently by ignoring unsupported capabilities. - Stateless MCP (spec 2026-07-28): Removes the mandatory 3-step handshake; each request carries a
_metaheader with protocol version and client capabilities, and clients can optionally callserver/discoverup front. Client libraries (async with Client(...)) abstract both transparently.
- Legacy 3-step handshake:
- Tool Discovery (
tools/list):- Returns each tool's
name,description, andinputSchema(input_schemain Python). - The description is the LLM's only interface: Write specific descriptions, explicitly state when not to use the tool, document parameters via
Field(...), stay honest, and never embed hidden commands.
- Returns each tool's
- Tool Invocation (
tools/call) & Error Distinction:- Returns typed content blocks (
text,image,resource, orstructuredContentwith anoutputSchema). - Tool error (
isError: true/is_error=True) vs. JSON-RPC protocol error:- A tool error is a valid MCP result (e.g., Pydantic validation failure like
max_results=500exceeding100, or an upstream API timeout) with a readable message so the LLM can self-correct and retry. - A JSON-RPC protocol error means the wire request itself was malformed (e.g., calling a nonexistent method).
- A tool error is a valid MCP result (e.g., Pydantic validation failure like
- Returns typed content blocks (
End-to-End FastMCP Host Flow (fastmcp_demo_v1.ipynb)#
- In-memory vs. network testing:
Client(mcp)connects directly in memory for notebooks and tests using the exact same API asstdioorStreamable HTTP— switching transport requires changing onlymcp.run(transport=...).
Code Reference#
import getpass
import os
# Avoid hard-coding API keys in notebook cells; prompt only if not set in env.
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ")
# --- next cell ---
import json
import requests
from openai import OpenAI
from fastmcp import FastMCP
openai_client = OpenAI()
MODEL = "gpt-6-luna"
# ---------------------------------------------------------------------------
# FastMCP server — tools are plain functions decorated with @mcp.tool()
# FastMCP inspects type annotations and docstrings to auto-generate JSON schemas
# that any MCP-compatible client or LLM host can discover and call.
# ---------------------------------------------------------------------------
mcp = FastMCP("MCP Demo Server")
# Open-Meteo returns numeric WMO weather codes; mapping them here gives the LLM
# human-readable conditions instead of opaque integers.
WMO_CODES = {
0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
45: "Fog", 48: "Icy fog",
51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle",
61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
71: "Slight snow", 73: "Moderate snow", 75: "Heavy snow", 77: "Snow grains",
80: "Slight showers", 81: "Moderate showers", 82: "Violent showers",
85: "Slight snow showers", 86: "Heavy snow showers",
95: "Thunderstorm", 96: "Thunderstorm with hail", 99: "Thunderstorm with heavy hail",
}
@mcp.tool()
def get_current_time(timezone: str = "UTC") -> str:
"""Get the current time in a given IANA timezone (e.g. 'Asia/Tokyo', 'Asia/Kolkata')."""
# Standard-library zoneinfo handles DST rules accurately without external deps
from zoneinfo import ZoneInfo
from datetime import datetime
try:
tz = ZoneInfo(timezone)
now = datetime.now(tz)
# -> datetime(2026, 12, 2, 22, 25, 14, tzinfo=ZoneInfo("Asia/Tokyo"))
return f"Current time in {timezone}: {now.strftime('%Y-%m-%d %H:%M:%S %Z')}"
# -> "Current time in Asia/Tokyo: 2026-12-02 22:25:14 JST"
except Exception as e:
# Return errors as strings so the LLM can recover or ask for a valid timezone
return f"Unknown timezone '{timezone}': {e}"
@mcp.tool()
def get_weather(city: str) -> str:
"""Get current weather for a city using Open-Meteo (no API key required)."""
try:
# Step 1: resolve the city name into lat/lon via Open-Meteo's free geocoding API
geo_resp = requests.get(
"https://geocoding-api.open-meteo.com/v1/search",
params={"name": city, "count": 1, "language": "en", "format": "json"},
timeout=10,
)
geo_resp.raise_for_status()
geo_data = geo_resp.json()
# -> {"results": [{"name": "Tokyo", "country": "Japan",
# "latitude": 35.6895, "longitude": 139.6917}]}
if not geo_data.get("results"):
# ... (see full file: fastmcp_demo_v1.ipynb)
Discovered MCP tools: ['get_current_time', 'get_weather']
User: What time is it in Tokyo and what's the weather like there?
-> Tool call: get_current_time(timezone='Asia/Tokyo')
Result: Current time in Asia/Tokyo: 2026-12-02 22:25:14 JST
-> Tool call: get_weather(city='Tokyo')
Result: Tokyo, Japan: 11.4°C, Clear sky, wind 6.2 km/h
Assistant: It is currently 10:25 PM JST in Tokyo, with clear skies and a temperature of 11.4°C (wind 6.2 km/h).
MCP Security Challenges, Mitigations & Context Bloat#
Revision Notes#
Reference file: memory-and-mcp-notes/mcp_explained.html
Concept#
In traditional software, code and data are separate. In an LLM agent, everything is text, so tool descriptions and tool outputs can hijack the model's next action. The LLM is simultaneously the decision-maker and the attack surface, while every tool schema and result also competes for the context window.
Seven Security Threats & Defences#
- Prompt injection (malicious instructions hidden inside tool results) → Treat all tool outputs as untrusted data (wrap with data-only delimiters), harden system prompts, and prefer compact structured JSON over raw prose.
- Tool poisoning (malicious instructions embedded in a tool's description) → Install only audited servers, review descriptions before enabling, and run a content-security scanner to reject commanding/secret-seeking text.
- Confused deputy (an over-privileged server tricked via the LLM into abusing its authority) → Enforce least privilege, split read-only servers from write-capable servers, and require human-in-the-loop confirmation for destructive actions.
- Rug pull (a server passes initial review, then a silent update turns malicious — e.g., the September 2025 fake
postmark-mcpnpm package that BCC'd emails to an attacker starting in v1.0.16) → Pin server versions, hash-pin reviewed tool descriptions, and audit updates like supply-chain dependencies. - Cross-server contamination (malicious server A injects text that steers how the model uses trusted server B) → Isolate sensitive/write-capable servers in separate sessions and label context by origin.
- Missing authentication / authorization (no built-in auth;
stdioinherits user rights) → Use OAuth 2.1 for remote HTTP servers, hash-verify local server binaries, and enforce per-tool allow-lists + full audit logs in the MCP client. - Data exfiltration (combining a data-reading tool with a network-sending tool) → Separate data-reading and network-egress capabilities, restrict outbound network access at the OS level, and never expose credentials as MCP resources.
Pitfall: Tool Hints Are Not Security#
- Annotations like
readOnlyHintordestructiveHintare self-reported by the server. A malicious server can label a delete tool as read-only — use hints for UI display, never for safety enforcement.
Context Bloat & Design Choices#
- Why bloat hurts: Connecting dozens of tools injects thousands of schema tokens into every turn before the user even speaks (and intermediate tool outputs pile up further), increasing cost, latency, and tool-selection errors.
- Core design mitigations:
- Lazy loading & domain grouping: Load only the server(s) relevant to the active task instead of exposing every connected server at once.
- Move read-only data to resources: Eliminates tool schemas and repeated tool calls for static context.
- Compact outputs & pruning: Return concise structured JSON, summarize/paginate large results, and prune completed intermediate tool calls in long loops.
- Balanced granularity & trust boundaries: Avoid one giant catch-all server or 100 micro-tools; split servers by trust level (read vs. write), not convenience.
How All Building Blocks Connect#
Revision Notes#
A real-world AI agent brings Memory and MCP together inside a single host loop:
- Short-term memory keeps the current thread coherent without overflowing the context window (using checkpointers plus trimming, deletion, or summarization).
- Long-term memory gives the agent continuity and improvement across sessions: semantic facts ground truth, episodic history recalls user preferences and past wins/failures (updated live on the hot path or asynchronously in the background), and procedural workflows encode reliable multi-step skills.
- MCP standardizes how the agent's host reaches external tools, read-only resources, and user prompts (
M + Ninstead ofM × N), while least-privilege server splitting, version/hash pinning, human-in-the-loop checks, and lazy-loaded schemas keep the system both secure and token-efficient.
Quick Self-Check Questions#
Self-Check Questions#
What is the difference between trimming and deleting in short-term memory?
Trimming only slices what is sent to the LLM for the current call while leaving the saved history untouched; deleting (e.g., via LangGraph's RemoveMessage) permanently removes messages from stored state.
When should you update long-term memory on the hot path versus in the background?
Use the hot path when a change must take effect immediately in the same turn (such as a user changing response verbosity or language); use background updates when low latency matters more and cross-session availability can wait.
How do semantic, episodic, and procedural memory differ for a support agent?
Semantic = general facts ("30-day return window"); Episodic = specific past events/outcomes ("order #78910 failed on the shipping API last week"); Procedural = reusable know-how ("validate ID → check DB → fallback to cache").
How does MCP solve the M × N integration problem, and what are its three architectural roles?
Each AI app implements one MCP client protocol and each tool/data source implements one MCP server (M + N). The Host owns the LLM and trust boundaries, each Client manages one 1:1 server session and gatekeeping, and each Server exposes capabilities.
Why does MCP split capabilities into Tools, Resources, and Prompts?
Control and security: Tools are model-controlled (can cause side effects, need strict checks), Resources are app-controlled read-only context (no schema overhead), and Prompts are user-controlled reusable templates.
What is the difference between isError: true and a JSON-RPC protocol error in MCP?
isError: true is a normal tool-call result carrying a readable failure reason (e.g., failed Pydantic validation) so the LLM can fix its arguments and retry; a JSON-RPC protocol error means the wire request itself was invalid (e.g., unknown method).
What is an MCP "rug pull", and how do you defend against it?
A server behaves safely during initial review, then a silent update injects malicious behavior or poisoned tool descriptions (like postmark-mcp v1.0.16). Defend by pinning server versions, hashing and verifying reviewed tool descriptions, scanning for commanding text, and enforcing least privilege with client-side allow-lists.