basic-memory 0.17.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.
Files changed (171) hide show
  1. basic_memory/__init__.py +7 -0
  2. basic_memory/alembic/alembic.ini +119 -0
  3. basic_memory/alembic/env.py +185 -0
  4. basic_memory/alembic/migrations.py +24 -0
  5. basic_memory/alembic/script.py.mako +26 -0
  6. basic_memory/alembic/versions/314f1ea54dc4_add_postgres_full_text_search_support_.py +131 -0
  7. basic_memory/alembic/versions/3dae7c7b1564_initial_schema.py +93 -0
  8. basic_memory/alembic/versions/502b60eaa905_remove_required_from_entity_permalink.py +51 -0
  9. basic_memory/alembic/versions/5fe1ab1ccebe_add_projects_table.py +120 -0
  10. basic_memory/alembic/versions/647e7a75e2cd_project_constraint_fix.py +112 -0
  11. basic_memory/alembic/versions/9d9c1cb7d8f5_add_mtime_and_size_columns_to_entity_.py +49 -0
  12. basic_memory/alembic/versions/a1b2c3d4e5f6_fix_project_foreign_keys.py +49 -0
  13. basic_memory/alembic/versions/a2b3c4d5e6f7_add_search_index_entity_cascade.py +56 -0
  14. basic_memory/alembic/versions/b3c3938bacdb_relation_to_name_unique_index.py +44 -0
  15. basic_memory/alembic/versions/cc7172b46608_update_search_index_schema.py +113 -0
  16. basic_memory/alembic/versions/e7e1f4367280_add_scan_watermark_tracking_to_project.py +37 -0
  17. basic_memory/alembic/versions/f8a9b2c3d4e5_add_pg_trgm_for_fuzzy_link_resolution.py +239 -0
  18. basic_memory/api/__init__.py +5 -0
  19. basic_memory/api/app.py +131 -0
  20. basic_memory/api/routers/__init__.py +11 -0
  21. basic_memory/api/routers/directory_router.py +84 -0
  22. basic_memory/api/routers/importer_router.py +152 -0
  23. basic_memory/api/routers/knowledge_router.py +318 -0
  24. basic_memory/api/routers/management_router.py +80 -0
  25. basic_memory/api/routers/memory_router.py +90 -0
  26. basic_memory/api/routers/project_router.py +448 -0
  27. basic_memory/api/routers/prompt_router.py +260 -0
  28. basic_memory/api/routers/resource_router.py +249 -0
  29. basic_memory/api/routers/search_router.py +36 -0
  30. basic_memory/api/routers/utils.py +169 -0
  31. basic_memory/api/template_loader.py +292 -0
  32. basic_memory/api/v2/__init__.py +35 -0
  33. basic_memory/api/v2/routers/__init__.py +21 -0
  34. basic_memory/api/v2/routers/directory_router.py +93 -0
  35. basic_memory/api/v2/routers/importer_router.py +182 -0
  36. basic_memory/api/v2/routers/knowledge_router.py +413 -0
  37. basic_memory/api/v2/routers/memory_router.py +130 -0
  38. basic_memory/api/v2/routers/project_router.py +342 -0
  39. basic_memory/api/v2/routers/prompt_router.py +270 -0
  40. basic_memory/api/v2/routers/resource_router.py +286 -0
  41. basic_memory/api/v2/routers/search_router.py +73 -0
  42. basic_memory/cli/__init__.py +1 -0
  43. basic_memory/cli/app.py +84 -0
  44. basic_memory/cli/auth.py +277 -0
  45. basic_memory/cli/commands/__init__.py +18 -0
  46. basic_memory/cli/commands/cloud/__init__.py +6 -0
  47. basic_memory/cli/commands/cloud/api_client.py +112 -0
  48. basic_memory/cli/commands/cloud/bisync_commands.py +110 -0
  49. basic_memory/cli/commands/cloud/cloud_utils.py +101 -0
  50. basic_memory/cli/commands/cloud/core_commands.py +195 -0
  51. basic_memory/cli/commands/cloud/rclone_commands.py +371 -0
  52. basic_memory/cli/commands/cloud/rclone_config.py +110 -0
  53. basic_memory/cli/commands/cloud/rclone_installer.py +263 -0
  54. basic_memory/cli/commands/cloud/upload.py +233 -0
  55. basic_memory/cli/commands/cloud/upload_command.py +124 -0
  56. basic_memory/cli/commands/command_utils.py +77 -0
  57. basic_memory/cli/commands/db.py +44 -0
  58. basic_memory/cli/commands/format.py +198 -0
  59. basic_memory/cli/commands/import_chatgpt.py +84 -0
  60. basic_memory/cli/commands/import_claude_conversations.py +87 -0
  61. basic_memory/cli/commands/import_claude_projects.py +86 -0
  62. basic_memory/cli/commands/import_memory_json.py +87 -0
  63. basic_memory/cli/commands/mcp.py +76 -0
  64. basic_memory/cli/commands/project.py +889 -0
  65. basic_memory/cli/commands/status.py +174 -0
  66. basic_memory/cli/commands/telemetry.py +81 -0
  67. basic_memory/cli/commands/tool.py +341 -0
  68. basic_memory/cli/main.py +28 -0
  69. basic_memory/config.py +616 -0
  70. basic_memory/db.py +394 -0
  71. basic_memory/deps.py +705 -0
  72. basic_memory/file_utils.py +478 -0
  73. basic_memory/ignore_utils.py +297 -0
  74. basic_memory/importers/__init__.py +27 -0
  75. basic_memory/importers/base.py +79 -0
  76. basic_memory/importers/chatgpt_importer.py +232 -0
  77. basic_memory/importers/claude_conversations_importer.py +180 -0
  78. basic_memory/importers/claude_projects_importer.py +148 -0
  79. basic_memory/importers/memory_json_importer.py +108 -0
  80. basic_memory/importers/utils.py +61 -0
  81. basic_memory/markdown/__init__.py +21 -0
  82. basic_memory/markdown/entity_parser.py +279 -0
  83. basic_memory/markdown/markdown_processor.py +160 -0
  84. basic_memory/markdown/plugins.py +242 -0
  85. basic_memory/markdown/schemas.py +70 -0
  86. basic_memory/markdown/utils.py +117 -0
  87. basic_memory/mcp/__init__.py +1 -0
  88. basic_memory/mcp/async_client.py +139 -0
  89. basic_memory/mcp/project_context.py +141 -0
  90. basic_memory/mcp/prompts/__init__.py +19 -0
  91. basic_memory/mcp/prompts/ai_assistant_guide.py +70 -0
  92. basic_memory/mcp/prompts/continue_conversation.py +62 -0
  93. basic_memory/mcp/prompts/recent_activity.py +188 -0
  94. basic_memory/mcp/prompts/search.py +57 -0
  95. basic_memory/mcp/prompts/utils.py +162 -0
  96. basic_memory/mcp/resources/ai_assistant_guide.md +283 -0
  97. basic_memory/mcp/resources/project_info.py +71 -0
  98. basic_memory/mcp/server.py +81 -0
  99. basic_memory/mcp/tools/__init__.py +48 -0
  100. basic_memory/mcp/tools/build_context.py +120 -0
  101. basic_memory/mcp/tools/canvas.py +152 -0
  102. basic_memory/mcp/tools/chatgpt_tools.py +190 -0
  103. basic_memory/mcp/tools/delete_note.py +242 -0
  104. basic_memory/mcp/tools/edit_note.py +324 -0
  105. basic_memory/mcp/tools/list_directory.py +168 -0
  106. basic_memory/mcp/tools/move_note.py +551 -0
  107. basic_memory/mcp/tools/project_management.py +201 -0
  108. basic_memory/mcp/tools/read_content.py +281 -0
  109. basic_memory/mcp/tools/read_note.py +267 -0
  110. basic_memory/mcp/tools/recent_activity.py +534 -0
  111. basic_memory/mcp/tools/search.py +385 -0
  112. basic_memory/mcp/tools/utils.py +540 -0
  113. basic_memory/mcp/tools/view_note.py +78 -0
  114. basic_memory/mcp/tools/write_note.py +230 -0
  115. basic_memory/models/__init__.py +15 -0
  116. basic_memory/models/base.py +10 -0
  117. basic_memory/models/knowledge.py +226 -0
  118. basic_memory/models/project.py +87 -0
  119. basic_memory/models/search.py +85 -0
  120. basic_memory/repository/__init__.py +11 -0
  121. basic_memory/repository/entity_repository.py +503 -0
  122. basic_memory/repository/observation_repository.py +73 -0
  123. basic_memory/repository/postgres_search_repository.py +379 -0
  124. basic_memory/repository/project_info_repository.py +10 -0
  125. basic_memory/repository/project_repository.py +128 -0
  126. basic_memory/repository/relation_repository.py +146 -0
  127. basic_memory/repository/repository.py +385 -0
  128. basic_memory/repository/search_index_row.py +95 -0
  129. basic_memory/repository/search_repository.py +94 -0
  130. basic_memory/repository/search_repository_base.py +241 -0
  131. basic_memory/repository/sqlite_search_repository.py +439 -0
  132. basic_memory/schemas/__init__.py +86 -0
  133. basic_memory/schemas/base.py +297 -0
  134. basic_memory/schemas/cloud.py +50 -0
  135. basic_memory/schemas/delete.py +37 -0
  136. basic_memory/schemas/directory.py +30 -0
  137. basic_memory/schemas/importer.py +35 -0
  138. basic_memory/schemas/memory.py +285 -0
  139. basic_memory/schemas/project_info.py +212 -0
  140. basic_memory/schemas/prompt.py +90 -0
  141. basic_memory/schemas/request.py +112 -0
  142. basic_memory/schemas/response.py +229 -0
  143. basic_memory/schemas/search.py +117 -0
  144. basic_memory/schemas/sync_report.py +72 -0
  145. basic_memory/schemas/v2/__init__.py +27 -0
  146. basic_memory/schemas/v2/entity.py +129 -0
  147. basic_memory/schemas/v2/resource.py +46 -0
  148. basic_memory/services/__init__.py +8 -0
  149. basic_memory/services/context_service.py +601 -0
  150. basic_memory/services/directory_service.py +308 -0
  151. basic_memory/services/entity_service.py +864 -0
  152. basic_memory/services/exceptions.py +37 -0
  153. basic_memory/services/file_service.py +541 -0
  154. basic_memory/services/initialization.py +216 -0
  155. basic_memory/services/link_resolver.py +121 -0
  156. basic_memory/services/project_service.py +880 -0
  157. basic_memory/services/search_service.py +404 -0
  158. basic_memory/services/service.py +15 -0
  159. basic_memory/sync/__init__.py +6 -0
  160. basic_memory/sync/background_sync.py +26 -0
  161. basic_memory/sync/sync_service.py +1259 -0
  162. basic_memory/sync/watch_service.py +510 -0
  163. basic_memory/telemetry.py +249 -0
  164. basic_memory/templates/prompts/continue_conversation.hbs +110 -0
  165. basic_memory/templates/prompts/search.hbs +101 -0
  166. basic_memory/utils.py +468 -0
  167. basic_memory-0.17.1.dist-info/METADATA +617 -0
  168. basic_memory-0.17.1.dist-info/RECORD +171 -0
  169. basic_memory-0.17.1.dist-info/WHEEL +4 -0
  170. basic_memory-0.17.1.dist-info/entry_points.txt +3 -0
  171. basic_memory-0.17.1.dist-info/licenses/LICENSE +661 -0
