zzstoatzz commited on
Commit
0882194
·
1 Parent(s): 8057dc1

merge conflict

Browse files
Files changed (2) hide show
  1. examples/memory.py +122 -0
  2. src/fastmcp/cli/cli.py +7 -6
examples/memory.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ filesystem mcp server with basic memory capabilities.
3
+ keeps a user profile that can be updated and summarized by an llm.
4
+ """
5
+
6
+ import os
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+ from typing import Annotated
10
+
11
+ from pydantic import BaseModel, Field
12
+ from pydantic_ai import Agent
13
+
14
+ from fastmcp import FastMCP
15
+
16
+ MAX_MEMORIES = 3
17
+
18
+
19
+ class Memory(BaseModel):
20
+ """a single memory/observation about the user"""
21
+
22
+ content: str
23
+ timestamp: float
24
+ importance: Annotated[int, Field(ge=1, le=5)] = Field(default=3)
25
+
26
+
27
+ class Profile(BaseModel):
28
+ """user profile built from memories"""
29
+
30
+ memories: list[Memory] = Field(default_factory=list, max_length=MAX_MEMORIES)
31
+ summary: str = Field(default="")
32
+
33
+
34
+ class MemoryUpdate(BaseModel):
35
+ """llm analysis of how to update the profile"""
36
+
37
+ keep_indices: list[int] = Field(description="indices of memories to keep")
38
+ new_memory: Memory = Field(description="processed version of the new memory")
39
+ updated_summary: str = Field(description="brief summary of all memories")
40
+
41
+
42
+ memory_agent = Agent(
43
+ "openai:gpt-4o",
44
+ result_type=MemoryUpdate,
45
+ system_prompt="""
46
+ you help maintain a concise user memory profile. when given a new memory:
47
+ 1. analyze its importance relative to existing memories
48
+ 2. if we're at max capacity of memories, decide which to keep
49
+ 3. provide a brief summary of all memories
50
+ focus on keeping the most important and relevant information.
51
+ """,
52
+ )
53
+
54
+ mcp = FastMCP("memory", dependencies=["pydantic-ai-slim[openai]"])
55
+
56
+ PROFILE_DIR = (
57
+ Path.home() / ".fastmcp" / os.environ.get("USER", "anon") / "memory"
58
+ ).resolve()
59
+ PROFILE_DIR.mkdir(parents=True, exist_ok=True)
60
+
61
+
62
+ @mcp.tool()
63
+ async def remember(
64
+ content: Annotated[str, Field(description="new observation/memory to store")],
65
+ importance: Annotated[int, Field(ge=1, le=5, description="importance (1-5)")],
66
+ ) -> str:
67
+ """store a new memory/observation about the user"""
68
+ profile_path = PROFILE_DIR / "profile.json"
69
+
70
+ if profile_path.exists():
71
+ profile = Profile.model_validate_json(profile_path.read_text())
72
+ else:
73
+ profile = Profile()
74
+
75
+ new_memory = Memory(
76
+ content=content,
77
+ timestamp=datetime.now(UTC).timestamp(),
78
+ importance=importance,
79
+ )
80
+
81
+ if len(profile.memories) >= MAX_MEMORIES:
82
+ result = await memory_agent.run(
83
+ f"""
84
+ new memory: {content} (importance: {importance})
85
+
86
+ current memories:
87
+ {[f"{i}: {m.content} (importance: {m.importance})"
88
+ for i, m in enumerate(profile.memories)]}
89
+ """
90
+ )
91
+
92
+ profile.memories = [profile.memories[i] for i in result.data.keep_indices]
93
+ profile.memories.append(result.data.new_memory)
94
+ profile.summary = result.data.updated_summary
95
+ else:
96
+ profile.memories.append(new_memory)
97
+
98
+ profile_path.write_text(profile.model_dump_json(indent=2))
99
+ return f"remembered: {content}"
100
+
101
+
102
+ @mcp.tool()
103
+ async def read_profile() -> str:
104
+ """read and display the current memory profile"""
105
+ profile_path = PROFILE_DIR / "profile.json"
106
+ if not profile_path.exists():
107
+ return "no profile found"
108
+
109
+ profile = Profile.model_validate_json(profile_path.read_text())
110
+
111
+ output = ["current memories:"]
112
+ for i, memory in enumerate(profile.memories):
113
+ output.append(
114
+ f"{i}. {memory.content} "
115
+ f"(importance: {memory.importance}, "
116
+ f"timestamp: {datetime.fromtimestamp(memory.timestamp, UTC)})"
117
+ )
118
+
119
+ if profile.summary:
120
+ output.append(f"\nsummary: {profile.summary}")
121
+
122
+ return "\n".join(output)
src/fastmcp/cli/cli.py CHANGED
@@ -6,11 +6,11 @@ import os
6
  import subprocess
7
  import sys
8
  from pathlib import Path
9
- from typing import Optional, Tuple, Dict
10
 
 
11
  import typer
12
  from typing_extensions import Annotated
13
- import dotenv
14
 
15
  from fastmcp.cli import claude
16
  from fastmcp.utilities.logging import get_logger
@@ -425,10 +425,11 @@ def install(
425
  # Load from .env file if specified
426
  if env_file:
427
  try:
428
- env_values = dotenv.dotenv_values(env_file)
429
- env_dict.update(
430
- (k, str(v)) for k, v in env_values.items() if v is not None
431
- )
 
432
  except Exception as e:
433
  logger.error(f"Failed to load .env file: {e}")
434
  sys.exit(1)
 
6
  import subprocess
7
  import sys
8
  from pathlib import Path
9
+ from typing import Dict, Optional, Tuple
10
 
11
+ import dotenv
12
  import typer
13
  from typing_extensions import Annotated
 
14
 
15
  from fastmcp.cli import claude
16
  from fastmcp.utilities.logging import get_logger
 
425
  # Load from .env file if specified
426
  if env_file:
427
  try:
428
+ env_dict |= {
429
+ k: v
430
+ for k, v in dotenv.dotenv_values(env_file).items()
431
+ if v is not None
432
+ }
433
  except Exception as e:
434
  logger.error(f"Failed to load .env file: {e}")
435
  sys.exit(1)