remdb 0.3.114__py3-none-any.whl → 0.3.172__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 remdb might be problematic. Click here for more details.

Files changed (83) hide show
  1. rem/agentic/agents/__init__.py +16 -0
  2. rem/agentic/agents/agent_manager.py +311 -0
  3. rem/agentic/agents/sse_simulator.py +2 -0
  4. rem/agentic/context.py +103 -5
  5. rem/agentic/context_builder.py +36 -9
  6. rem/agentic/mcp/tool_wrapper.py +161 -18
  7. rem/agentic/otel/setup.py +1 -0
  8. rem/agentic/providers/phoenix.py +371 -108
  9. rem/agentic/providers/pydantic_ai.py +172 -30
  10. rem/agentic/schema.py +8 -4
  11. rem/api/deps.py +3 -5
  12. rem/api/main.py +26 -4
  13. rem/api/mcp_router/resources.py +15 -10
  14. rem/api/mcp_router/server.py +11 -3
  15. rem/api/mcp_router/tools.py +418 -4
  16. rem/api/middleware/tracking.py +5 -5
  17. rem/api/routers/admin.py +218 -1
  18. rem/api/routers/auth.py +349 -6
  19. rem/api/routers/chat/completions.py +255 -7
  20. rem/api/routers/chat/models.py +81 -7
  21. rem/api/routers/chat/otel_utils.py +33 -0
  22. rem/api/routers/chat/sse_events.py +17 -1
  23. rem/api/routers/chat/streaming.py +126 -19
  24. rem/api/routers/feedback.py +134 -14
  25. rem/api/routers/messages.py +24 -15
  26. rem/api/routers/query.py +6 -3
  27. rem/auth/__init__.py +13 -3
  28. rem/auth/jwt.py +352 -0
  29. rem/auth/middleware.py +115 -10
  30. rem/auth/providers/__init__.py +4 -1
  31. rem/auth/providers/email.py +215 -0
  32. rem/cli/commands/README.md +42 -0
  33. rem/cli/commands/cluster.py +617 -168
  34. rem/cli/commands/configure.py +4 -7
  35. rem/cli/commands/db.py +66 -22
  36. rem/cli/commands/experiments.py +468 -76
  37. rem/cli/commands/schema.py +6 -5
  38. rem/cli/commands/session.py +336 -0
  39. rem/cli/dreaming.py +2 -2
  40. rem/cli/main.py +2 -0
  41. rem/config.py +8 -1
  42. rem/models/core/experiment.py +58 -14
  43. rem/models/entities/__init__.py +4 -0
  44. rem/models/entities/ontology.py +1 -1
  45. rem/models/entities/ontology_config.py +1 -1
  46. rem/models/entities/subscriber.py +175 -0
  47. rem/models/entities/user.py +1 -0
  48. rem/schemas/agents/core/agent-builder.yaml +235 -0
  49. rem/schemas/agents/examples/contract-analyzer.yaml +1 -1
  50. rem/schemas/agents/examples/contract-extractor.yaml +1 -1
  51. rem/schemas/agents/examples/cv-parser.yaml +1 -1
  52. rem/services/__init__.py +3 -1
  53. rem/services/content/service.py +4 -3
  54. rem/services/email/__init__.py +10 -0
  55. rem/services/email/service.py +513 -0
  56. rem/services/email/templates.py +360 -0
  57. rem/services/phoenix/client.py +59 -18
  58. rem/services/postgres/README.md +38 -0
  59. rem/services/postgres/diff_service.py +127 -6
  60. rem/services/postgres/pydantic_to_sqlalchemy.py +45 -13
  61. rem/services/postgres/repository.py +5 -4
  62. rem/services/postgres/schema_generator.py +205 -4
  63. rem/services/session/compression.py +120 -50
  64. rem/services/session/reload.py +14 -7
  65. rem/services/user_service.py +41 -9
  66. rem/settings.py +442 -23
  67. rem/sql/migrations/001_install.sql +156 -0
  68. rem/sql/migrations/002_install_models.sql +1951 -88
  69. rem/sql/migrations/004_cache_system.sql +548 -0
  70. rem/sql/migrations/005_schema_update.sql +145 -0
  71. rem/utils/README.md +45 -0
  72. rem/utils/__init__.py +18 -0
  73. rem/utils/files.py +157 -1
  74. rem/utils/schema_loader.py +139 -10
  75. rem/utils/sql_paths.py +146 -0
  76. rem/utils/vision.py +1 -1
  77. rem/workers/__init__.py +3 -1
  78. rem/workers/db_listener.py +579 -0
  79. rem/workers/unlogged_maintainer.py +463 -0
  80. {remdb-0.3.114.dist-info → remdb-0.3.172.dist-info}/METADATA +218 -180
  81. {remdb-0.3.114.dist-info → remdb-0.3.172.dist-info}/RECORD +83 -68
  82. {remdb-0.3.114.dist-info → remdb-0.3.172.dist-info}/WHEEL +0 -0
  83. {remdb-0.3.114.dist-info → remdb-0.3.172.dist-info}/entry_points.txt +0 -0
