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
@@ -0,0 +1,200 @@
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.utils import generate_permalink
19
+
20
+
21
+ @mcp.tool("list_memory_projects")
22
+ async def list_memory_projects(context: Context | None = None) -> str:
23
+ """List all available projects with their status.
24
+
25
+ Shows all Basic Memory projects that are available for MCP operations.
26
+ Use this tool to discover projects when you need to know which project to use.
27
+
28
+ Use this tool:
29
+ - At conversation start when project is unknown
30
+ - When user asks about available projects
31
+ - Before any operation requiring a project
32
+
33
+ After calling:
34
+ - Ask user which project to use
35
+ - Remember their choice for the session
36
+
37
+ Returns:
38
+ Formatted list of projects with session management guidance
39
+
40
+ Example:
41
+ list_memory_projects()
42
+ """
43
+ async with get_client() as client:
44
+ if context: # pragma: no cover
45
+ await context.info("Listing all available projects")
46
+
47
+ # Check if server is constrained to a specific project
48
+ constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
49
+
50
+ # Get projects from API
51
+ response = await call_get(client, "/projects/projects")
52
+ project_list = ProjectList.model_validate(response.json())
53
+
54
+ if constrained_project:
55
+ result = f"Project: {constrained_project}\n\n"
56
+ result += "Note: This MCP server is constrained to a single project.\n"
57
+ result += "All operations will automatically use this project."
58
+ else:
59
+ # Show all projects with session guidance
60
+ result = "Available projects:\n"
61
+
62
+ for project in project_list.projects:
63
+ result += f"• {project.name}\n"
64
+
65
+ result += "\n" + "─" * 40 + "\n"
66
+ result += "Next: Ask which project to use for this session.\n"
67
+ result += "Example: 'Which project should I use for this task?'\n\n"
68
+ result += "Session reminder: Track the selected project for all subsequent operations in this conversation.\n"
69
+ result += "The user can say 'switch to [project]' to change projects."
70
+
71
+ return result
72
+
73
+
74
+ @mcp.tool("create_memory_project")
75
+ async def create_memory_project(
76
+ project_name: str, project_path: str, set_default: bool = False, context: Context | None = None
77
+ ) -> str:
78
+ """Create a new Basic Memory project.
79
+
80
+ Creates a new project with the specified name and path. The project directory
81
+ will be created if it doesn't exist. Optionally sets the new project as default.
82
+
83
+ Args:
84
+ project_name: Name for the new project (must be unique)
85
+ project_path: File system path where the project will be stored
86
+ set_default: Whether to set this project as the default (optional, defaults to False)
87
+
88
+ Returns:
89
+ Confirmation message with project details
90
+
91
+ Example:
92
+ create_memory_project("my-research", "~/Documents/research")
93
+ create_memory_project("work-notes", "/home/user/work", set_default=True)
94
+ """
95
+ async with get_client() as client:
96
+ # Check if server is constrained to a specific project
97
+ constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
98
+ if constrained_project:
99
+ 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}"`'
100
+
101
+ if context: # pragma: no cover
102
+ await context.info(f"Creating project: {project_name} at {project_path}")
103
+
104
+ # Create the project request
105
+ project_request = ProjectInfoRequest(
106
+ name=project_name, path=project_path, set_default=set_default
107
+ )
108
+
109
+ # Call API to create project
110
+ response = await call_post(client, "/projects/projects", json=project_request.model_dump())
111
+ status_response = ProjectStatusResponse.model_validate(response.json())
112
+
113
+ result = f"✓ {status_response.message}\n\n"
114
+
115
+ if status_response.new_project:
116
+ result += "Project Details:\n"
117
+ result += f"• Name: {status_response.new_project.name}\n"
118
+ result += f"• Path: {status_response.new_project.path}\n"
119
+
120
+ if set_default:
121
+ result += "• Set as default project\n"
122
+
123
+ result += "\nProject is now available for use in tool calls.\n"
124
+ result += f"Use '{project_name}' as the project parameter in MCP tool calls.\n"
125
+
126
+ return result
127
+
128
+
129
+ @mcp.tool()
130
+ async def delete_project(project_name: str, context: Context | None = None) -> str:
131
+ """Delete a Basic Memory project.
132
+
133
+ Removes a project from the configuration and database. This does NOT delete
134
+ the actual files on disk - only removes the project from Basic Memory's
135
+ configuration and database records.
136
+
137
+ Args:
138
+ project_name: Name of the project to delete
139
+
140
+ Returns:
141
+ Confirmation message about project deletion
142
+
143
+ Example:
144
+ delete_project("old-project")
145
+
146
+ Warning:
147
+ This action cannot be undone. The project will need to be re-added
148
+ to access its content through Basic Memory again.
149
+ """
150
+ async with get_client() as client:
151
+ # Check if server is constrained to a specific project
152
+ constrained_project = os.environ.get("BASIC_MEMORY_MCP_PROJECT")
153
+ if constrained_project:
154
+ 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}\"`"
155
+
156
+ if context: # pragma: no cover
157
+ await context.info(f"Deleting project: {project_name}")
158
+
159
+ # Get project info before deletion to validate it exists
160
+ response = await call_get(client, "/projects/projects")
161
+ project_list = ProjectList.model_validate(response.json())
162
+
163
+ # Find the project by name (case-insensitive) or permalink - same logic as switch_project
164
+ project_permalink = generate_permalink(project_name)
165
+ target_project = None
166
+ for p in project_list.projects:
167
+ # Match by permalink (handles case-insensitive input)
168
+ if p.permalink == project_permalink:
169
+ target_project = p
170
+ break
171
+ # Also match by name comparison (case-insensitive)
172
+ if p.name.lower() == project_name.lower():
173
+ target_project = p
174
+ break
175
+
176
+ if not target_project:
177
+ available_projects = [p.name for p in project_list.projects]
178
+ raise ValueError(
179
+ f"Project '{project_name}' not found. Available projects: {', '.join(available_projects)}"
180
+ )
181
+
182
+ # Call API to delete project using URL encoding for special characters
183
+ from urllib.parse import quote
184
+
185
+ encoded_name = quote(target_project.name, safe="")
186
+ response = await call_delete(client, f"/projects/{encoded_name}")
187
+ status_response = ProjectStatusResponse.model_validate(response.json())
188
+
189
+ result = f"✓ {status_response.message}\n\n"
190
+
191
+ if status_response.old_project:
192
+ result += "Removed project details:\n"
193
+ result += f"• Name: {status_response.old_project.name}\n"
194
+ if hasattr(status_response.old_project, "path"):
195
+ result += f"• Path: {status_response.old_project.path}\n"
196
+
197
+ result += "Files remain on disk but project is no longer tracked by Basic Memory.\n"
198
+ result += "Re-add the project to access its content again.\n"
199
+
200
+ return result
@@ -0,0 +1,271 @@
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
+
17
+ from basic_memory.mcp.project_context import get_active_project
18
+ from basic_memory.mcp.server import mcp
19
+ from basic_memory.mcp.async_client import get_client
20
+ from basic_memory.mcp.tools.utils import call_get
21
+ from basic_memory.schemas.memory import memory_url_path
22
+ from basic_memory.utils import validate_project_path
23
+
24
+
25
+ def calculate_target_params(content_length):
26
+ """Calculate initial quality and size based on input file size"""
27
+ target_size = 350000 # Reduced target for more safety margin
28
+ ratio = content_length / target_size
29
+
30
+ logger.debug(
31
+ "Calculating target parameters",
32
+ content_length=content_length,
33
+ ratio=ratio,
34
+ target_size=target_size,
35
+ )
36
+
37
+ if ratio > 4:
38
+ # Very large images - start very aggressive
39
+ return 50, 600 # Lower initial quality and size
40
+ elif ratio > 2:
41
+ return 60, 800
42
+ else:
43
+ return 70, 1000
44
+
45
+
46
+ def resize_image(img, max_size):
47
+ """Resize image maintaining aspect ratio"""
48
+ original_dimensions = {"width": img.width, "height": img.height}
49
+
50
+ if img.width > max_size or img.height > max_size:
51
+ ratio = min(max_size / img.width, max_size / img.height)
52
+ new_size = (int(img.width * ratio), int(img.height * ratio))
53
+ logger.debug("Resizing image", original=original_dimensions, target=new_size, ratio=ratio)
54
+ return img.resize(new_size, PILImage.Resampling.LANCZOS)
55
+
56
+ logger.debug("No resize needed", dimensions=original_dimensions)
57
+ return img
58
+
59
+
60
+ def optimize_image(img, content_length, max_output_bytes=350000):
61
+ """Iteratively optimize image with aggressive size reduction"""
62
+ stats = {
63
+ "dimensions": {"width": img.width, "height": img.height},
64
+ "mode": img.mode,
65
+ "estimated_memory": (img.width * img.height * len(img.getbands())),
66
+ }
67
+
68
+ initial_quality, initial_size = calculate_target_params(content_length)
69
+
70
+ logger.debug(
71
+ "Starting optimization",
72
+ image_stats=stats,
73
+ content_length=content_length,
74
+ initial_quality=initial_quality,
75
+ initial_size=initial_size,
76
+ max_output_bytes=max_output_bytes,
77
+ )
78
+
79
+ quality = initial_quality
80
+ size = initial_size
81
+
82
+ # Convert to RGB if needed
83
+ if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
84
+ img = img.convert("RGB")
85
+ logger.debug("Converted to RGB mode")
86
+
87
+ iteration = 0
88
+ min_size = 300 # Absolute minimum size
89
+ min_quality = 20 # Absolute minimum quality
90
+
91
+ while True:
92
+ iteration += 1
93
+ buf = io.BytesIO()
94
+ resized = resize_image(img, size)
95
+
96
+ resized.save(
97
+ buf,
98
+ format="JPEG",
99
+ quality=quality,
100
+ optimize=True,
101
+ progressive=True,
102
+ subsampling="4:2:0",
103
+ )
104
+
105
+ output_size = buf.getbuffer().nbytes
106
+ reduction_ratio = output_size / content_length
107
+
108
+ logger.debug(
109
+ "Optimization attempt",
110
+ iteration=iteration,
111
+ quality=quality,
112
+ size=size,
113
+ output_bytes=output_size,
114
+ target_bytes=max_output_bytes,
115
+ reduction_ratio=f"{reduction_ratio:.2f}",
116
+ )
117
+
118
+ if output_size < max_output_bytes:
119
+ logger.info(
120
+ "Image optimization complete",
121
+ final_size=output_size,
122
+ quality=quality,
123
+ dimensions={"width": resized.width, "height": resized.height},
124
+ reduction_ratio=f"{reduction_ratio:.2f}",
125
+ )
126
+ return buf.getvalue()
127
+
128
+ # Very aggressive reduction for large files
129
+ if content_length > 2000000: # 2MB+ # pragma: no cover
130
+ quality = max(min_quality, quality - 20)
131
+ size = max(min_size, int(size * 0.6))
132
+ elif content_length > 1000000: # 1MB+ # pragma: no cover
133
+ quality = max(min_quality, quality - 15)
134
+ size = max(min_size, int(size * 0.7))
135
+ else:
136
+ quality = max(min_quality, quality - 10) # pragma: no cover
137
+ size = max(min_size, int(size * 0.8)) # pragma: no cover
138
+
139
+ logger.debug("Reducing parameters", new_quality=quality, new_size=size) # pragma: no cover
140
+
141
+ # If we've hit minimum values and still too big
142
+ if quality <= min_quality and size <= min_size: # pragma: no cover
143
+ logger.warning(
144
+ "Reached minimum parameters",
145
+ final_size=output_size,
146
+ over_limit_by=output_size - max_output_bytes,
147
+ )
148
+ return buf.getvalue()
149
+
150
+
151
+ @mcp.tool(description="Read a file's raw content by path or permalink")
152
+ async def read_content(
153
+ path: str, project: Optional[str] = None, context: Context | None = None
154
+ ) -> dict:
155
+ """Read a file's raw content by path or permalink.
156
+
157
+ This tool provides direct access to file content in the knowledge base,
158
+ handling different file types appropriately. Uses stateless architecture -
159
+ project parameter optional with server resolution.
160
+
161
+ Supported file types:
162
+ - Text files (markdown, code, etc.) are returned as plain text
163
+ - Images are automatically resized/optimized for display
164
+ - Other binary files are returned as base64 if below size limits
165
+
166
+ Args:
167
+ path: The path or permalink to the file. Can be:
168
+ - A regular file path (docs/example.md)
169
+ - A memory URL (memory://docs/example)
170
+ - A permalink (docs/example)
171
+ project: Project name to read from. Optional - server will resolve using hierarchy.
172
+ If unknown, use list_memory_projects() to discover available projects.
173
+ context: Optional FastMCP context for performance caching.
174
+
175
+ Returns:
176
+ A dictionary with the file content and metadata:
177
+ - For text: {"type": "text", "text": "content", "content_type": "text/markdown", "encoding": "utf-8"}
178
+ - For images: {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "base64_data"}}
179
+ - For other files: {"type": "document", "source": {"type": "base64", "media_type": "content_type", "data": "base64_data"}}
180
+ - For errors: {"type": "error", "error": "error message"}
181
+
182
+ Examples:
183
+ # Read a markdown file
184
+ result = await read_content("docs/project-specs.md")
185
+
186
+ # Read an image
187
+ image_data = await read_content("assets/diagram.png")
188
+
189
+ # Read using memory URL
190
+ content = await read_content("memory://docs/architecture")
191
+
192
+ # Read configuration file
193
+ config = await read_content("config/settings.json")
194
+
195
+ # Explicit project specification
196
+ result = await read_content("docs/project-specs.md", project="my-project")
197
+
198
+ Raises:
199
+ HTTPError: If project doesn't exist or is inaccessible
200
+ SecurityError: If path attempts path traversal
201
+ """
202
+ logger.info("Reading file", path=path, project=project)
203
+
204
+ async with get_client() as client:
205
+ active_project = await get_active_project(client, project, context)
206
+ project_url = active_project.project_url
207
+
208
+ url = memory_url_path(path)
209
+
210
+ # Validate path to prevent path traversal attacks
211
+ project_path = active_project.home
212
+ if not validate_project_path(url, project_path):
213
+ logger.warning(
214
+ "Attempted path traversal attack blocked",
215
+ path=path,
216
+ url=url,
217
+ project=active_project.name,
218
+ )
219
+ return {
220
+ "type": "error",
221
+ "error": f"Path '{path}' is not allowed - paths must stay within project boundaries",
222
+ }
223
+
224
+ response = await call_get(client, f"{project_url}/resource/{url}")
225
+ content_type = response.headers.get("content-type", "application/octet-stream")
226
+ content_length = int(response.headers.get("content-length", 0))
227
+
228
+ logger.debug("Resource metadata", content_type=content_type, size=content_length, path=path)
229
+
230
+ # Handle text or json
231
+ if content_type.startswith("text/") or content_type == "application/json":
232
+ logger.debug("Processing text resource")
233
+ return {
234
+ "type": "text",
235
+ "text": response.text,
236
+ "content_type": content_type,
237
+ "encoding": "utf-8",
238
+ }
239
+
240
+ # Handle images
241
+ elif content_type.startswith("image/"):
242
+ logger.debug("Processing image")
243
+ img = PILImage.open(io.BytesIO(response.content))
244
+ img_bytes = optimize_image(img, content_length)
245
+
246
+ return {
247
+ "type": "image",
248
+ "source": {
249
+ "type": "base64",
250
+ "media_type": "image/jpeg",
251
+ "data": base64.b64encode(img_bytes).decode("utf-8"),
252
+ },
253
+ }
254
+
255
+ # Handle other file types
256
+ else:
257
+ logger.debug(f"Processing binary resource content_type {content_type}")
258
+ if content_length > 350000: # pragma: no cover
259
+ logger.warning("Document too large for response", size=content_length)
260
+ return {
261
+ "type": "error",
262
+ "error": f"Document size {content_length} bytes exceeds maximum allowed size",
263
+ }
264
+ return {
265
+ "type": "document",
266
+ "source": {
267
+ "type": "base64",
268
+ "media_type": content_type,
269
+ "data": base64.b64encode(response.content).decode("utf-8"),
270
+ },
271
+ }