@@ -0,0 +1,201 @@
1
+ """Project management tools for Basic Memory MCP server.
2
+
3
+ These tools allow users to switch between projects, list available projects,
4
+ and manage project context during conversations.
5
+ """
6
+
7
+ import os
8
+ from fastmcp import Context
9
+
10
+ from basic_memory.mcp.async_client import get_client
11
+ from basic_memory.mcp.server import mcp
12
+ from basic_memory.mcp.tools.utils import call_get, call_post, call_delete
13
+ from basic_memory.schemas.project_info import (
14
+ ProjectList,
15
+ ProjectStatusResponse,
16
+ ProjectInfoRequest,
17
+ )
18
+ from basic_memory.telemetry import track_mcp_tool
19
+ from basic_memory.utils import generate_permalink
20
+
21
+
22
+ @mcp.tool("list_memory_projects")
23
+ async def list_memory_projects(context: Context | None = None) -> str:
24
+ """List all available projects with their status.
25
+
26
+ Shows all Basic Memory projects that are available for MCP operations.
27
+ Use this tool to discover projects when you need to know which project to use.
28
+
29
+ Use this tool:
30
+ - At conversation start when project is unknown
31
+ - When user asks about available projects
32
+ - Before any operation requiring a project
33
+
34
+ After calling:
35
+ - Ask user which project to use
36
+ - Remember their choice for the session
37
+
38
+ Returns:
39
+ Formatted list of projects with session management guidance
40
+
41
+ Example:
42
+ list_memory_projects()
43
+ """
44
+ track_mcp_tool("list_memory_projects")
45
+ async with get_client() as client:
46
+ if context: # pragma: no cover
47
+ await context.info("Listing all available projects")
48
+
49
+ # Check if server is constrained to a specific project
50
+ constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
51
+
52
+ # Get projects from API
53
+ response = await call_get(client, "/projects/projects")
54
+ project_list = ProjectList.model_validate(response.json())
55
+
56
+ if constrained_project:
57
+ result = f"Project: {constrained_project}\n\n"
58
+ result += "Note: This MCP server is constrained to a single project.\n"
59
+ result += "All operations will automatically use this project."
60
+ else:
61
+ # Show all projects with session guidance
62
+ result = "Available projects:\n"
63
+
64
+ for project in project_list.projects:
65
+ result += f"• {project.name}\n"
66
+
67
+ result += "\n" + "─" * 40 + "\n"
68
+ result += "Next: Ask which project to use for this session.\n"
69
+ result += "Example: 'Which project should I use for this task?'\n\n"
70
+ result += "Session reminder: Track the selected project for all subsequent operations in this conversation.\n"
71
+ result += "The user can say 'switch to [project]' to change projects."
72
+
73
+ return result
74
+
75
+
76
+ @mcp.tool("create_memory_project")
77
+ async def create_memory_project(
78
+ project_name: str, project_path: str, set_default: bool = False, context: Context | None = None
79
+ ) -> str:
80
+ """Create a new Basic Memory project.
81
+
82
+ Creates a new project with the specified name and path. The project directory
83
+ will be created if it doesn't exist. Optionally sets the new project as default.
84
+
85
+ Args:
86
+ project_name: Name for the new project (must be unique)
87
+ project_path: File system path where the project will be stored
88
+ set_default: Whether to set this project as the default (optional, defaults to False)
89
+
90
+ Returns:
91
+ Confirmation message with project details
92
+
93
+ Example:
94
+ create_memory_project("my-research", "~/Documents/research")
95
+ create_memory_project("work-notes", "/home/user/work", set_default=True)
96
+ """
97
+ track_mcp_tool("create_memory_project")
98
+ async with get_client() as client:
99
+ # Check if server is constrained to a specific project
100
+ constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
101
+ if constrained_project:
102
+ return f'# Error\n\nProject creation disabled - MCP server is constrained to project \'{constrained_project}\'.\nUse the CLI to create projects: `basic-memory project add "{project_name}" "{project_path}"`'
103
+
104
+ if context: # pragma: no cover
105
+ await context.info(f"Creating project: {project_name} at {project_path}")
106
+
107
+ # Create the project request
108
+ project_request = ProjectInfoRequest(
109
+ name=project_name, path=project_path, set_default=set_default
110
+ )
111
+
112
+ # Call API to create project
113
+ response = await call_post(client, "/projects/projects", json=project_request.model_dump())
114
+ status_response = ProjectStatusResponse.model_validate(response.json())
115
+
116
+ result = f"✓ {status_response.message}\n\n"
117
+
118
+ if status_response.new_project:
119
+ result += "Project Details:\n"
120
+ result += f"• Name: {status_response.new_project.name}\n"
121
+ result += f"• Path: {status_response.new_project.path}\n"
122
+
123
+ if set_default:
124
+ result += "• Set as default project\n"
125
+
126
+ result += "\nProject is now available for use in tool calls.\n"
127
+ result += f"Use '{project_name}' as the project parameter in MCP tool calls.\n"
128
+
129
+ return result
130
+
131
+
132
+ @mcp.tool()
133
+ async def delete_project(project_name: str, context: Context | None = None) -> str:
134
+ """Delete a Basic Memory project.
135
+
136
+ Removes a project from the configuration and database. This does NOT delete
137
+ the actual files on disk - only removes the project from Basic Memory's
138
+ configuration and database records.
139
+
140
+ Args:
141
+ project_name: Name of the project to delete
142
+
143
+ Returns:
144
+ Confirmation message about project deletion
145
+
146
+ Example:
147
+ delete_project("old-project")
148
+
149
+ Warning:
150
+ This action cannot be undone. The project will need to be re-added
151
+ to access its content through Basic Memory again.
152
+ """
153
+ track_mcp_tool("delete_project")
154
+ async with get_client() as client:
155
+ # Check if server is constrained to a specific project
156
+ constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
157
+ if constrained_project:
158
+ return f"# Error\n\nProject deletion disabled - MCP server is constrained to project '{constrained_project}'.\nUse the CLI to delete projects: `basic-memory project remove \"{project_name}\"`"
159
+
160
+ if context: # pragma: no cover
161
+ await context.info(f"Deleting project: {project_name}")
162
+
163
+ # Get project info before deletion to validate it exists
164
+ response = await call_get(client, "/projects/projects")
165
+ project_list = ProjectList.model_validate(response.json())
166
+
167
+ # Find the project by name (case-insensitive) or permalink - same logic as switch_project
168
+ project_permalink = generate_permalink(project_name)
169
+ target_project = None
170
+ for p in project_list.projects:
171
+ # Match by permalink (handles case-insensitive input)
172
+ if p.permalink == project_permalink:
173
+ target_project = p
174
+ break
175
+ # Also match by name comparison (case-insensitive)
176
+ if p.name.lower() == project_name.lower():
177
+ target_project = p
178
+ break
179
+
180
+ if not target_project:
181
+ available_projects = [p.name for p in project_list.projects]
182
+ raise ValueError(
183
+ f"Project '{project_name}' not found. Available projects: {', '.join(available_projects)}"
184
+ )
185
+
186
+ # Call v2 API to delete project using project ID
187
+ response = await call_delete(client, f"/v2/projects/{target_project.id}")
188
+ status_response = ProjectStatusResponse.model_validate(response.json())
189
+
190
+ result = f"✓ {status_response.message}\n\n"
191
+
192
+ if status_response.old_project:
193
+ result += "Removed project details:\n"
194
+ result += f"• Name: {status_response.old_project.name}\n"
195
+ if hasattr(status_response.old_project, "path"):
196
+ result += f"• Path: {status_response.old_project.path}\n"
197
+
198
+ result += "Files remain on disk but project is no longer tracked by Basic Memory.\n"
199
+ result += "Re-add the project to access its content again.\n"
200
+
201
+ return result
@@ -0,0 +1,281 @@
1
+ """File reading tool for Basic Memory MCP server.
2
+
3
+ This module provides tools for reading raw file content directly,
4
+ supporting various file types including text, images, and other binary files.
5
+ Files are read directly without any knowledge graph processing.
6
+ """
7
+
8
+ import base64
9
+ import io
10
+
11
+ from typing import Optional
12
+
13
+ from loguru import logger
14
+ from PIL import Image as PILImage
15
+ from fastmcp import Context
16
+ from mcp.server.fastmcp.exceptions import ToolError
17
+
18
+ from basic_memory.mcp.project_context import get_active_project
19
+ from basic_memory.mcp.server import mcp
20
+ from basic_memory.mcp.async_client import get_client
21
+ from basic_memory.mcp.tools.utils import call_get, resolve_entity_id
22
+ from basic_memory.schemas.memory import memory_url_path
23
+ from basic_memory.telemetry import track_mcp_tool
24
+ from basic_memory.utils import validate_project_path
25
+
26
+
27
+ def calculate_target_params(content_length):
28
+ """Calculate initial quality and size based on input file size"""
29
+ target_size = 350000 # Reduced target for more safety margin
30
+ ratio = content_length / target_size
31
+
32
+ logger.debug(
33
+ "Calculating target parameters",
34
+ content_length=content_length,
35
+ ratio=ratio,
36
+ target_size=target_size,
37
+ )
38
+
39
+ if ratio > 4:
40
+ # Very large images - start very aggressive
41
+ return 50, 600 # Lower initial quality and size
42
+ elif ratio > 2:
43
+ return 60, 800
44
+ else:
45
+ return 70, 1000
46
+
47
+
48
+ def resize_image(img, max_size):
49
+ """Resize image maintaining aspect ratio"""
50
+ original_dimensions = {"width": img.width, "height": img.height}
51
+
52
+ if img.width > max_size or img.height > max_size:
53
+ ratio = min(max_size / img.width, max_size / img.height)
54
+ new_size = (int(img.width * ratio), int(img.height * ratio))
55
+ logger.debug("Resizing image", original=original_dimensions, target=new_size, ratio=ratio)
56
+ return img.resize(new_size, PILImage.Resampling.LANCZOS)
57
+
58
+ logger.debug("No resize needed", dimensions=original_dimensions)
59
+ return img
60
+
61
+
62
+ def optimize_image(img, content_length, max_output_bytes=350000):
63
+ """Iteratively optimize image with aggressive size reduction"""
64
+ stats = {
65
+ "dimensions": {"width": img.width, "height": img.height},
66
+ "mode": img.mode,
67
+ "estimated_memory": (img.width * img.height * len(img.getbands())),
68
+ }
69
+
70
+ initial_quality, initial_size = calculate_target_params(content_length)
71
+
72
+ logger.debug(
73
+ "Starting optimization",
74
+ image_stats=stats,
75
+ content_length=content_length,
76
+ initial_quality=initial_quality,
77
+ initial_size=initial_size,
78
+ max_output_bytes=max_output_bytes,
79
+ )
80
+
81
+ quality = initial_quality
82
+ size = initial_size
83
+
84
+ # Convert to RGB if needed
85
+ if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
86
+ img = img.convert("RGB")
87
+ logger.debug("Converted to RGB mode")
88
+
89
+ iteration = 0
90
+ min_size = 300 # Absolute minimum size
91
+ min_quality = 20 # Absolute minimum quality
92
+
93
+ while True:
94
+ iteration += 1
95
+ buf = io.BytesIO()
96
+ resized = resize_image(img, size)
97
+
98
+ resized.save(
99
+ buf,
100
+ format="JPEG",
101
+ quality=quality,
102
+ optimize=True,
103
+ progressive=True,
104
+ subsampling="4:2:0",
105
+ )
106
+
107
+ output_size = buf.getbuffer().nbytes
108
+ reduction_ratio = output_size / content_length
109
+
110
+ logger.debug(
111
+ "Optimization attempt",
112
+ iteration=iteration,
113
+ quality=quality,
114
+ size=size,
115
+ output_bytes=output_size,
116
+ target_bytes=max_output_bytes,
117
+ reduction_ratio=f"{reduction_ratio:.2f}",
118
+ )
119
+
120
+ if output_size < max_output_bytes:
121
+ logger.info(
122
+ "Image optimization complete",
123
+ final_size=output_size,
124
+ quality=quality,
125
+ dimensions={"width": resized.width, "height": resized.height},
126
+ reduction_ratio=f"{reduction_ratio:.2f}",
127
+ )
128
+ return buf.getvalue()
129
+
130
+ # Very aggressive reduction for large files
131
+ if content_length > 2000000: # 2MB+ # pragma: no cover
132
+ quality = max(min_quality, quality - 20)
133
+ size = max(min_size, int(size * 0.6))
134
+ elif content_length > 1000000: # 1MB+ # pragma: no cover
135
+ quality = max(min_quality, quality - 15)
136
+ size = max(min_size, int(size * 0.7))
137
+ else:
138
+ quality = max(min_quality, quality - 10) # pragma: no cover
139
+ size = max(min_size, int(size * 0.8)) # pragma: no cover
140
+
141
+ logger.debug("Reducing parameters", new_quality=quality, new_size=size) # pragma: no cover
142
+
143
+ # If we've hit minimum values and still too big
144
+ if quality <= min_quality and size <= min_size: # pragma: no cover
145
+ logger.warning(
146
+ "Reached minimum parameters",
147
+ final_size=output_size,
148
+ over_limit_by=output_size - max_output_bytes,
149
+ )
150
+ return buf.getvalue()
151
+
152
+
153
+ @mcp.tool(description="Read a file's raw content by path or permalink")
154
+ async def read_content(
155
+ path: str, project: Optional[str] = None, context: Context | None = None
156
+ ) -> dict:
157
+ """Read a file's raw content by path or permalink.
158
+
159
+ This tool provides direct access to file content in the knowledge base,
160
+ handling different file types appropriately. Uses stateless architecture -
161
+ project parameter optional with server resolution.
162
+
163
+ Supported file types:
164
+ - Text files (markdown, code, etc.) are returned as plain text
165
+ - Images are automatically resized/optimized for display
166
+ - Other binary files are returned as base64 if below size limits
167
+
168
+ Args:
169
+ path: The path or permalink to the file. Can be:
170
+ - A regular file path (docs/example.md)
171
+ - A memory URL (memory://docs/example)
172
+ - A permalink (docs/example)
173
+ project: Project name to read from. Optional - server will resolve using hierarchy.
174
+ If unknown, use list_memory_projects() to discover available projects.
175
+ context: Optional FastMCP context for performance caching.
176
+
177
+ Returns:
178
+ A dictionary with the file content and metadata:
179
+ - For text: {"type": "text", "text": "content", "content_type": "text/markdown", "encoding": "utf-8"}
180
+ - For images: {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "base64_data"}}
181
+ - For other files: {"type": "document", "source": {"type": "base64", "media_type": "content_type", "data": "base64_data"}}
182
+ - For errors: {"type": "error", "error": "error message"}
183
+
184
+ Examples:
185
+ # Read a markdown file
186
+ result = await read_content("docs/project-specs.md")
187
+
188
+ # Read an image
189
+ image_data = await read_content("assets/diagram.png")
190
+
191
+ # Read using memory URL
192
+ content = await read_content("memory://docs/architecture")
193
+
194
+ # Read configuration file
195
+ config = await read_content("config/settings.json")
196
+
197
+ # Explicit project specification
198
+ result = await read_content("docs/project-specs.md", project="my-project")
199
+
200
+ Raises:
201
+ HTTPError: If project doesn't exist or is inaccessible
202
+ SecurityError: If path attempts path traversal
203
+ """
204
+ track_mcp_tool("read_content")
205
+ logger.info("Reading file", path=path, project=project)
206
+
207
+ async with get_client() as client:
208
+ active_project = await get_active_project(client, project, context)
209
+
210
+ url = memory_url_path(path)
211
+
212
+ # Validate path to prevent path traversal attacks
213
+ project_path = active_project.home
214
+ if not validate_project_path(url, project_path):
215
+ logger.warning(
216
+ "Attempted path traversal attack blocked",
217
+ path=path,
218
+ url=url,
219
+ project=active_project.name,
220
+ )
221
+ return {
222
+ "type": "error",
223
+ "error": f"Path '{path}' is not allowed - paths must stay within project boundaries",
224
+ }
225
+
226
+ # Resolve path to entity ID
227
+ try:
228
+ entity_id = await resolve_entity_id(client, active_project.id, url)
229
+ except ToolError:
230
+ # Convert resolution errors to "Resource not found" for consistency
231
+ raise ToolError(f"Resource not found: {url}")
232
+
233
+ # Call the v2 resource endpoint
234
+ response = await call_get(client, f"/v2/projects/{active_project.id}/resource/{entity_id}")
235
+ content_type = response.headers.get("content-type", "application/octet-stream")
236
+ content_length = int(response.headers.get("content-length", 0))
237
+
238
+ logger.debug("Resource metadata", content_type=content_type, size=content_length, path=path)
239
+
240
+ # Handle text or json
241
+ if content_type.startswith("text/") or content_type == "application/json":
242
+ logger.debug("Processing text resource")
243
+ return {
244
+ "type": "text",
245
+ "text": response.text,
246
+ "content_type": content_type,
247
+ "encoding": "utf-8",
248
+ }
249
+
250
+ # Handle images
251
+ elif content_type.startswith("image/"):
252
+ logger.debug("Processing image")
253
+ img = PILImage.open(io.BytesIO(response.content))
254
+ img_bytes = optimize_image(img, content_length)
255
+
256
+ return {
257
+ "type": "image",
258
+ "source": {
259
+ "type": "base64",
260
+ "media_type": "image/jpeg",
261
+ "data": base64.b64encode(img_bytes).decode("utf-8"),
262
+ },
263
+ }
264
+
265
+ # Handle other file types
266
+ else:
267
+ logger.debug(f"Processing binary resource content_type {content_type}")
268
+ if content_length > 350000: # pragma: no cover
269
+ logger.warning("Document too large for response", size=content_length)
270
+ return {
271
+ "type": "error",
272
+ "error": f"Document size {content_length} bytes exceeds maximum allowed size",
273
+ }
274
+ return {
275
+ "type": "document",
276
+ "source": {
277
+ "type": "base64",
278
+ "media_type": content_type,
279
+ "data": base64.b64encode(response.content).decode("utf-8"),
280
+ },
281
+ }