@@ -96,6 +96,35 @@ TODO:
96
96
 
97
97
  Priority: HIGH (blocks production scaling beyond 50 req/sec)
98
98
 
99
+ 4. Response Format Control (structured_output enhancement):
100
+ - Current: structured_output is bool (True=strict schema, False=free-form text)
101
+ - Missing: OpenAI JSON mode (valid JSON without strict schema enforcement)
102
+ - Missing: Completions API support (some models only support completions, not chat)
103
+
104
+ Proposed schema field values for `structured_output`:
105
+ - True (default): Strict structured output using provider's native schema support
106
+ - False: Free-form text response (properties converted to prompt guidance)
107
+ - "json": JSON mode - ensures valid JSON but no schema enforcement
108
+ (OpenAI: response_format={"type": "json_object"})
109
+ - "text": Explicit free-form text (alias for False)
110
+
111
+ Implementation:
112
+ a) Update AgentSchemaMetadata.structured_output type:
113
+ structured_output: bool | Literal["json", "text"] = True
114
+ b) In create_agent(), handle each mode:
115
+ - True: Use output_type with Pydantic model (current behavior)
116
+ - False/"text": Convert properties to prompt guidance (current behavior)
117
+ - "json": Use provider's JSON mode without strict schema
118
+ c) Provider-specific JSON mode:
119
+ - OpenAI: model_settings={"response_format": {"type": "json_object"}}
120
+ - Anthropic: Not supported natively, use prompt guidance
121
+ - Others: Fallback to prompt guidance with JSON instruction
122
+
123
+ Related: Some providers (Cerebras) have completions-only models where
124
+ structured output isn't available. Consider model capability detection.
125
+
126
+ Priority: MEDIUM (enables more flexible output control)
127
+
99
128
  Example Agent Schema:
