basic-memory 0.7.0__py3-none-any.whl → 0.16.1__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.

Files changed (150) hide show
  1. basic_memory/__init__.py +5 -1
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +27 -3
  4. basic_memory/alembic/migrations.py +4 -9
  5. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  6. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +108 -0
  7. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +104 -0
  8. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  9. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  10. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  11. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +100 -0
  12. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  13. basic_memory/api/app.py +64 -18
  14. basic_memory/api/routers/__init__.py +4 -1
  15. basic_memory/api/routers/directory_router.py +84 -0
  16. basic_memory/api/routers/importer_router.py +152 -0
  17. basic_memory/api/routers/knowledge_router.py +166 -21
  18. basic_memory/api/routers/management_router.py +80 -0
  19. basic_memory/api/routers/memory_router.py +9 -64
  20. basic_memory/api/routers/project_router.py +406 -0
  21. basic_memory/api/routers/prompt_router.py +260 -0
  22. basic_memory/api/routers/resource_router.py +119 -4
  23. basic_memory/api/routers/search_router.py +5 -5
  24. basic_memory/api/routers/utils.py +130 -0
  25. basic_memory/api/template_loader.py +292 -0
  26. basic_memory/cli/app.py +43 -9
  27. basic_memory/cli/auth.py +277 -0
  28. basic_memory/cli/commands/__init__.py +13 -2
  29. basic_memory/cli/commands/cloud/__init__.py +6 -0
  30. basic_memory/cli/commands/cloud/api_client.py +112 -0
  31. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  32. basic_memory/cli/commands/cloud/cloud_utils.py +101 -0
  33. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  34. basic_memory/cli/commands/cloud/rclone_commands.py +301 -0
  35. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  36. basic_memory/cli/commands/cloud/rclone_installer.py +249 -0
  37. basic_memory/cli/commands/cloud/upload.py +233 -0
  38. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  39. basic_memory/cli/commands/command_utils.py +51 -0
  40. basic_memory/cli/commands/db.py +28 -12
  41. basic_memory/cli/commands/import_chatgpt.py +40 -220
  42. basic_memory/cli/commands/import_claude_conversations.py +41 -168
  43. basic_memory/cli/commands/import_claude_projects.py +46 -157
  44. basic_memory/cli/commands/import_memory_json.py +48 -108
  45. basic_memory/cli/commands/mcp.py +84 -10
  46. basic_memory/cli/commands/project.py +876 -0
  47. basic_memory/cli/commands/status.py +50 -33
  48. basic_memory/cli/commands/tool.py +341 -0
  49. basic_memory/cli/main.py +8 -7
  50. basic_memory/config.py +477 -23
  51. basic_memory/db.py +168 -17
  52. basic_memory/deps.py +251 -25
  53. basic_memory/file_utils.py +113 -58
  54. basic_memory/ignore_utils.py +297 -0
  55. basic_memory/importers/__init__.py +27 -0
  56. basic_memory/importers/base.py +79 -0
  57. basic_memory/importers/chatgpt_importer.py +232 -0
  58. basic_memory/importers/claude_conversations_importer.py +177 -0
  59. basic_memory/importers/claude_projects_importer.py +148 -0
  60. basic_memory/importers/memory_json_importer.py +108 -0
  61. basic_memory/importers/utils.py +58 -0
  62. basic_memory/markdown/entity_parser.py +143 -23
  63. basic_memory/markdown/markdown_processor.py +3 -3
  64. basic_memory/markdown/plugins.py +39 -21
  65. basic_memory/markdown/schemas.py +1 -1
  66. basic_memory/markdown/utils.py +28 -13
  67. basic_memory/mcp/async_client.py +134 -4
  68. basic_memory/mcp/project_context.py +141 -0
  69. basic_memory/mcp/prompts/__init__.py +19 -0
  70. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  71. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  72. basic_memory/mcp/prompts/recent_activity.py +188 -0
  73. basic_memory/mcp/prompts/search.py +57 -0
  74. basic_memory/mcp/prompts/utils.py +162 -0
  75. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  76. basic_memory/mcp/resources/project_info.py +71 -0
  77. basic_memory/mcp/server.py +7 -13
  78. basic_memory/mcp/tools/__init__.py +33 -21
  79. basic_memory/mcp/tools/build_context.py +120 -0
  80. basic_memory/mcp/tools/canvas.py +130 -0
  81. basic_memory/mcp/tools/chatgpt_tools.py +187 -0
  82. basic_memory/mcp/tools/delete_note.py +225 -0
  83. basic_memory/mcp/tools/edit_note.py +320 -0
  84. basic_memory/mcp/tools/list_directory.py +167 -0
  85. basic_memory/mcp/tools/move_note.py +545 -0
  86. basic_memory/mcp/tools/project_management.py +200 -0
  87. basic_memory/mcp/tools/read_content.py +271 -0
  88. basic_memory/mcp/tools/read_note.py +255 -0
  89. basic_memory/mcp/tools/recent_activity.py +534 -0
  90. basic_memory/mcp/tools/search.py +369 -23
  91. basic_memory/mcp/tools/utils.py +374 -16
  92. basic_memory/mcp/tools/view_note.py +77 -0
  93. basic_memory/mcp/tools/write_note.py +207 -0
  94. basic_memory/models/__init__.py +3 -2
  95. basic_memory/models/knowledge.py +67 -15
  96. basic_memory/models/project.py +87 -0
  97. basic_memory/models/search.py +10 -6
  98. basic_memory/repository/__init__.py +2 -0
  99. basic_memory/repository/entity_repository.py +229 -7
  100. basic_memory/repository/observation_repository.py +35 -3
  101. basic_memory/repository/project_info_repository.py +10 -0
  102. basic_memory/repository/project_repository.py +103 -0
  103. basic_memory/repository/relation_repository.py +21 -2
  104. basic_memory/repository/repository.py +147 -29
  105. basic_memory/repository/search_repository.py +411 -62
  106. basic_memory/schemas/__init__.py +22 -9
  107. basic_memory/schemas/base.py +97 -8
  108. basic_memory/schemas/cloud.py +50 -0
  109. basic_memory/schemas/directory.py +30 -0
  110. basic_memory/schemas/importer.py +35 -0
  111. basic_memory/schemas/memory.py +187 -25
  112. basic_memory/schemas/project_info.py +211 -0
  113. basic_memory/schemas/prompt.py +90 -0
  114. basic_memory/schemas/request.py +56 -2
  115. basic_memory/schemas/response.py +1 -1
  116. basic_memory/schemas/search.py +31 -35
  117. basic_memory/schemas/sync_report.py +72 -0
  118. basic_memory/services/__init__.py +2 -1
  119. basic_memory/services/context_service.py +241 -104
  120. basic_memory/services/directory_service.py +295 -0
  121. basic_memory/services/entity_service.py +590 -60
  122. basic_memory/services/exceptions.py +21 -0
  123. basic_memory/services/file_service.py +284 -30
  124. basic_memory/services/initialization.py +191 -0
  125. basic_memory/services/link_resolver.py +49 -56
  126. basic_memory/services/project_service.py +863 -0
  127. basic_memory/services/search_service.py +168 -32
  128. basic_memory/sync/__init__.py +3 -2
  129. basic_memory/sync/background_sync.py +26 -0
  130. basic_memory/sync/sync_service.py +1180 -109
  131. basic_memory/sync/watch_service.py +412 -135
  132. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  133. basic_memory/templates/prompts/search.hbs +101 -0
  134. basic_memory/utils.py +383 -51
  135. basic_memory-0.16.1.dist-info/METADATA +493 -0
  136. basic_memory-0.16.1.dist-info/RECORD +148 -0
  137. {basic_memory-0.7.0.dist-info → basic_memory-0.16.1.dist-info}/entry_points.txt +1 -0
  138. basic_memory/alembic/README +0 -1
  139. basic_memory/cli/commands/sync.py +0 -206
  140. basic_memory/cli/commands/tools.py +0 -157
  141. basic_memory/mcp/tools/knowledge.py +0 -68
  142. basic_memory/mcp/tools/memory.py +0 -170
  143. basic_memory/mcp/tools/notes.py +0 -202
  144. basic_memory/schemas/discovery.py +0 -28
  145. basic_memory/sync/file_change_scanner.py +0 -158
  146. basic_memory/sync/utils.py +0 -31
  147. basic_memory-0.7.0.dist-info/METADATA +0 -378
  148. basic_memory-0.7.0.dist-info/RECORD +0 -82
  149. {basic_memory-0.7.0.dist-info → basic_memory-0.16.1.dist-info}/WHEEL +0 -0
  150. {basic_memory-0.7.0.dist-info → basic_memory-0.16.1.dist-info}/licenses/LICENSE +0 -0
