basic-memory 0.12.2__py3-none-any.whl → 0.13.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of basic-memory might be problematic. Click here for more details.
- basic_memory/__init__.py +2 -1
- basic_memory/alembic/env.py +1 -1
- basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +108 -0
- basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +104 -0
- basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +0 -6
- basic_memory/api/app.py +43 -13
- basic_memory/api/routers/__init__.py +4 -2
- basic_memory/api/routers/directory_router.py +63 -0
- basic_memory/api/routers/importer_router.py +152 -0
- basic_memory/api/routers/knowledge_router.py +139 -37
- basic_memory/api/routers/management_router.py +78 -0
- basic_memory/api/routers/memory_router.py +6 -62
- basic_memory/api/routers/project_router.py +234 -0
- basic_memory/api/routers/prompt_router.py +260 -0
- basic_memory/api/routers/search_router.py +3 -21
- basic_memory/api/routers/utils.py +130 -0
- basic_memory/api/template_loader.py +292 -0
- basic_memory/cli/app.py +20 -21
- basic_memory/cli/commands/__init__.py +2 -1
- basic_memory/cli/commands/auth.py +136 -0
- basic_memory/cli/commands/db.py +3 -3
- basic_memory/cli/commands/import_chatgpt.py +31 -207
- basic_memory/cli/commands/import_claude_conversations.py +16 -142
- basic_memory/cli/commands/import_claude_projects.py +33 -143
- basic_memory/cli/commands/import_memory_json.py +26 -83
- basic_memory/cli/commands/mcp.py +71 -18
- basic_memory/cli/commands/project.py +102 -70
- basic_memory/cli/commands/status.py +19 -9
- basic_memory/cli/commands/sync.py +44 -58
- basic_memory/cli/commands/tool.py +6 -6
- basic_memory/cli/main.py +1 -5
- basic_memory/config.py +143 -87
- basic_memory/db.py +6 -4
- basic_memory/deps.py +227 -30
- basic_memory/importers/__init__.py +27 -0
- basic_memory/importers/base.py +79 -0
- basic_memory/importers/chatgpt_importer.py +222 -0
- basic_memory/importers/claude_conversations_importer.py +172 -0
- basic_memory/importers/claude_projects_importer.py +148 -0
- basic_memory/importers/memory_json_importer.py +93 -0
- basic_memory/importers/utils.py +58 -0
- basic_memory/markdown/entity_parser.py +5 -2
- basic_memory/mcp/auth_provider.py +270 -0
- basic_memory/mcp/external_auth_provider.py +321 -0
- basic_memory/mcp/project_session.py +103 -0
- basic_memory/mcp/prompts/__init__.py +2 -0
- basic_memory/mcp/prompts/continue_conversation.py +18 -68
- basic_memory/mcp/prompts/recent_activity.py +20 -4
- basic_memory/mcp/prompts/search.py +14 -140
- basic_memory/mcp/prompts/sync_status.py +116 -0
- basic_memory/mcp/prompts/utils.py +3 -3
- basic_memory/mcp/{tools → resources}/project_info.py +6 -2
- basic_memory/mcp/server.py +86 -13
- basic_memory/mcp/supabase_auth_provider.py +463 -0
- basic_memory/mcp/tools/__init__.py +24 -0
- basic_memory/mcp/tools/build_context.py +43 -8
- basic_memory/mcp/tools/canvas.py +17 -3
- basic_memory/mcp/tools/delete_note.py +168 -5
- basic_memory/mcp/tools/edit_note.py +303 -0
- basic_memory/mcp/tools/list_directory.py +154 -0
- basic_memory/mcp/tools/move_note.py +299 -0
- basic_memory/mcp/tools/project_management.py +332 -0
- basic_memory/mcp/tools/read_content.py +15 -6
- basic_memory/mcp/tools/read_note.py +28 -9
- basic_memory/mcp/tools/recent_activity.py +47 -16
- basic_memory/mcp/tools/search.py +189 -8
- basic_memory/mcp/tools/sync_status.py +254 -0
- basic_memory/mcp/tools/utils.py +184 -12
- basic_memory/mcp/tools/view_note.py +66 -0
- basic_memory/mcp/tools/write_note.py +24 -17
- basic_memory/models/__init__.py +3 -2
- basic_memory/models/knowledge.py +16 -4
- basic_memory/models/project.py +78 -0
- basic_memory/models/search.py +8 -5
- basic_memory/repository/__init__.py +2 -0
- basic_memory/repository/entity_repository.py +8 -3
- basic_memory/repository/observation_repository.py +35 -3
- basic_memory/repository/project_info_repository.py +3 -2
- basic_memory/repository/project_repository.py +85 -0
- basic_memory/repository/relation_repository.py +8 -2
- basic_memory/repository/repository.py +107 -15
- basic_memory/repository/search_repository.py +192 -54
- basic_memory/schemas/__init__.py +6 -0
- basic_memory/schemas/base.py +33 -5
- basic_memory/schemas/directory.py +30 -0
- basic_memory/schemas/importer.py +34 -0
- basic_memory/schemas/memory.py +84 -13
- basic_memory/schemas/project_info.py +112 -2
- basic_memory/schemas/prompt.py +90 -0
- basic_memory/schemas/request.py +56 -2
- basic_memory/schemas/search.py +1 -1
- basic_memory/services/__init__.py +2 -1
- basic_memory/services/context_service.py +208 -95
- basic_memory/services/directory_service.py +167 -0
- basic_memory/services/entity_service.py +399 -6
- basic_memory/services/exceptions.py +6 -0
- basic_memory/services/file_service.py +14 -15
- basic_memory/services/initialization.py +170 -66
- basic_memory/services/link_resolver.py +35 -12
- basic_memory/services/migration_service.py +168 -0
- basic_memory/services/project_service.py +671 -0
- basic_memory/services/search_service.py +77 -2
- basic_memory/services/sync_status_service.py +181 -0
- basic_memory/sync/background_sync.py +25 -0
- basic_memory/sync/sync_service.py +102 -21
- basic_memory/sync/watch_service.py +63 -39
- basic_memory/templates/prompts/continue_conversation.hbs +110 -0
- basic_memory/templates/prompts/search.hbs +101 -0
- basic_memory/utils.py +67 -17
- {basic_memory-0.12.2.dist-info → basic_memory-0.13.0.dist-info}/METADATA +26 -4
- basic_memory-0.13.0.dist-info/RECORD +138 -0
- basic_memory/api/routers/project_info_router.py +0 -274
- basic_memory/mcp/main.py +0 -24
- basic_memory-0.12.2.dist-info/RECORD +0 -100
- {basic_memory-0.12.2.dist-info → basic_memory-0.13.0.dist-info}/WHEEL +0 -0
- {basic_memory-0.12.2.dist-info → basic_memory-0.13.0.dist-info}/entry_points.txt +0 -0
- {basic_memory-0.12.2.dist-info → basic_memory-0.13.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""Template loading and rendering utilities for the Basic Memory API.
|
|
2
|
+
|
|
3
|
+
This module handles the loading and rendering of Handlebars templates from the
|
|
4
|
+
templates directory, providing a consistent interface for all prompt-related
|
|
5
|
+
formatting needs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import textwrap
|
|
9
|
+
from typing import Dict, Any, Optional, Callable
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import json
|
|
12
|
+
import datetime
|
|
13
|
+
|
|
14
|
+
import pybars
|
|
15
|
+
from loguru import logger
|
|
16
|
+
|
|
17
|
+
# Get the base path of the templates directory
|
|
18
|
+
TEMPLATES_DIR = Path(__file__).parent.parent / "templates"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Custom helpers for Handlebars
|
|
22
|
+
def _date_helper(this, *args):
|
|
23
|
+
"""Format a date using the given format string."""
|
|
24
|
+
if len(args) < 1: # pragma: no cover
|
|
25
|
+
return ""
|
|
26
|
+
|
|
27
|
+
timestamp = args[0]
|
|
28
|
+
format_str = args[1] if len(args) > 1 else "%Y-%m-%d %H:%M"
|
|
29
|
+
|
|
30
|
+
if hasattr(timestamp, "strftime"):
|
|
31
|
+
result = timestamp.strftime(format_str)
|
|
32
|
+
elif isinstance(timestamp, str):
|
|
33
|
+
try:
|
|
34
|
+
dt = datetime.datetime.fromisoformat(timestamp)
|
|
35
|
+
result = dt.strftime(format_str)
|
|
36
|
+
except ValueError:
|
|
37
|
+
result = timestamp
|
|
38
|
+
else:
|
|
39
|
+
result = str(timestamp) # pragma: no cover
|
|
40
|
+
|
|
41
|
+
return pybars.strlist([result])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _default_helper(this, *args):
|
|
45
|
+
"""Return a default value if the given value is None or empty."""
|
|
46
|
+
if len(args) < 2: # pragma: no cover
|
|
47
|
+
return ""
|
|
48
|
+
|
|
49
|
+
value = args[0]
|
|
50
|
+
default_value = args[1]
|
|
51
|
+
|
|
52
|
+
result = default_value if value is None or value == "" else value
|
|
53
|
+
# Use strlist for consistent handling of HTML escaping
|
|
54
|
+
return pybars.strlist([str(result)])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _capitalize_helper(this, *args):
|
|
58
|
+
"""Capitalize the first letter of a string."""
|
|
59
|
+
if len(args) < 1: # pragma: no cover
|
|
60
|
+
return ""
|
|
61
|
+
|
|
62
|
+
text = args[0]
|
|
63
|
+
if not text or not isinstance(text, str): # pragma: no cover
|
|
64
|
+
result = ""
|
|
65
|
+
else:
|
|
66
|
+
result = text.capitalize()
|
|
67
|
+
|
|
68
|
+
return pybars.strlist([result])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _round_helper(this, *args):
|
|
72
|
+
"""Round a number to the specified number of decimal places."""
|
|
73
|
+
if len(args) < 1:
|
|
74
|
+
return ""
|
|
75
|
+
|
|
76
|
+
value = args[0]
|
|
77
|
+
decimal_places = args[1] if len(args) > 1 else 2
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
result = str(round(float(value), int(decimal_places)))
|
|
81
|
+
except (ValueError, TypeError):
|
|
82
|
+
result = str(value)
|
|
83
|
+
|
|
84
|
+
return pybars.strlist([result])
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _size_helper(this, *args):
|
|
88
|
+
"""Return the size/length of a collection."""
|
|
89
|
+
if len(args) < 1:
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
value = args[0]
|
|
93
|
+
if value is None:
|
|
94
|
+
result = "0"
|
|
95
|
+
elif isinstance(value, (list, tuple, dict, str)):
|
|
96
|
+
result = str(len(value)) # pragma: no cover
|
|
97
|
+
else: # pragma: no cover
|
|
98
|
+
result = "0"
|
|
99
|
+
|
|
100
|
+
return pybars.strlist([result])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _json_helper(this, *args):
|
|
104
|
+
"""Convert a value to a JSON string."""
|
|
105
|
+
if len(args) < 1: # pragma: no cover
|
|
106
|
+
return "{}"
|
|
107
|
+
|
|
108
|
+
value = args[0]
|
|
109
|
+
# For pybars, we need to return a SafeString to prevent HTML escaping
|
|
110
|
+
result = json.dumps(value) # pragma: no cover
|
|
111
|
+
# Safe string implementation to prevent HTML escaping
|
|
112
|
+
return pybars.strlist([result])
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _math_helper(this, *args):
|
|
116
|
+
"""Perform basic math operations."""
|
|
117
|
+
if len(args) < 3:
|
|
118
|
+
return pybars.strlist(["Math error: Insufficient arguments"])
|
|
119
|
+
|
|
120
|
+
lhs = args[0]
|
|
121
|
+
operator = args[1]
|
|
122
|
+
rhs = args[2]
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
lhs = float(lhs)
|
|
126
|
+
rhs = float(rhs)
|
|
127
|
+
if operator == "+":
|
|
128
|
+
result = str(lhs + rhs)
|
|
129
|
+
elif operator == "-":
|
|
130
|
+
result = str(lhs - rhs)
|
|
131
|
+
elif operator == "*":
|
|
132
|
+
result = str(lhs * rhs)
|
|
133
|
+
elif operator == "/":
|
|
134
|
+
result = str(lhs / rhs)
|
|
135
|
+
else:
|
|
136
|
+
result = f"Unsupported operator: {operator}"
|
|
137
|
+
except (ValueError, TypeError) as e:
|
|
138
|
+
result = f"Math error: {e}"
|
|
139
|
+
|
|
140
|
+
return pybars.strlist([result])
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _lt_helper(this, *args):
|
|
144
|
+
"""Check if left hand side is less than right hand side."""
|
|
145
|
+
if len(args) < 2:
|
|
146
|
+
return False
|
|
147
|
+
|
|
148
|
+
lhs = args[0]
|
|
149
|
+
rhs = args[1]
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
return float(lhs) < float(rhs)
|
|
153
|
+
except (ValueError, TypeError):
|
|
154
|
+
# Fall back to string comparison for non-numeric values
|
|
155
|
+
return str(lhs) < str(rhs)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _if_cond_helper(this, options, condition):
|
|
159
|
+
"""Block helper for custom if conditionals."""
|
|
160
|
+
if condition:
|
|
161
|
+
return options["fn"](this)
|
|
162
|
+
elif "inverse" in options:
|
|
163
|
+
return options["inverse"](this)
|
|
164
|
+
return "" # pragma: no cover
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _dedent_helper(this, options):
|
|
168
|
+
"""Dedent a block of text to remove common leading whitespace.
|
|
169
|
+
|
|
170
|
+
Usage:
|
|
171
|
+
{{#dedent}}
|
|
172
|
+
This text will have its
|
|
173
|
+
common leading whitespace removed
|
|
174
|
+
while preserving relative indentation.
|
|
175
|
+
{{/dedent}}
|
|
176
|
+
"""
|
|
177
|
+
if "fn" not in options: # pragma: no cover
|
|
178
|
+
return ""
|
|
179
|
+
|
|
180
|
+
# Get the content from the block
|
|
181
|
+
content = options["fn"](this)
|
|
182
|
+
|
|
183
|
+
# Convert to string if it's a strlist
|
|
184
|
+
if (
|
|
185
|
+
isinstance(content, list)
|
|
186
|
+
or hasattr(content, "__iter__")
|
|
187
|
+
and not isinstance(content, (str, bytes))
|
|
188
|
+
):
|
|
189
|
+
content_str = "".join(str(item) for item in content) # pragma: no cover
|
|
190
|
+
else:
|
|
191
|
+
content_str = str(content) # pragma: no cover
|
|
192
|
+
|
|
193
|
+
# Add trailing and leading newlines to ensure proper dedenting
|
|
194
|
+
# This is critical for textwrap.dedent to work correctly with mixed content
|
|
195
|
+
content_str = "\n" + content_str + "\n"
|
|
196
|
+
|
|
197
|
+
# Use textwrap to dedent the content and remove the extra newlines we added
|
|
198
|
+
dedented = textwrap.dedent(content_str)[1:-1]
|
|
199
|
+
|
|
200
|
+
# Return as a SafeString to prevent HTML escaping
|
|
201
|
+
return pybars.strlist([dedented]) # pragma: no cover
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class TemplateLoader:
|
|
205
|
+
"""Loader for Handlebars templates.
|
|
206
|
+
|
|
207
|
+
This class is responsible for loading templates from disk and rendering
|
|
208
|
+
them with the provided context data.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
def __init__(self, template_dir: Optional[str] = None):
|
|
212
|
+
"""Initialize the template loader.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
template_dir: Optional custom template directory path
|
|
216
|
+
"""
|
|
217
|
+
self.template_dir = Path(template_dir) if template_dir else TEMPLATES_DIR
|
|
218
|
+
self.template_cache: Dict[str, Callable] = {}
|
|
219
|
+
self.compiler = pybars.Compiler()
|
|
220
|
+
|
|
221
|
+
# Set up standard helpers
|
|
222
|
+
self.helpers = {
|
|
223
|
+
"date": _date_helper,
|
|
224
|
+
"default": _default_helper,
|
|
225
|
+
"capitalize": _capitalize_helper,
|
|
226
|
+
"round": _round_helper,
|
|
227
|
+
"size": _size_helper,
|
|
228
|
+
"json": _json_helper,
|
|
229
|
+
"math": _math_helper,
|
|
230
|
+
"lt": _lt_helper,
|
|
231
|
+
"if_cond": _if_cond_helper,
|
|
232
|
+
"dedent": _dedent_helper,
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
logger.debug(f"Initialized template loader with directory: {self.template_dir}")
|
|
236
|
+
|
|
237
|
+
def get_template(self, template_path: str) -> Callable:
|
|
238
|
+
"""Get a template by path, using cache if available.
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
template_path: The path to the template, relative to the templates directory
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
The compiled Handlebars template
|
|
245
|
+
|
|
246
|
+
Raises:
|
|
247
|
+
FileNotFoundError: If the template doesn't exist
|
|
248
|
+
"""
|
|
249
|
+
if template_path in self.template_cache:
|
|
250
|
+
return self.template_cache[template_path]
|
|
251
|
+
|
|
252
|
+
# Convert from Liquid-style path to Handlebars extension
|
|
253
|
+
if template_path.endswith(".liquid"):
|
|
254
|
+
template_path = template_path.replace(".liquid", ".hbs")
|
|
255
|
+
elif not template_path.endswith(".hbs"):
|
|
256
|
+
template_path = f"{template_path}.hbs"
|
|
257
|
+
|
|
258
|
+
full_path = self.template_dir / template_path
|
|
259
|
+
|
|
260
|
+
if not full_path.exists():
|
|
261
|
+
raise FileNotFoundError(f"Template not found: {full_path}")
|
|
262
|
+
|
|
263
|
+
with open(full_path, "r", encoding="utf-8") as f:
|
|
264
|
+
template_str = f.read()
|
|
265
|
+
|
|
266
|
+
template = self.compiler.compile(template_str)
|
|
267
|
+
self.template_cache[template_path] = template
|
|
268
|
+
|
|
269
|
+
logger.debug(f"Loaded template: {template_path}")
|
|
270
|
+
return template
|
|
271
|
+
|
|
272
|
+
async def render(self, template_path: str, context: Dict[str, Any]) -> str:
|
|
273
|
+
"""Render a template with the given context.
|
|
274
|
+
|
|
275
|
+
Args:
|
|
276
|
+
template_path: The path to the template, relative to the templates directory
|
|
277
|
+
context: The context data to pass to the template
|
|
278
|
+
|
|
279
|
+
Returns:
|
|
280
|
+
The rendered template as a string
|
|
281
|
+
"""
|
|
282
|
+
template = self.get_template(template_path)
|
|
283
|
+
return template(context, helpers=self.helpers)
|
|
284
|
+
|
|
285
|
+
def clear_cache(self) -> None:
|
|
286
|
+
"""Clear the template cache."""
|
|
287
|
+
self.template_cache.clear()
|
|
288
|
+
logger.debug("Template cache cleared")
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
# Global template loader instance
|
|
292
|
+
template_loader = TemplateLoader()
|
basic_memory/cli/app.py
CHANGED
|
@@ -2,6 +2,9 @@ from typing import Optional
|
|
|
2
2
|
|
|
3
3
|
import typer
|
|
4
4
|
|
|
5
|
+
from basic_memory.config import get_project_config
|
|
6
|
+
from basic_memory.mcp.project_session import session
|
|
7
|
+
|
|
5
8
|
|
|
6
9
|
def version_callback(value: bool) -> None:
|
|
7
10
|
"""Show version and exit."""
|
|
@@ -39,31 +42,27 @@ def app_callback(
|
|
|
39
42
|
) -> None:
|
|
40
43
|
"""Basic Memory - Local-first personal knowledge management."""
|
|
41
44
|
|
|
42
|
-
#
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
import
|
|
46
|
-
import importlib
|
|
47
|
-
from basic_memory import config as config_module
|
|
48
|
-
|
|
49
|
-
# Set the environment variable
|
|
50
|
-
os.environ["BASIC_MEMORY_PROJECT"] = project
|
|
51
|
-
|
|
52
|
-
# Reload the config module to pick up the new project
|
|
53
|
-
importlib.reload(config_module)
|
|
45
|
+
# Run initialization for every command unless --version was specified
|
|
46
|
+
if not version and ctx.invoked_subcommand is not None:
|
|
47
|
+
from basic_memory.config import app_config
|
|
48
|
+
from basic_memory.services.initialization import ensure_initialization
|
|
54
49
|
|
|
55
|
-
|
|
56
|
-
global config
|
|
57
|
-
from basic_memory.config import config as new_config
|
|
50
|
+
ensure_initialization(app_config)
|
|
58
51
|
|
|
59
|
-
|
|
52
|
+
# Initialize MCP session with the specified project or default
|
|
53
|
+
if project: # pragma: no cover
|
|
54
|
+
# Use the project specified via --project flag
|
|
55
|
+
current_project_config = get_project_config(project)
|
|
56
|
+
session.set_current_project(current_project_config.name)
|
|
60
57
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
from basic_memory.config import config
|
|
64
|
-
from basic_memory.services.initialization import ensure_initialize_database
|
|
58
|
+
# Update the global config to use this project
|
|
59
|
+
from basic_memory.config import update_current_project
|
|
65
60
|
|
|
66
|
-
|
|
61
|
+
update_current_project(project)
|
|
62
|
+
else:
|
|
63
|
+
# Use the default project
|
|
64
|
+
current_project = app_config.default_project
|
|
65
|
+
session.set_current_project(current_project)
|
|
67
66
|
|
|
68
67
|
|
|
69
68
|
# Register sub-command groups
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"""CLI commands for basic-memory."""
|
|
2
2
|
|
|
3
|
-
from . import status, sync, db, import_memory_json, mcp, import_claude_conversations
|
|
3
|
+
from . import auth, status, sync, db, import_memory_json, mcp, import_claude_conversations
|
|
4
4
|
from . import import_claude_projects, import_chatgpt, tool, project
|
|
5
5
|
|
|
6
6
|
__all__ = [
|
|
7
|
+
"auth",
|
|
7
8
|
"status",
|
|
8
9
|
"sync",
|
|
9
10
|
"db",
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""OAuth management commands."""
|
|
2
|
+
|
|
3
|
+
import typer
|
|
4
|
+
from typing import Optional
|
|
5
|
+
from pydantic import AnyHttpUrl
|
|
6
|
+
|
|
7
|
+
from basic_memory.cli.app import app
|
|
8
|
+
from basic_memory.mcp.auth_provider import BasicMemoryOAuthProvider
|
|
9
|
+
from mcp.shared.auth import OAuthClientInformationFull
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
auth_app = typer.Typer(help="OAuth client management commands")
|
|
13
|
+
app.add_typer(auth_app, name="auth")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@auth_app.command()
|
|
17
|
+
def register_client(
|
|
18
|
+
client_id: Optional[str] = typer.Option(
|
|
19
|
+
None, help="Client ID (auto-generated if not provided)"
|
|
20
|
+
),
|
|
21
|
+
client_secret: Optional[str] = typer.Option(
|
|
22
|
+
None, help="Client secret (auto-generated if not provided)"
|
|
23
|
+
),
|
|
24
|
+
issuer_url: str = typer.Option("http://localhost:8000", help="OAuth issuer URL"),
|
|
25
|
+
):
|
|
26
|
+
"""Register a new OAuth client for Basic Memory MCP server."""
|
|
27
|
+
|
|
28
|
+
# Create provider instance
|
|
29
|
+
provider = BasicMemoryOAuthProvider(issuer_url=issuer_url)
|
|
30
|
+
|
|
31
|
+
# Create client info with required redirect_uris
|
|
32
|
+
client_info = OAuthClientInformationFull(
|
|
33
|
+
client_id=client_id or "", # Provider will generate if empty
|
|
34
|
+
client_secret=client_secret or "", # Provider will generate if empty
|
|
35
|
+
redirect_uris=[AnyHttpUrl("http://localhost:8000/callback")], # Default redirect URI
|
|
36
|
+
client_name="Basic Memory OAuth Client",
|
|
37
|
+
grant_types=["authorization_code", "refresh_token"],
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# Register the client
|
|
41
|
+
import asyncio
|
|
42
|
+
|
|
43
|
+
asyncio.run(provider.register_client(client_info))
|
|
44
|
+
|
|
45
|
+
typer.echo("Client registered successfully!")
|
|
46
|
+
typer.echo(f"Client ID: {client_info.client_id}")
|
|
47
|
+
typer.echo(f"Client Secret: {client_info.client_secret}")
|
|
48
|
+
typer.echo("\nSave these credentials securely - the client secret cannot be retrieved later.")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@auth_app.command()
|
|
52
|
+
def test_auth(
|
|
53
|
+
issuer_url: str = typer.Option("http://localhost:8000", help="OAuth issuer URL"),
|
|
54
|
+
):
|
|
55
|
+
"""Test OAuth authentication flow.
|
|
56
|
+
|
|
57
|
+
IMPORTANT: Use the same FASTMCP_AUTH_SECRET_KEY environment variable
|
|
58
|
+
as your MCP server for tokens to validate correctly.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
import asyncio
|
|
62
|
+
import secrets
|
|
63
|
+
from mcp.server.auth.provider import AuthorizationParams
|
|
64
|
+
from pydantic import AnyHttpUrl
|
|
65
|
+
|
|
66
|
+
async def test_flow():
|
|
67
|
+
# Create provider with same secret key as server
|
|
68
|
+
provider = BasicMemoryOAuthProvider(issuer_url=issuer_url)
|
|
69
|
+
|
|
70
|
+
# Register a test client
|
|
71
|
+
client_info = OAuthClientInformationFull(
|
|
72
|
+
client_id=secrets.token_urlsafe(16),
|
|
73
|
+
client_secret=secrets.token_urlsafe(32),
|
|
74
|
+
redirect_uris=[AnyHttpUrl("http://localhost:8000/callback")],
|
|
75
|
+
client_name="Test OAuth Client",
|
|
76
|
+
grant_types=["authorization_code", "refresh_token"],
|
|
77
|
+
)
|
|
78
|
+
await provider.register_client(client_info)
|
|
79
|
+
typer.echo(f"Registered test client: {client_info.client_id}")
|
|
80
|
+
|
|
81
|
+
# Get the client
|
|
82
|
+
client = await provider.get_client(client_info.client_id)
|
|
83
|
+
if not client:
|
|
84
|
+
typer.echo("Error: Client not found after registration", err=True)
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
# Create authorization request
|
|
88
|
+
auth_params = AuthorizationParams(
|
|
89
|
+
state="test-state",
|
|
90
|
+
scopes=["read", "write"],
|
|
91
|
+
code_challenge="test-challenge",
|
|
92
|
+
redirect_uri=AnyHttpUrl("http://localhost:8000/callback"),
|
|
93
|
+
redirect_uri_provided_explicitly=True,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# Get authorization URL
|
|
97
|
+
auth_url = await provider.authorize(client, auth_params)
|
|
98
|
+
typer.echo(f"Authorization URL: {auth_url}")
|
|
99
|
+
|
|
100
|
+
# Extract auth code from URL
|
|
101
|
+
from urllib.parse import urlparse, parse_qs
|
|
102
|
+
|
|
103
|
+
parsed = urlparse(auth_url)
|
|
104
|
+
params = parse_qs(parsed.query)
|
|
105
|
+
auth_code = params.get("code", [None])[0]
|
|
106
|
+
|
|
107
|
+
if not auth_code:
|
|
108
|
+
typer.echo("Error: No authorization code in URL", err=True)
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
# Load the authorization code
|
|
112
|
+
code_obj = await provider.load_authorization_code(client, auth_code)
|
|
113
|
+
if not code_obj:
|
|
114
|
+
typer.echo("Error: Invalid authorization code", err=True)
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
# Exchange for tokens
|
|
118
|
+
token = await provider.exchange_authorization_code(client, code_obj)
|
|
119
|
+
typer.echo(f"Access token: {token.access_token}")
|
|
120
|
+
typer.echo(f"Refresh token: {token.refresh_token}")
|
|
121
|
+
typer.echo(f"Expires in: {token.expires_in} seconds")
|
|
122
|
+
|
|
123
|
+
# Validate access token
|
|
124
|
+
access_token_obj = await provider.load_access_token(token.access_token)
|
|
125
|
+
if access_token_obj:
|
|
126
|
+
typer.echo("Access token validated successfully!")
|
|
127
|
+
typer.echo(f"Client ID: {access_token_obj.client_id}")
|
|
128
|
+
typer.echo(f"Scopes: {access_token_obj.scopes}")
|
|
129
|
+
else:
|
|
130
|
+
typer.echo("Error: Invalid access token", err=True)
|
|
131
|
+
|
|
132
|
+
asyncio.run(test_flow())
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
if __name__ == "__main__":
|
|
136
|
+
auth_app()
|
basic_memory/cli/commands/db.py
CHANGED
|
@@ -7,7 +7,7 @@ from loguru import logger
|
|
|
7
7
|
|
|
8
8
|
from basic_memory import db
|
|
9
9
|
from basic_memory.cli.app import app
|
|
10
|
-
from basic_memory.config import
|
|
10
|
+
from basic_memory.config import app_config
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
@app.command()
|
|
@@ -18,7 +18,7 @@ def reset(
|
|
|
18
18
|
if typer.confirm("This will delete all data in your db. Are you sure?"):
|
|
19
19
|
logger.info("Resetting database...")
|
|
20
20
|
# Get database path
|
|
21
|
-
db_path =
|
|
21
|
+
db_path = app_config.app_database_path
|
|
22
22
|
|
|
23
23
|
# Delete the database file if it exists
|
|
24
24
|
if db_path.exists():
|
|
@@ -26,7 +26,7 @@ def reset(
|
|
|
26
26
|
logger.info(f"Database file deleted: {db_path}")
|
|
27
27
|
|
|
28
28
|
# Create a new empty database
|
|
29
|
-
asyncio.run(db.run_migrations(
|
|
29
|
+
asyncio.run(db.run_migrations(app_config))
|
|
30
30
|
logger.info("Database reset complete")
|
|
31
31
|
|
|
32
32
|
if reindex:
|