100
129
  {
101
130
  "type": "object",
@@ -550,10 +579,18 @@ async def create_agent(
550
579
  # Extract schema fields using typed helpers
551
580
  from ..schema import get_system_prompt, get_metadata
552
581
 
582
+ # Track whether mcp_servers was explicitly configured (even if empty)
583
+ mcp_servers_explicitly_set = False
584
+
553
585
  if agent_schema:
554
586
  system_prompt = get_system_prompt(agent_schema)
555
587
  metadata = get_metadata(agent_schema)
556
- mcp_server_configs = [s.model_dump() for s in metadata.mcp_servers] if hasattr(metadata, 'mcp_servers') else []
588
+ # Check if mcp_servers was explicitly set (could be empty list to disable)
589
+ if hasattr(metadata, 'mcp_servers') and metadata.mcp_servers is not None:
590
+ mcp_server_configs = [s.model_dump() for s in metadata.mcp_servers]
591
+ mcp_servers_explicitly_set = True
592
+ else:
593
+ mcp_server_configs = []
557
594
  resource_configs = metadata.resources if hasattr(metadata, 'resources') else []
558
595
 
559
596
  if metadata.system_prompt:
@@ -564,15 +601,49 @@ async def create_agent(
564
601
  mcp_server_configs = []
565
602
  resource_configs = []
566
603
 
604
+ # Auto-detect local MCP server if not explicitly configured
605
+ # This makes mcp_servers config optional - agents get tools automatically
606
+ # But if mcp_servers: [] is explicitly set, respect that (no auto-detection)
607
+ if not mcp_server_configs and not mcp_servers_explicitly_set:
608
+ import importlib
609
+ import os
610
+ import sys
611
+
612
+ # Ensure current working directory is in sys.path for local imports
613
+ cwd = os.getcwd()
614
+ if cwd not in sys.path:
615
+ sys.path.insert(0, cwd)
616
+
617
+ # Try common local MCP server module paths first
618
+ auto_detect_modules = [
619
+ "tools.mcp_server", # Convention: tools/mcp_server.py
620
+ "mcp_server", # Alternative: mcp_server.py in root
621
+ ]
622
+ for module_path in auto_detect_modules:
623
+ try:
624
+ mcp_module = importlib.import_module(module_path)
625
+ if hasattr(mcp_module, "mcp"):
626
+ logger.info(f"Auto-detected local MCP server: {module_path}")
627
+ mcp_server_configs = [{"type": "local", "module": module_path, "id": "auto-detected"}]
628
+ break
629
+ except ImportError:
630
+ continue
631
+
632
+ # Fall back to REM's default MCP server if no local server found
633
+ if not mcp_server_configs:
634
+ logger.debug("No local MCP server found, using REM default")
635
+ mcp_server_configs = [{"type": "local", "module": "rem.mcp_server", "id": "rem"}]
636
+
567
637
  # Extract temperature and max_iterations from schema metadata (with fallback to settings defaults)
568
638
  if metadata:
569
639
  temperature = metadata.override_temperature if metadata.override_temperature is not None else settings.llm.default_temperature
570
640
  max_iterations = metadata.override_max_iterations if metadata.override_max_iterations is not None else settings.llm.default_max_iterations
571
- use_structured_output = metadata.structured_output
641
+ # Use schema-level structured_output if set, otherwise fall back to global setting
642
+ use_structured_output = metadata.structured_output if metadata.structured_output is not None else settings.llm.default_structured_output
572
643
  else:
573
644
  temperature = settings.llm.default_temperature
574
645
  max_iterations = settings.llm.default_max_iterations
575
- use_structured_output = True
646
+ use_structured_output = settings.llm.default_structured_output
576
647
 
577
648
  # Build list of tools - start with built-in tools
578
649
  tools = _get_builtin_tools()
@@ -591,43 +662,114 @@ async def create_agent(
591
662
 
592
663
  set_agent_resource_attributes(agent_schema=agent_schema)
593
664
 
665
+ # Extract schema metadata for search_rem tool description suffix
666
+ # This allows entity schemas to add context-specific notes to the search_rem tool
667
+ search_rem_suffix = None
668
+ if metadata:
669
+ # Check for default_search_table in metadata (set by entity schemas)
670
+ extra = agent_schema.get("json_schema_extra", {}) if agent_schema else {}
671
+ default_table = extra.get("default_search_table")
672
+ has_embeddings = extra.get("has_embeddings", False)
673
+
674
+ if default_table:
675
+ # Build description suffix for search_rem
676
+ search_rem_suffix = f"\n\nFor this schema, use `search_rem` to query `{default_table}`. "
677
+ if has_embeddings:
678
+ search_rem_suffix += f"SEARCH works well on {default_table} (has embeddings). "
679
+ search_rem_suffix += f"Example: `SEARCH \"your query\" FROM {default_table} LIMIT 10`"
680
+
594
681
  # Add tools from MCP server (in-process, no subprocess)
595
- if mcp_server_configs:
596
- for server_config in mcp_server_configs:
597
- server_type = server_config.get("type")
598
- server_id = server_config.get("id", "mcp-server")
682
+ # Track loaded MCP servers for resource resolution
683
+ loaded_mcp_server = None
599
684
 
600
- if server_type == "local":
601
- # Import MCP server directly (in-process)
602
- module_path = server_config.get("module", "rem.mcp_server")
685
+ for server_config in mcp_server_configs:
686
+ server_type = server_config.get("type")
687
+ server_id = server_config.get("id", "mcp-server")
603
688
 
604
- try:
605
- # Dynamic import of MCP server module
606
- import importlib
607
- mcp_module = importlib.import_module(module_path)
608
- mcp_server = mcp_module.mcp
689
+ if server_type == "local":
690
+ # Import MCP server directly (in-process)
691
+ module_path = server_config.get("module", "rem.mcp_server")
609
692
 
610
- # Extract tools from MCP server (get_tools is async)
611
- from ..mcp.tool_wrapper import create_mcp_tool_wrapper
693
+ try:
694
+ # Dynamic import of MCP server module
695
+ import importlib
696
+ mcp_module = importlib.import_module(module_path)
697
+ mcp_server = mcp_module.mcp
612
698
 
613
- # Await async get_tools() call
614
- mcp_tools_dict = await mcp_server.get_tools()
699
+ # Store the loaded server for resource resolution
700
+ loaded_mcp_server = mcp_server
615
701
 
616
- for tool_name, tool_func in mcp_tools_dict.items():
617
- wrapped_tool = create_mcp_tool_wrapper(tool_name, tool_func, user_id=context.user_id if context else None)
618
- tools.append(wrapped_tool)
619
- logger.debug(f"Loaded MCP tool: {tool_name}")
702
+ # Extract tools from MCP server (get_tools is async)
703
+ from ..mcp.tool_wrapper import create_mcp_tool_wrapper
620
704
 
621
- logger.info(f"Loaded {len(mcp_tools_dict)} tools from MCP server: {server_id} (in-process)")
705
+ # Await async get_tools() call
706
+ mcp_tools_dict = await mcp_server.get_tools()
622
707
 
623
- except Exception as e:
624
- logger.error(f"Failed to load MCP server {server_id}: {e}", exc_info=True)
625
- else:
626
- logger.warning(f"Unsupported MCP server type: {server_type}")
708
+ for tool_name, tool_func in mcp_tools_dict.items():
709
+ # Add description suffix to search_rem tool if schema specifies a default table
710
+ tool_suffix = search_rem_suffix if tool_name == "search_rem" else None
711
+
712
+ wrapped_tool = create_mcp_tool_wrapper(
713
+ tool_name,
714
+ tool_func,
715
+ user_id=context.user_id if context else None,
716
+ description_suffix=tool_suffix,
717
+ )
718
+ tools.append(wrapped_tool)
719
+ logger.debug(f"Loaded MCP tool: {tool_name}" + (" (with schema suffix)" if tool_suffix else ""))
627
720
 
721
+ logger.info(f"Loaded {len(mcp_tools_dict)} tools from MCP server: {server_id} (in-process)")
722
+
723
+ except Exception as e:
724
+ logger.error(f"Failed to load MCP server {server_id}: {e}", exc_info=True)
725
+ else:
726
+ logger.warning(f"Unsupported MCP server type: {server_type}")
727
+
728
+ # Convert resources to tools (MCP convenience syntax)
729
+ # Resources declared in agent YAML become callable tools - eliminates
730
+ # the artificial MCP distinction between tools and resources
731
+ #
732
+ # Supports both concrete and template URIs:
733
+ # - Concrete: "rem://schemas" -> no-param tool
734
+ # - Template: "patient-profile://field/{field_key}" -> tool with field_key param
735
+ from ..mcp.tool_wrapper import create_resource_tool
736
+
737
+ # Collect all resource URIs from both resources section AND tools section
738
+ resource_uris = []
739
+
740
+ # From resources section (legacy format)
628
741
  if resource_configs:
629
- # TODO: Convert resources to tools (MCP convenience syntax)
630
- pass
742
+ for resource_config in resource_configs:
743
+ if hasattr(resource_config, 'uri'):
744
+ uri = resource_config.uri
745
+ usage = resource_config.description or ""
746
+ else:
747
+ uri = resource_config.get("uri", "")
748
+ usage = resource_config.get("description", "")
749
+ if uri:
750
+ resource_uris.append((uri, usage))
751
+
752
+ # From tools section - detect URIs (anything with ://)
753
+ # This allows unified syntax: resources as tools
754
+ tool_configs = metadata.tools if metadata and hasattr(metadata, 'tools') else []
755
+ for tool_config in tool_configs:
756
+ if hasattr(tool_config, 'name'):
757
+ tool_name = tool_config.name
758
+ tool_desc = tool_config.description or ""
759
+ else:
760
+ tool_name = tool_config.get("name", "")
761
+ tool_desc = tool_config.get("description", "")
762
+
763
+ # Auto-detect resource URIs (anything with :// scheme)
764
+ if "://" in tool_name:
765
+ resource_uris.append((tool_name, tool_desc))
766
+
767
+ # Create tools from collected resource URIs
768
+ # Pass the loaded MCP server so resources can be resolved from it
769
+ for uri, usage in resource_uris:
770
+ resource_tool = create_resource_tool(uri, usage, mcp_server=loaded_mcp_server)
771
+ tools.append(resource_tool)
772
+ logger.debug(f"Loaded resource as tool: {uri}")
631
773
 
632
774
  # Create dynamic result_type from schema if not provided
633
775
  # Note: use_structured_output is set earlier from metadata.structured_output
rem/agentic/schema.py CHANGED
@@ -154,8 +154,10 @@ class MCPServerConfig(BaseModel):
154
154
  )
155
155
 
156
156
  id: str = Field(
157
+ default="mcp-server",
157
158
  description=(
158
159
  "Server identifier for logging and debugging. "
160
+ "Defaults to 'mcp-server' if not specified. "
159
161
  "Example: 'rem-local'"
160
162
  )
161
163
  )
@@ -213,12 +215,13 @@ class AgentSchemaMetadata(BaseModel):
213
215
  )
214
216
 
215
217
  # Structured output toggle
216
- structured_output: bool = Field(
217
- default=True,
218
+ structured_output: bool | None = Field(
219
+ default=None,
218
220
  description=(
219
221
  "Whether to enforce structured JSON output. "
220
222
  "When False, the agent produces free-form text and schema properties "
221
- "are converted to prompt guidance instead. Default: True (JSON output)."
223
+ "are converted to prompt guidance instead. "
224
+ "Default: None (uses LLM__DEFAULT_STRUCTURED_OUTPUT setting, which defaults to False)."
222
225
  ),
223
226
  )
224
227
 
@@ -228,7 +231,8 @@ class AgentSchemaMetadata(BaseModel):
228
231
  description=(
229
232
  "MCP server configurations for dynamic tool loading. "
230
233
  "Servers are loaded in-process at agent creation time. "
231
- "All tools from configured servers become available to the agent."
234
+ "All tools from configured servers become available to the agent. "
235
+ "If not specified, defaults to rem.mcp_server (REM's built-in tools)."
232
236
  ),
233
237
  )
234
238
 
rem/api/deps.py CHANGED
@@ -147,7 +147,6 @@ def is_admin(user: dict | None) -> bool:
147
147
  async def get_user_filter(
148
148
  request: Request,
149
149
  x_user_id: str | None = None,
150
- x_tenant_id: str = "default",
151
150
  ) -> dict[str, Any]:
152
151
  """
153
152
  Get user-scoped filter dict for database queries.
@@ -158,7 +157,6 @@ async def get_user_filter(
158
157
  Args:
159
158
  request: FastAPI request
160
159
  x_user_id: Optional user_id filter (admin only for cross-user)
161
- x_tenant_id: Tenant ID for multi-tenancy
162
160
 
163
161
  Returns:
164
162
  Filter dict with appropriate user_id constraint
@@ -169,7 +167,7 @@ async def get_user_filter(
169
167
  return await repo.find(filters)
170
168
  """
171
169
  user = get_current_user(request)
172
- filters: dict[str, Any] = {"tenant_id": x_tenant_id}
170
+ filters: dict[str, Any] = {}
173
171
 
174
172
  if is_admin(user):
175
173
  # Admin can filter by any user or see all
@@ -185,8 +183,8 @@ async def get_user_filter(
185
183
  f"User {user.get('email')} attempted to filter by user_id={x_user_id}"
186
184
  )
187
185
  else:
188
- # Anonymous: could use anonymous tracking ID or restrict access
189
- # For now, anonymous can't access user-scoped data
186
+ # Anonymous: use anonymous tracking ID
187
+ # Note: user_id should come from JWT, not from parameters
190
188
  anon_id = getattr(request.state, "anon_id", None)
191
189
  if anon_id:
192
190
  filters["user_id"] = f"anon:{anon_id}"
rem/api/main.py CHANGED
@@ -149,19 +149,38 @@ class RequestLoggingMiddleware(BaseHTTPMiddleware):
149
149
  client_host = request.client.host if request.client else "unknown"
150
150
  user_agent = request.headers.get('user-agent', 'unknown')[:100]
151
151
 
152
+ # Extract auth info for logging (first 8 chars of token for debugging)
153
+ auth_header = request.headers.get('authorization', '')
154
+ auth_preview = ""
155
+ if auth_header.startswith('Bearer '):
156
+ token = auth_header[7:]
157
+ auth_preview = f"Bearer {token[:8]}..." if len(token) > 8 else f"Bearer {token}"
158
+
152
159
  # Process request
153
160
  response = await call_next(request)
154
161
 
162
+ # Extract user info set by auth middleware (after processing)
163
+ user = getattr(request.state, "user", None)
164
+ user_id = user.get("id", "none")[:12] if user else "anon"
165
+ user_email = user.get("email", "") if user else ""
166
+
155
167
  # Determine log level based on path AND response status
156
168
  duration_ms = (time.time() - start_time) * 1000
157
169
  use_debug = self._should_log_at_debug(path, response.status_code)
158
170
  log_fn = logger.debug if use_debug else logger.info
159
171
 
160
- # Log request and response together
172
+ # Build user info string
173
+ user_info = f"user={user_id}"
174
+ if user_email:
175
+ user_info += f" ({user_email})"
176
+ if auth_preview:
177
+ user_info += f" | auth={auth_preview}"
178
+
179
+ # Log request and response together with auth info
161
180
  log_fn(
162
181
  f"→ REQUEST: {request.method} {path} | "
163
182
  f"Client: {client_host} | "
164
- f"User-Agent: {user_agent}"
183
+ f"{user_info}"
165
184
  )
166
185
  log_fn(
167
186
  f"← RESPONSE: {request.method} {path} | "
@@ -304,7 +323,7 @@ def create_app() -> FastAPI:
304
323
  app.add_middleware(
305
324
  AuthMiddleware,
306
325
  protected_paths=["/api/v1"],
307
- excluded_paths=["/api/auth", "/api/dev", "/api/v1/mcp/auth"],
326
+ excluded_paths=["/api/auth", "/api/dev", "/api/v1/mcp/auth", "/api/v1/slack"],
308
327
  # Allow anonymous when auth is disabled, otherwise use setting
309
328
  allow_anonymous=(not settings.auth.enabled) or settings.auth.allow_anonymous,
310
329
  # MCP requires auth only when auth is fully enabled
@@ -376,10 +395,13 @@ def create_app() -> FastAPI:
376
395
 
377
396
  app.include_router(chat_router)
378
397
  app.include_router(models_router)
398
+ # shared_sessions_router MUST be before messages_router
399
+ # because messages_router has /sessions/{session_id} which would match
400
+ # before the more specific /sessions/shared-with-me routes
401
+ app.include_router(shared_sessions_router)
379
402
  app.include_router(messages_router)
380
403
  app.include_router(feedback_router)
381
404
  app.include_router(admin_router)
382
- app.include_router(shared_sessions_router)
383
405
  app.include_router(query_router)
384
406
 
385
407
  # Register auth router (if enabled)
@@ -512,9 +512,10 @@ async def load_resource(uri: str) -> dict | str:
512
512
  Raises:
513
513
  ValueError: If URI is invalid or resource not found
514
514
  """
515
- # Create temporary MCP instance with resources
515
+ import inspect
516
516
  from fastmcp import FastMCP
517
517
 
518
+ # Create temporary MCP instance with resources
518
519
  mcp = FastMCP(name="temp")
519
520
 
520
521
  # Register all resources
@@ -523,14 +524,18 @@ async def load_resource(uri: str) -> dict | str:
523
524
  register_file_resources(mcp)
524
525
  register_status_resources(mcp)
525
526
 
526
- # Get resource handlers from MCP internal registry
527
- # FastMCP stores resources in a dict by URI
528
- if hasattr(mcp, "_resources"):
529
- if uri in mcp._resources:
530
- handler = mcp._resources[uri]
531
- if callable(handler):
532
- result = handler()
533
- return result if result else {"error": "Resource returned None"}
527
+ # Get resources using FastMCP's async get_resources() method
528
+ resources = await mcp.get_resources()
529
+
530
+ if uri in resources:
531
+ resource = resources[uri]
532
+ # Call the underlying function
533
+ result = resource.fn()
534
+ # Handle async functions
535
+ if inspect.iscoroutine(result):
536
+ result = await result
537
+ return result if result else {"error": "Resource returned None"}
534
538
 
535
539
  # If not found, raise error
536
- raise ValueError(f"Resource not found: {uri}. Available resources: {list(mcp._resources.keys()) if hasattr(mcp, '_resources') else 'unknown'}")
540
+ available = list(resources.keys())
541
+ raise ValueError(f"Resource not found: {uri}. Available resources: {available}")
@@ -127,10 +127,12 @@ def create_mcp_server(is_local: bool = False) -> FastMCP:
127
127
  "AVAILABLE TOOLS\n"
128
128
  "═══════════════════════════════════════════════════════════════════════════\n"
129
129
  "\n"
130
- "• rem_query - Execute REM queries (LOOKUP, FUZZY, SEARCH, SQL, TRAVERSE)\n"
131
- "• ask_rem - Natural language to REM query conversion\n"
130
+ "• search_rem - Execute REM queries (LOOKUP, FUZZY, SEARCH, SQL, TRAVERSE)\n"
131
+ "• ask_rem_agent - Natural language to REM query conversion\n"
132
132
  " - plan_mode=True: Hints agent to use TRAVERSE with depth=0 for edge analysis\n"
133
- "• parse_and_ingest_file - Ingest files from local paths (local server only), s3://, or https://\n"
133
+ "• ingest_into_rem - Ingest files from local paths (local server only), s3://, or https://\n"
134
+ "• list_schema - List all database schemas (tables) with row counts\n"
135
+ "• get_schema - Get detailed schema for a specific table (columns, types, indexes)\n"
134
136
  "\n"
135
137
  "═══════════════════════════════════════════════════════════════════════════\n"
136
138
  "AVAILABLE RESOURCES (Read-Only)\n"
@@ -175,9 +177,12 @@ def create_mcp_server(is_local: bool = False) -> FastMCP:
175
177
  # Register REM tools
176
178
  from .tools import (
177
179
  ask_rem_agent,
180
+ get_schema,
178
181
  ingest_into_rem,
182
+ list_schema,
179
183
  read_resource,
180
184
  register_metadata,
185
+ save_agent,
181
186
  search_rem,
182
187
  )
183
188
 
@@ -185,6 +190,9 @@ def create_mcp_server(is_local: bool = False) -> FastMCP:
185
190
  mcp.tool()(ask_rem_agent)
186
191
  mcp.tool()(read_resource)
187
192
  mcp.tool()(register_metadata)
193
+ mcp.tool()(list_schema)
194
+ mcp.tool()(get_schema)
195
+ mcp.tool()(save_agent)
188
196
 
189
197
  # File ingestion tool (with local path support for local servers)
190
198
  # Wrap to inject is_local parameter