@@ -1,206 +0,0 @@
1
- """Command module for basic-memory sync operations."""
2
-
3
- import asyncio
4
- from collections import defaultdict
5
- from dataclasses import dataclass
6
- from pathlib import Path
7
- from typing import List, Dict
8
-
9
- import typer
10
- from loguru import logger
11
- from rich.console import Console
12
- from rich.tree import Tree
13
-
14
- from basic_memory import db
15
- from basic_memory.cli.app import app
16
- from basic_memory.config import config
17
- from basic_memory.markdown import EntityParser
18
- from basic_memory.markdown.markdown_processor import MarkdownProcessor
19
- from basic_memory.repository import (
20
- EntityRepository,
21
- ObservationRepository,
22
- RelationRepository,
23
- )
24
- from basic_memory.repository.search_repository import SearchRepository
25
- from basic_memory.services import EntityService, FileService
26
- from basic_memory.services.link_resolver import LinkResolver
27
- from basic_memory.services.search_service import SearchService
28
- from basic_memory.sync import SyncService, FileChangeScanner
29
- from basic_memory.sync.utils import SyncReport
30
- from basic_memory.sync.watch_service import WatchService
31
-
32
- console = Console()
33
-
34
-
35
- @dataclass
36
- class ValidationIssue:
37
- file_path: str
38
- error: str
39
-
40
-
41
- async def get_sync_service(): # pragma: no cover
42
- """Get sync service instance with all dependencies."""
43
- _, session_maker = await db.get_or_create_db(
44
- db_path=config.database_path, db_type=db.DatabaseType.FILESYSTEM
45
- )
46
-
47
- entity_parser = EntityParser(config.home)
48
- markdown_processor = MarkdownProcessor(entity_parser)
49
- file_service = FileService(config.home, markdown_processor)
50
-
51
- # Initialize repositories
52
- entity_repository = EntityRepository(session_maker)
53
- observation_repository = ObservationRepository(session_maker)
54
- relation_repository = RelationRepository(session_maker)
55
- search_repository = SearchRepository(session_maker)
56
-
57
- # Initialize services
58
- search_service = SearchService(search_repository, entity_repository, file_service)
59
- link_resolver = LinkResolver(entity_repository, search_service)
60
-
61
- # Initialize scanner
62
- file_change_scanner = FileChangeScanner(entity_repository)
63
-
64
- # Initialize services
65
- entity_service = EntityService(
66
- entity_parser,
67
- entity_repository,
68
- observation_repository,
69
- relation_repository,
70
- file_service,
71
- link_resolver,
72
- )
73
-
74
- # Create sync service
75
- sync_service = SyncService(
76
- scanner=file_change_scanner,
77
- entity_service=entity_service,
78
- entity_parser=entity_parser,
79
- entity_repository=entity_repository,
80
- relation_repository=relation_repository,
81
- search_service=search_service,
82
- )
83
-
84
- return sync_service
85
-
86
-
87
- def group_issues_by_directory(issues: List[ValidationIssue]) -> Dict[str, List[ValidationIssue]]:
88
- """Group validation issues by directory."""
89
- grouped = defaultdict(list)
90
- for issue in issues:
91
- dir_name = Path(issue.file_path).parent.name
92
- grouped[dir_name].append(issue)
93
- return dict(grouped)
94
-
95
-
96
- def display_sync_summary(knowledge: SyncReport):
97
- """Display a one-line summary of sync changes."""
98
- total_changes = knowledge.total_changes
99
- if total_changes == 0:
100
- console.print("[green]Everything up to date[/green]")
101
- return
102
-
103
- # Format as: "Synced X files (A new, B modified, C moved, D deleted)"
104
- changes = []
105
- new_count = len(knowledge.new)
106
- mod_count = len(knowledge.modified)
107
- move_count = len(knowledge.moves)
108
- del_count = len(knowledge.deleted)
109
-
110
- if new_count:
111
- changes.append(f"[green]{new_count} new[/green]")
112
- if mod_count:
113
- changes.append(f"[yellow]{mod_count} modified[/yellow]")
114
- if move_count:
115
- changes.append(f"[blue]{move_count} moved[/blue]")
116
- if del_count:
117
- changes.append(f"[red]{del_count} deleted[/red]")
118
-
119
- console.print(f"Synced {total_changes} files ({', '.join(changes)})")
120
-
121
-
122
- def display_detailed_sync_results(knowledge: SyncReport):
123
- """Display detailed sync results with trees."""
124
- if knowledge.total_changes == 0:
125
- console.print("\n[green]Everything up to date[/green]")
126
- return
127
-
128
- console.print("\n[bold]Sync Results[/bold]")
129
-
130
- if knowledge.total_changes > 0:
131
- knowledge_tree = Tree("[bold]Knowledge Files[/bold]")
132
- if knowledge.new:
133
- created = knowledge_tree.add("[green]Created[/green]")
134
- for path in sorted(knowledge.new):
135
- checksum = knowledge.checksums.get(path, "")
136
- created.add(f"[green]{path}[/green] ({checksum[:8]})")
137
- if knowledge.modified:
138
- modified = knowledge_tree.add("[yellow]Modified[/yellow]")
139
- for path in sorted(knowledge.modified):
140
- checksum = knowledge.checksums.get(path, "")
141
- modified.add(f"[yellow]{path}[/yellow] ({checksum[:8]})")
142
- if knowledge.moves:
143
- moved = knowledge_tree.add("[blue]Moved[/blue]")
144
- for old_path, new_path in sorted(knowledge.moves.items()):
145
- checksum = knowledge.checksums.get(new_path, "")
146
- moved.add(f"[blue]{old_path}[/blue] → [blue]{new_path}[/blue] ({checksum[:8]})")
147
- if knowledge.deleted:
148
- deleted = knowledge_tree.add("[red]Deleted[/red]")
149
- for path in sorted(knowledge.deleted):
150
- deleted.add(f"[red]{path}[/red]")
151
- console.print(knowledge_tree)
152
-
153
-
154
- async def run_sync(verbose: bool = False, watch: bool = False, console_status: bool = False):
155
- """Run sync operation."""
156
-
157
- sync_service = await get_sync_service()
158
-
159
- # Start watching if requested
160
- if watch:
161
- watch_service = WatchService(
162
- sync_service=sync_service,
163
- file_service=sync_service.entity_service.file_service,
164
- config=config,
165
- )
166
- await watch_service.handle_changes(config.home)
167
- await watch_service.run(console_status=console_status) # pragma: no cover
168
- else:
169
- # one time sync
170
- knowledge_changes = await sync_service.sync(config.home)
171
- # Display results
172
- if verbose:
173
- display_detailed_sync_results(knowledge_changes)
174
- else:
175
- display_sync_summary(knowledge_changes) # pragma: no cover
176
-
177
-
178
- @app.command()
179
- def sync(
180
- verbose: bool = typer.Option(
181
- False,
182
- "--verbose",
183
- "-v",
184
- help="Show detailed sync information.",
185
- ),
186
- watch: bool = typer.Option(
187
- False,
188
- "--watch",
189
- "-w",
190
- help="Start watching for changes after sync.",
191
- ),
192
- console_status: bool = typer.Option(
193
- False, "--console-status", "-c", help="Show live console status"
194
- ),
195
- ) -> None:
196
- """Sync knowledge files with the database."""
197
- try:
198
- # Run sync
199
- asyncio.run(run_sync(verbose=verbose, watch=watch, console_status=console_status))
200
-
201
- except Exception as e: # pragma: no cover
202
- if not isinstance(e, typer.Exit):
203
- logger.exception("Sync failed")
204
- typer.echo(f"Error during sync: {e}", err=True)
205
- raise typer.Exit(1)
206
- raise
@@ -1,157 +0,0 @@
1
- """Database management commands."""
2
-
3
- import asyncio
4
- from typing import Optional, List, Annotated
5
-
6
- import typer
7
- from rich import print as rprint
8
-
9
- from basic_memory.cli.app import app
10
- from basic_memory.mcp.tools import build_context as mcp_build_context
11
- from basic_memory.mcp.tools import get_entity as mcp_get_entity
12
- from basic_memory.mcp.tools import read_note as mcp_read_note
13
- from basic_memory.mcp.tools import recent_activity as mcp_recent_activity
14
- from basic_memory.mcp.tools import search as mcp_search
15
- from basic_memory.mcp.tools import write_note as mcp_write_note
16
- from basic_memory.schemas.base import TimeFrame
17
- from basic_memory.schemas.memory import MemoryUrl
18
- from basic_memory.schemas.search import SearchQuery
19
-
20
- tool_app = typer.Typer()
21
- app.add_typer(tool_app, name="tools", help="cli versions mcp tools")
22
-
23
-
24
- @tool_app.command()
25
- def write_note(
26
- title: Annotated[str, typer.Option(help="The title of the note")],
27
- content: Annotated[str, typer.Option(help="The content of the note")],
28
- folder: Annotated[str, typer.Option(help="The folder to create the note in")],
29
- tags: Annotated[
30
- Optional[List[str]], typer.Option(help="A list of tags to apply to the note")
31
- ] = None,
32
- ):
33
- try:
34
- note = asyncio.run(mcp_write_note(title, content, folder, tags))
35
- rprint(note)
36
- except Exception as e: # pragma: no cover
37
- if not isinstance(e, typer.Exit):
38
- typer.echo(f"Error during write_note: {e}", err=True)
39
- raise typer.Exit(1)
40
- raise
41
-
42
-
43
- @tool_app.command()
44
- def read_note(identifier: str, page: int = 1, page_size: int = 10):
45
- try:
46
- note = asyncio.run(mcp_read_note(identifier, page, page_size))
47
- rprint(note)
48
- except Exception as e: # pragma: no cover
49
- if not isinstance(e, typer.Exit):
50
- typer.echo(f"Error during read_note: {e}", err=True)
51
- raise typer.Exit(1)
52
- raise
53
-
54
-
55
- @tool_app.command()
56
- def build_context(
57
- url: MemoryUrl,
58
- depth: Optional[int] = 1,
59
- timeframe: Optional[TimeFrame] = "7d",
60
- page: int = 1,
61
- page_size: int = 10,
62
- max_related: int = 10,
63
- ):
64
- try:
65
- context = asyncio.run(
66
- mcp_build_context(
67
- url=url,
68
- depth=depth,
69
- timeframe=timeframe,
70
- page=page,
71
- page_size=page_size,
72
- max_related=max_related,
73
- )
74
- )
75
- rprint(context.model_dump())
76
- except Exception as e: # pragma: no cover
77
- if not isinstance(e, typer.Exit):
78
- typer.echo(f"Error during build_context: {e}", err=True)
79
- raise typer.Exit(1)
80
- raise
81
-
82
-
83
- @tool_app.command()
84
- def recent_activity(
85
- type: Annotated[Optional[List[str]], typer.Option()] = ["entity", "observation", "relation"],
86
- depth: Optional[int] = 1,
87
- timeframe: Optional[TimeFrame] = "7d",
88
- page: int = 1,
89
- page_size: int = 10,
90
- max_related: int = 10,
91
- ):
92
- assert type is not None, "type is required"
93
- if any(t not in ["entity", "observation", "relation"] for t in type): # pragma: no cover
94
- print("type must be one of ['entity', 'observation', 'relation']")
95
- raise typer.Abort()
96
-
97
- try:
98
- context = asyncio.run(
99
- mcp_recent_activity(
100
- type=type, # pyright: ignore [reportArgumentType]
101
- depth=depth,
102
- timeframe=timeframe,
103
- page=page,
104
- page_size=page_size,
105
- max_related=max_related,
106
- )
107
- )
108
- rprint(context.model_dump())
109
- except Exception as e: # pragma: no cover
110
- if not isinstance(e, typer.Exit):
111
- typer.echo(f"Error during build_context: {e}", err=True)
112
- raise typer.Exit(1)
113
- raise
114
-
115
-
116
- @tool_app.command()
117
- def search(
118
- query: str,
119
- permalink: Annotated[bool, typer.Option("--permalink", help="Search permalink values")] = False,
120
- title: Annotated[bool, typer.Option("--title", help="Search title values")] = False,
121
- after_date: Annotated[
122
- Optional[str],
123
- typer.Option("--after_date", help="Search results after date, eg. '2d', '1 week'"),
124
- ] = None,
125
- page: int = 1,
126
- page_size: int = 10,
127
- ):
128
- if permalink and title: # pragma: no cover
129
- print("Cannot search both permalink and title")
130
- raise typer.Abort()
131
-
132
- try:
133
- search_query = SearchQuery(
134
- permalink_match=query if permalink else None,
135
- text=query if query else None,
136
- title=query if title else None,
137
- after_date=after_date,
138
- )
139
- results = asyncio.run(mcp_search(query=search_query, page=page, page_size=page_size))
140
- rprint(results.model_dump())
141
- except Exception as e: # pragma: no cover
142
- if not isinstance(e, typer.Exit):
143
- typer.echo(f"Error during search: {e}", err=True)
144
- raise typer.Exit(1)
145
- raise
146
-
147
-
148
- @tool_app.command()
149
- def get_entity(identifier: str):
150
- try:
151
- entity = asyncio.run(mcp_get_entity(identifier=identifier))
152
- rprint(entity.model_dump())
153
- except Exception as e: # pragma: no cover
154
- if not isinstance(e, typer.Exit):
155
- typer.echo(f"Error during get_entity: {e}", err=True)
156
- raise typer.Exit(1)
157
- raise
@@ -1,68 +0,0 @@
1
- """Knowledge graph management tools for Basic Memory MCP server."""
2
-
3
- import logfire
4
-
5
- from basic_memory.mcp.server import mcp
6
- from basic_memory.mcp.tools.utils import call_get, call_post
7
- from basic_memory.schemas.memory import memory_url_path
8
- from basic_memory.schemas.request import (
9
- GetEntitiesRequest,
10
- )
11
- from basic_memory.schemas.delete import (
12
- DeleteEntitiesRequest,
13
- )
14
- from basic_memory.schemas.response import EntityListResponse, EntityResponse, DeleteEntitiesResponse
15
- from basic_memory.mcp.async_client import client
16
-
17
-
18
- @mcp.tool(
19
- description="Get complete information about a specific entity including observations and relations",
20
- )
21
- async def get_entity(identifier: str) -> EntityResponse:
22
- """Get a specific entity info by its permalink.
23
-
24
- Args:
25
- identifier: Path identifier for the entity
26
- """
27
- with logfire.span("Getting entity", permalink=identifier): # pyright: ignore [reportGeneralTypeIssues]
28
- permalink = memory_url_path(identifier)
29
- url = f"/knowledge/entities/{permalink}"
30
- response = await call_get(client, url)
31
- return EntityResponse.model_validate(response.json())
32
-
33
-
34
- @mcp.tool(
35
- description="Load multiple entities by their permalinks in a single request",
36
- )
37
- async def get_entities(request: GetEntitiesRequest) -> EntityListResponse:
38
- """Load multiple entities by their permalinks.
39
-
40
- Args:
41
- request: OpenNodesRequest containing list of permalinks to load
42
-
43
- Returns:
44
- EntityListResponse containing complete details for each requested entity
45
- """
46
- with logfire.span("Getting multiple entities", permalink_count=len(request.permalinks)): # pyright: ignore [reportGeneralTypeIssues]
47
- url = "/knowledge/entities"
48
- response = await call_get(
49
- client,
50
- url,
51
- params=[
52
- ("permalink", memory_url_path(identifier)) for identifier in request.permalinks
53
- ],
54
- )
55
- return EntityListResponse.model_validate(response.json())
56
-
57
-
58
- @mcp.tool(
59
- description="Permanently delete entities and all related content (observations and relations)",
60
- )
61
- async def delete_entities(request: DeleteEntitiesRequest) -> DeleteEntitiesResponse:
62
- """Delete entities from the knowledge graph."""
63
- with logfire.span("Deleting entities", permalink_count=len(request.permalinks)): # pyright: ignore [reportGeneralTypeIssues]
64
- url = "/knowledge/entities/delete"
65
-
66
- request.permalinks = [memory_url_path(permlink) for permlink in request.permalinks]
67
- response = await call_post(client, url, json=request.model_dump())
68
- return DeleteEntitiesResponse.model_validate(response.json())
@@ -1,170 +0,0 @@
1
- """Discussion context tools for Basic Memory MCP server."""
2
-
3
- from typing import Optional, Literal, List
4
-
5
- from loguru import logger
6
- import logfire
7
-
8
- from basic_memory.mcp.async_client import client
9
- from basic_memory.mcp.server import mcp
10
- from basic_memory.mcp.tools.utils import call_get
11
- from basic_memory.schemas.memory import (
12
- GraphContext,
13
- MemoryUrl,
14
- memory_url_path,
15
- normalize_memory_url,
16
- )
17
- from basic_memory.schemas.base import TimeFrame
18
-
19
-
20
- @mcp.tool(
21
- description="""Build context from a memory:// URI to continue conversations naturally.
22
-
23
- Use this to follow up on previous discussions or explore related topics.
24
- Timeframes support natural language like:
25
- - "2 days ago"
26
- - "last week"
27
- - "today"
28
- - "3 months ago"
29
- Or standard formats like "7d", "24h"
30
- """,
31
- )
32
- async def build_context(
33
- url: MemoryUrl,
34
- depth: Optional[int] = 1,
35
- timeframe: Optional[TimeFrame] = "7d",
36
- page: int = 1,
37
- page_size: int = 10,
38
- max_related: int = 10,
39
- ) -> GraphContext:
40
- """Get context needed to continue a discussion.
41
-
42
- This tool enables natural continuation of discussions by loading relevant context
43
- from memory:// URIs. It uses pattern matching to find relevant content and builds
44
- a rich context graph of related information.
45
-
46
- Args:
47
- url: memory:// URI pointing to discussion content (e.g. memory://specs/search)
48
- depth: How many relation hops to traverse (1-3 recommended for performance)
49
- timeframe: How far back to look. Supports natural language like "2 days ago", "last week"
50
- page: Page number of results to return (default: 1)
51
- page_size: Number of results to return per page (default: 10)
52
- max_related: Maximum number of related results to return (default: 10)
53
-
54
- Returns:
55
- GraphContext containing:
56
- - primary_results: Content matching the memory:// URI
57
- - related_results: Connected content via relations
58
- - metadata: Context building details
59
-
60
- Examples:
61
- # Continue a specific discussion
62
- build_context("memory://specs/search")
63
-
64
- # Get deeper context about a component
65
- build_context("memory://components/memory-service", depth=2)
66
-
67
- # Look at recent changes to a specification
68
- build_context("memory://specs/document-format", timeframe="today")
69
-
70
- # Research the history of a feature
71
- build_context("memory://features/knowledge-graph", timeframe="3 months ago")
72
- """
73
- with logfire.span("Building context", url=url, depth=depth, timeframe=timeframe): # pyright: ignore [reportGeneralTypeIssues]
74
- logger.info(f"Building context from {url}")
75
- url = normalize_memory_url(url)
76
- response = await call_get(
77
- client,
78
- f"/memory/{memory_url_path(url)}",
79
- params={
80
- "depth": depth,
81
- "timeframe": timeframe,
82
- "page": page,
83
- "page_size": page_size,
84
- "max_related": max_related,
85
- },
86
- )
87
- return GraphContext.model_validate(response.json())
88
-
89
-
90
- @mcp.tool(
91
- description="""Get recent activity from across the knowledge base.
92
-
93
- Timeframe supports natural language formats like:
94
- - "2 days ago"
95
- - "last week"
96
- - "yesterday"
97
- - "today"
98
- - "3 weeks ago"
99
- Or standard formats like "7d"
100
- """,
101
- )
102
- async def recent_activity(
103
- type: List[Literal["entity", "observation", "relation"]] = [],
104
- depth: Optional[int] = 1,
105
- timeframe: Optional[TimeFrame] = "7d",
106
- page: int = 1,
107
- page_size: int = 10,
108
- max_related: int = 10,
109
- ) -> GraphContext:
110
- """Get recent activity across the knowledge base.
111
-
112
- Args:
113
- type: Filter by content type(s). Valid options:
114
- - ["entity"] for knowledge entities
115
- - ["relation"] for connections between entities
116
- - ["observation"] for notes and observations
117
- Multiple types can be combined: ["entity", "relation"]
118
- depth: How many relation hops to traverse (1-3 recommended)
119
- timeframe: Time window to search. Supports natural language:
120
- - Relative: "2 days ago", "last week", "yesterday"
121
- - Points in time: "2024-01-01", "January 1st"
122
- - Standard format: "7d", "24h"
123
- page: Page number of results to return (default: 1)
124
- page_size: Number of results to return per page (default: 10)
125
- max_related: Maximum number of related results to return (default: 10)
126
-
127
- Returns:
128
- GraphContext containing:
129
- - primary_results: Latest activities matching the filters
130
- - related_results: Connected content via relations
131
- - metadata: Query details and statistics
132
-
133
- Examples:
134
- # Get all entities for the last 10 days (default)
135
- recent_activity()
136
-
137
- # Get all entities from yesterday
138
- recent_activity(type=["entity"], timeframe="yesterday")
139
-
140
- # Get recent relations and observations
141
- recent_activity(type=["relation", "observation"], timeframe="today")
142
-
143
- # Look back further with more context
144
- recent_activity(type=["entity"], depth=2, timeframe="2 weeks ago")
145
-
146
- Notes:
147
- - Higher depth values (>3) may impact performance with large result sets
148
- - For focused queries, consider using build_context with a specific URI
149
- - Max timeframe is 1 year in the past
150
- """
151
- with logfire.span("Getting recent activity", type=type, depth=depth, timeframe=timeframe): # pyright: ignore [reportGeneralTypeIssues]
152
- logger.info(
153
- f"Getting recent activity from {type}, depth={depth}, timeframe={timeframe}, page={page}, page_size={page_size}, max_related={max_related}"
154
- )
155
- params = {
156
- "depth": depth,
157
- "timeframe": timeframe,
158
- "page": page,
159
- "page_size": page_size,
160
- "max_related": max_related,
161
- }
162
- if type:
163
- params["type"] = type
164
-
165
- response = await call_get(
166
- client,
167
- "/memory/recent",
168
- params=params,
169
- )
170
- return GraphContext.model_validate(response.json())