remdb 0.3.163__py3-none-any.whl → 0.3.200__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 (48) hide show
  1. rem/agentic/agents/agent_manager.py +2 -1
  2. rem/agentic/context.py +101 -0
  3. rem/agentic/context_builder.py +30 -8
  4. rem/agentic/mcp/tool_wrapper.py +43 -14
  5. rem/agentic/providers/pydantic_ai.py +76 -34
  6. rem/agentic/schema.py +4 -3
  7. rem/agentic/tools/rem_tools.py +11 -0
  8. rem/api/main.py +1 -1
  9. rem/api/mcp_router/resources.py +75 -14
  10. rem/api/mcp_router/server.py +31 -24
  11. rem/api/mcp_router/tools.py +476 -155
  12. rem/api/routers/auth.py +11 -6
  13. rem/api/routers/chat/completions.py +52 -10
  14. rem/api/routers/chat/sse_events.py +2 -2
  15. rem/api/routers/chat/streaming.py +162 -19
  16. rem/api/routers/messages.py +96 -23
  17. rem/auth/middleware.py +59 -42
  18. rem/cli/README.md +62 -0
  19. rem/cli/commands/ask.py +1 -1
  20. rem/cli/commands/db.py +148 -70
  21. rem/cli/commands/process.py +171 -43
  22. rem/models/entities/ontology.py +93 -101
  23. rem/schemas/agents/core/agent-builder.yaml +143 -42
  24. rem/services/content/service.py +18 -5
  25. rem/services/email/service.py +17 -6
  26. rem/services/embeddings/worker.py +26 -12
  27. rem/services/postgres/__init__.py +28 -3
  28. rem/services/postgres/diff_service.py +57 -5
  29. rem/services/postgres/programmable_diff_service.py +635 -0
  30. rem/services/postgres/pydantic_to_sqlalchemy.py +2 -2
  31. rem/services/postgres/register_type.py +12 -11
  32. rem/services/postgres/repository.py +32 -21
  33. rem/services/postgres/schema_generator.py +5 -5
  34. rem/services/postgres/sql_builder.py +6 -5
  35. rem/services/session/__init__.py +7 -1
  36. rem/services/session/pydantic_messages.py +210 -0
  37. rem/services/user_service.py +12 -9
  38. rem/settings.py +7 -1
  39. rem/sql/background_indexes.sql +5 -0
  40. rem/sql/migrations/001_install.sql +148 -11
  41. rem/sql/migrations/002_install_models.sql +162 -132
  42. rem/sql/migrations/004_cache_system.sql +7 -275
  43. rem/utils/model_helpers.py +101 -0
  44. rem/utils/schema_loader.py +51 -13
  45. {remdb-0.3.163.dist-info → remdb-0.3.200.dist-info}/METADATA +1 -1
  46. {remdb-0.3.163.dist-info → remdb-0.3.200.dist-info}/RECORD +48 -46
  47. {remdb-0.3.163.dist-info → remdb-0.3.200.dist-info}/WHEEL +0 -0
  48. {remdb-0.3.163.dist-info → remdb-0.3.200.dist-info}/entry_points.txt +0 -0
@@ -128,8 +128,9 @@ async def save_agent(
128
128
  )
129
129
 
130
130
  # Create Schema entity (user-scoped)
131
+ # Note: tenant_id defaults to "default" for anonymous users
131
132
  schema_entity = Schema(
132
- tenant_id=user_id,
133
+ tenant_id=user_id or "default",
133
134
  user_id=user_id,
134
135
  name=name,
135
136
  spec=spec,
rem/agentic/context.py CHANGED
@@ -22,14 +22,81 @@ Key Design Pattern:
22
22
  - Enables session tracking across API, CLI, and test execution
23
23
  - Supports header-based configuration override (model, schema URI)
24
24
  - Clean separation: context (who/what) vs agent (how)
25
+
26
+ Multi-Agent Context Propagation:
27
+ - ContextVar (_current_agent_context) threads context through nested agent calls
28
+ - Parent context is automatically available to child agents via get_current_context()
29
+ - Use agent_context_scope() context manager for scoped context setting
30
+ - Child agents inherit user_id, tenant_id, session_id, is_eval from parent
25
31
  """
26
32
 
33
+ from contextlib import contextmanager
34
+ from contextvars import ContextVar
35
+ from typing import Generator
36
+
27
37
  from loguru import logger
28
38
  from pydantic import BaseModel, Field
29
39
 
30
40
  from ..settings import settings
31
41
 
32
42
 
43
+ # Thread-local context for current agent execution
44
+ # This enables context propagation through nested agent calls (multi-agent)
45
+ _current_agent_context: ContextVar["AgentContext | None"] = ContextVar(
46
+ "current_agent_context", default=None
47
+ )
48
+
49
+
50
+ def get_current_context() -> "AgentContext | None":
51
+ """
52
+ Get the current agent context from context var.
53
+
54
+ Used by MCP tools (like ask_agent) to inherit context from parent agent.
55
+ Returns None if no context is set (e.g., direct CLI invocation without context).
56
+
57
+ Example:
58
+ # In an MCP tool
59
+ parent_context = get_current_context()
60
+ if parent_context:
61
+ # Inherit user_id, session_id, etc. from parent
62
+ child_context = parent_context.child_context(agent_schema_uri="child-agent")
63
+ """
64
+ return _current_agent_context.get()
65
+
66
+
67
+ def set_current_context(ctx: "AgentContext | None") -> None:
68
+ """
69
+ Set the current agent context.
70
+
71
+ Called by streaming layer before agent execution.
72
+ Should be cleared (set to None) after execution completes.
73
+ """
74
+ _current_agent_context.set(ctx)
75
+
76
+
77
+ @contextmanager
78
+ def agent_context_scope(ctx: "AgentContext") -> Generator["AgentContext", None, None]:
79
+ """
80
+ Context manager for scoped context setting.
81
+
82
+ Automatically restores previous context when exiting scope.
83
+ Safe for nested agent calls - each level preserves its parent's context.
84
+
85
+ Example:
86
+ context = AgentContext(user_id="user-123")
87
+ with agent_context_scope(context):
88
+ # Context is available via get_current_context()
89
+ result = await agent.run(...)
90
+ # Previous context (or None) is restored
91
+ """
92
+ previous = _current_agent_context.get()
93
+ _current_agent_context.set(ctx)
94
+ try:
95
+ yield ctx
96
+ finally:
97
+ _current_agent_context.set(previous)
98
+
99
+
33
100
  class AgentContext(BaseModel):
34
101
  """
35
102
  Session and configuration context for agent execution.
@@ -85,6 +152,40 @@ class AgentContext(BaseModel):
85
152
 
86
153
  model_config = {"populate_by_name": True}
87
154
 
155
+ def child_context(
156
+ self,
157
+ agent_schema_uri: str | None = None,
158
+ model_override: str | None = None,
159
+ ) -> "AgentContext":
160
+ """
161
+ Create a child context for nested agent calls.
162
+
163
+ Inherits user_id, tenant_id, session_id, is_eval from parent.
164
+ Allows overriding agent_schema_uri and default_model for the child.
165
+
166
+ Args:
167
+ agent_schema_uri: Agent schema for the child agent (required for lineage)
168
+ model_override: Optional model override for child agent
169
+
170
+ Returns:
171
+ New AgentContext for the child agent
172
+
173
+ Example:
174
+ parent_context = get_current_context()
175
+ child_context = parent_context.child_context(
176
+ agent_schema_uri="sentiment-analyzer"
177
+ )
178
+ agent = await create_agent(context=child_context)
179
+ """
180
+ return AgentContext(
181
+ user_id=self.user_id,
182
+ tenant_id=self.tenant_id,
183
+ session_id=self.session_id,
184
+ default_model=model_override or self.default_model,
185
+ agent_schema_uri=agent_schema_uri or self.agent_schema_uri,
186
+ is_eval=self.is_eval,
187
+ )
188
+
88
189
  @staticmethod
89
190
  def get_user_id_or_default(
90
191
  user_id: str | None,
@@ -12,7 +12,7 @@ User Context (on-demand by default):
12
12
  - System message includes REM LOOKUP hint for user profile
13
13
  - Agent decides whether to load profile based on query
14
14
  - More efficient for queries that don't need personalization
15
- - Example: "User ID: sarah@example.com. To load user profile: Use REM LOOKUP users/sarah@example.com"
15
+ - Example: "User: sarah@example.com. To load user profile: Use REM LOOKUP \"sarah@example.com\""
16
16
 
17
17
  User Context (auto-inject when enabled):
18
18
  - Set CHAT__AUTO_INJECT_USER_CONTEXT=true
@@ -40,7 +40,7 @@ Usage (on-demand, default):
40
40
 
41
41
  # Messages list structure (on-demand):
42
42
  # [
43
- # {"role": "system", "content": "Today's date: 2025-11-22\nUser ID: sarah@example.com\nTo load user profile: Use REM LOOKUP users/sarah@example.com\nSession ID: sess-123\nTo load session history: Use REM LOOKUP messages?session_id=sess-123"},
43
+ # {"role": "system", "content": "Today's date: 2025-11-22\nUser: sarah@example.com\nTo load user profile: Use REM LOOKUP \"sarah@example.com\"\nSession ID: sess-123\nTo load session history: Use REM LOOKUP messages?session_id=sess-123"},
44
44
  # {"role": "user", "content": "What's next for the API migration?"}
45
45
  # ]
46
46
 
@@ -115,7 +115,7 @@ class ContextBuilder:
115
115
  - Agent can retrieve full content on-demand using REM LOOKUP
116
116
 
117
117
  User Context (on-demand by default):
118
- - System message includes REM LOOKUP hint: "User ID: {user_id}. To load user profile: Use REM LOOKUP users/{user_id}"
118
+ - System message includes REM LOOKUP hint: "User: {email}. To load user profile: Use REM LOOKUP \"{email}\""
119
119
  - Agent decides whether to load profile based on query
120
120
 
121
121
  User Context (auto-inject when enabled):
@@ -137,7 +137,7 @@ class ContextBuilder:
137
137
 
138
138
  # messages structure:
139
139
  # [
140
- # {"role": "system", "content": "Today's date: 2025-11-22\nUser ID: sarah@example.com\nTo load user profile: Use REM LOOKUP users/sarah@example.com"},
140
+ # {"role": "system", "content": "Today's date: 2025-11-22\nUser: sarah@example.com\nTo load user profile: Use REM LOOKUP \"sarah@example.com\""},
141
141
  # {"role": "user", "content": "Previous message"},
142
142
  # {"role": "assistant", "content": "Start of long response... [REM LOOKUP session-123-msg-1] ...end"},
143
143
  # {"role": "user", "content": "New message"}
@@ -191,8 +191,16 @@ class ContextBuilder:
191
191
  context_hint += "\n\nNo user context available (anonymous or new user)."
192
192
  elif context.user_id:
193
193
  # On-demand: Provide hint to use REM LOOKUP
194
- context_hint += f"\n\nUser ID: {context.user_id}"
195
- context_hint += f"\nTo load user profile: Use REM LOOKUP users/{context.user_id}"
194
+ # user_id is UUID5 hash of email - load user to get email for display and LOOKUP
195
+ user_repo = Repository(User, "users", db=db)
196
+ user = await user_repo.get_by_id(context.user_id, context.tenant_id)
197
+ if user and user.email:
198
+ # Show email (more useful than UUID) and LOOKUP hint
199
+ context_hint += f"\n\nUser: {user.email}"
200
+ context_hint += f"\nTo load user profile: Use REM LOOKUP \"{user.email}\""
201
+ else:
202
+ context_hint += f"\n\nUser ID: {context.user_id}"
203
+ context_hint += "\nUser profile not available."
196
204
 
197
205
  # Add system context hint
198
206
  messages.append(ContextMessage(role="system", content=context_hint))
@@ -209,11 +217,21 @@ class ContextBuilder:
209
217
  )
210
218
 
211
219
  # Convert to ContextMessage format
220
+ # For tool messages, wrap content with clear markers so the agent
221
+ # can see previous tool results when the prompt is concatenated
212
222
  for msg_dict in session_history:
223
+ role = msg_dict["role"]
224
+ content = msg_dict["content"]
225
+
226
+ if role == "tool":
227
+ # Wrap tool results with clear markers for visibility
228
+ tool_name = msg_dict.get("tool_name", "unknown")
229
+ content = f"[TOOL RESULT: {tool_name}]\n{content}\n[/TOOL RESULT]"
230
+
213
231
  messages.append(
214
232
  ContextMessage(
215
- role=msg_dict["role"],
216
- content=msg_dict["content"],
233
+ role=role,
234
+ content=content,
217
235
  )
218
236
  )
219
237
 
@@ -239,6 +257,9 @@ class ContextBuilder:
239
257
  """
240
258
  Load user profile from database and format as context.
241
259
 
260
+ user_id is always a UUID5 hash of email (bijection).
261
+ Looks up user by their id field in the database.
262
+
242
263
  Returns formatted string with:
243
264
  - User summary (generated by dreaming worker)
244
265
  - Current projects
@@ -252,6 +273,7 @@ class ContextBuilder:
252
273
 
253
274
  try:
254
275
  user_repo = Repository(User, "users", db=db)
276
+ # user_id is UUID5 hash of email - look up by database id
255
277
  user = await user_repo.get_by_id(user_id, tenant_id)
256
278
 
257
279
  if not user:
@@ -149,12 +149,23 @@ def create_resource_tool(uri: str, usage: str = "", mcp_server: Any = None) -> T
149
149
  parts = re.sub(r'_+', '_', parts).strip('_') # Clean up multiple underscores
150
150
  func_name = f"get_{parts}"
151
151
 
152
+ # For parameterized URIs, append _by_{params} to avoid naming conflicts
153
+ # e.g., rem://agents/{name} -> get_rem_agents_by_name (distinct from get_rem_agents)
154
+ if template_vars:
155
+ param_suffix = "_by_" + "_".join(template_vars)
156
+ func_name = f"{func_name}{param_suffix}"
157
+
152
158
  # Build description including parameter info
153
159
  description = usage or f"Fetch {uri} resource"
154
160
  if template_vars:
155
161
  param_desc = ", ".join(template_vars)
156
162
  description = f"{description}\n\nParameters: {param_desc}"
157
163
 
164
+ # Capture mcp_server reference at tool creation time (for closure)
165
+ # This ensures the correct server is used even if called later
166
+ _captured_mcp_server = mcp_server
167
+ _captured_uri = uri # Also capture URI for consistent logging
168
+
158
169
  if template_vars:
159
170
  # Template URI -> create parameterized tool
160
171
  async def wrapper(**kwargs: Any) -> str:
@@ -162,13 +173,17 @@ def create_resource_tool(uri: str, usage: str = "", mcp_server: Any = None) -> T
162
173
  import asyncio
163
174
  import inspect
164
175
 
176
+ logger.debug(f"Resource tool invoked: uri={_captured_uri}, kwargs={kwargs}, mcp_server={'set' if _captured_mcp_server else 'None'}")
177
+
165
178
  # Try to resolve from MCP server's resource templates first
166
- if mcp_server is not None:
179
+ if _captured_mcp_server is not None:
167
180
  try:
168
181
  # Get resource templates from MCP server
169
- templates = await mcp_server.get_resource_templates()
170
- if uri in templates:
171
- template = templates[uri]
182
+ templates = await _captured_mcp_server.get_resource_templates()
183
+ logger.debug(f"MCP server templates: {list(templates.keys())}")
184
+ if _captured_uri in templates:
185
+ template = templates[_captured_uri]
186
+ logger.debug(f"Found template for {_captured_uri}, calling fn with kwargs={kwargs}")
172
187
  # Call the template's underlying function directly
173
188
  # The fn expects the template variables as kwargs
174
189
  fn_result = template.fn(**kwargs)
@@ -178,17 +193,22 @@ def create_resource_tool(uri: str, usage: str = "", mcp_server: Any = None) -> T
178
193
  if isinstance(fn_result, str):
179
194
  return fn_result
180
195
  return json.dumps(fn_result, indent=2)
196
+ else:
197
+ logger.warning(f"Template {_captured_uri} not found in MCP server templates: {list(templates.keys())}")
181
198
  except Exception as e:
182
- logger.warning(f"Failed to resolve resource {uri} from MCP server: {e}")
199
+ logger.warning(f"Failed to resolve resource {_captured_uri} from MCP server: {e}", exc_info=True)
200
+ else:
201
+ logger.warning(f"No MCP server provided for resource tool {_captured_uri}, using fallback")
183
202
 
184
203
  # Fallback: substitute template variables and use load_resource
185
- resolved_uri = uri
204
+ resolved_uri = _captured_uri
186
205
  for var in template_vars:
187
206
  if var in kwargs:
188
207
  resolved_uri = resolved_uri.replace(f"{{{var}}}", str(kwargs[var]))
189
208
  else:
190
209
  return json.dumps({"error": f"Missing required parameter: {var}"})
191
210
 
211
+ logger.debug(f"Using fallback load_resource for resolved URI: {resolved_uri}")
192
212
  from rem.api.mcp_router.resources import load_resource
193
213
  result = await load_resource(resolved_uri)
194
214
  if isinstance(result, str):
@@ -202,7 +222,7 @@ def create_resource_tool(uri: str, usage: str = "", mcp_server: Any = None) -> T
202
222
  wrapper.__annotations__ = {var: str for var in template_vars}
203
223
  wrapper.__annotations__['return'] = str
204
224
 
205
- logger.info(f"Built parameterized resource tool: {func_name} (uri: {uri}, params: {template_vars})")
225
+ logger.info(f"Built parameterized resource tool: {func_name} (uri: {uri}, params: {template_vars}, mcp_server={'provided' if mcp_server else 'None'})")
206
226
  else:
207
227
  # Concrete URI -> no-param tool
208
228
  async def wrapper(**kwargs: Any) -> str:
@@ -213,12 +233,16 @@ def create_resource_tool(uri: str, usage: str = "", mcp_server: Any = None) -> T
213
233
  if kwargs:
214
234
  logger.warning(f"Resource tool {func_name} called with unexpected kwargs: {list(kwargs.keys())}")
215
235
 
236
+ logger.debug(f"Concrete resource tool invoked: uri={_captured_uri}, mcp_server={'set' if _captured_mcp_server else 'None'}")
237
+
216
238
  # Try to resolve from MCP server's resources first
217
- if mcp_server is not None:
239
+ if _captured_mcp_server is not None:
218
240
  try:
219
- resources = await mcp_server.get_resources()
220
- if uri in resources:
221
- resource = resources[uri]
241
+ resources = await _captured_mcp_server.get_resources()
242
+ logger.debug(f"MCP server resources: {list(resources.keys())}")
243
+ if _captured_uri in resources:
244
+ resource = resources[_captured_uri]
245
+ logger.debug(f"Found resource for {_captured_uri}")
222
246
  # Call the resource's underlying function
223
247
  fn_result = resource.fn()
224
248
  if inspect.iscoroutine(fn_result):
@@ -226,12 +250,17 @@ def create_resource_tool(uri: str, usage: str = "", mcp_server: Any = None) -> T
226
250
  if isinstance(fn_result, str):
227
251
  return fn_result
228
252
  return json.dumps(fn_result, indent=2)
253
+ else:
254
+ logger.warning(f"Resource {_captured_uri} not found in MCP server resources: {list(resources.keys())}")
229
255
  except Exception as e:
230
- logger.warning(f"Failed to resolve resource {uri} from MCP server: {e}")
256
+ logger.warning(f"Failed to resolve resource {_captured_uri} from MCP server: {e}", exc_info=True)
257
+ else:
258
+ logger.warning(f"No MCP server provided for resource tool {_captured_uri}, using fallback")
231
259
 
232
260
  # Fallback to load_resource
261
+ logger.debug(f"Using fallback load_resource for URI: {_captured_uri}")
233
262
  from rem.api.mcp_router.resources import load_resource
234
- result = await load_resource(uri)
263
+ result = await load_resource(_captured_uri)
235
264
  if isinstance(result, str):
236
265
  return result
237
266
  return json.dumps(result, indent=2)
@@ -239,6 +268,6 @@ def create_resource_tool(uri: str, usage: str = "", mcp_server: Any = None) -> T
239
268
  wrapper.__name__ = func_name
240
269
  wrapper.__doc__ = description
241
270
 
242
- logger.info(f"Built resource tool: {func_name} (uri: {uri})")
271
+ logger.info(f"Built resource tool: {func_name} (uri: {uri}, mcp_server={'provided' if mcp_server else 'None'})")
243
272
 
244
273
  return Tool(wrapper)
@@ -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",
@@ -553,58 +582,70 @@ async def create_agent(
553
582
  if agent_schema:
554
583
  system_prompt = get_system_prompt(agent_schema)
555
584
  metadata = get_metadata(agent_schema)
556
- mcp_server_configs = [s.model_dump() for s in metadata.mcp_servers] if hasattr(metadata, 'mcp_servers') and metadata.mcp_servers else []
557
585
  resource_configs = metadata.resources if hasattr(metadata, 'resources') else []
558
586
 
587
+ # DEPRECATED: mcp_servers in agent schemas is ignored
588
+ # MCP servers are now always auto-detected at the application level
589
+ if hasattr(metadata, 'mcp_servers') and metadata.mcp_servers:
590
+ logger.warning(
591
+ "DEPRECATED: mcp_servers in agent schema is ignored. "
592
+ "MCP servers are auto-detected from tools.mcp_server module. "
593
+ "Remove mcp_servers from your agent schema."
594
+ )
595
+
559
596
  if metadata.system_prompt:
560
597
  logger.debug("Using custom system_prompt from json_schema_extra")
561
598
  else:
562
599
  system_prompt = ""
563
600
  metadata = None
564
- mcp_server_configs = []
565
601
  resource_configs = []
566
602
 
567
- # Auto-detect local MCP server if not explicitly configured
568
- # This makes mcp_servers config optional - agents get tools automatically
603
+ # Auto-detect MCP server at application level
604
+ # Convention: tools/mcp_server.py exports `mcp` FastMCP instance
605
+ # Falls back to REM's built-in MCP server if no local server found
606
+ import importlib
607
+ import os
608
+ import sys
609
+
610
+ # Ensure current working directory is in sys.path for local imports
611
+ cwd = os.getcwd()
612
+ if cwd not in sys.path:
613
+ sys.path.insert(0, cwd)
614
+
615
+ mcp_server_configs = []
616
+ auto_detect_modules = [
617
+ "tools.mcp_server", # Convention: tools/mcp_server.py
618
+ "mcp_server", # Alternative: mcp_server.py in root
619
+ ]
620
+ for module_path in auto_detect_modules:
621
+ try:
622
+ mcp_module = importlib.import_module(module_path)
623
+ if hasattr(mcp_module, "mcp"):
624
+ logger.info(f"Auto-detected local MCP server: {module_path}")
625
+ mcp_server_configs = [{"type": "local", "module": module_path, "id": "auto-detected"}]
626
+ break
627
+ except ImportError as e:
628
+ logger.debug(f"MCP server auto-detect: {module_path} not found ({e})")
629
+ continue
630
+ except Exception as e:
631
+ logger.warning(f"MCP server auto-detect: {module_path} failed to load: {e}")
632
+ continue
633
+
634
+ # Fall back to REM's default MCP server if no local server found
569
635
  if not mcp_server_configs:
570
- import importlib
571
- import os
572
- import sys
573
-
574
- # Ensure current working directory is in sys.path for local imports
575
- cwd = os.getcwd()
576
- if cwd not in sys.path:
577
- sys.path.insert(0, cwd)
578
-
579
- # Try common local MCP server module paths first
580
- auto_detect_modules = [
581
- "tools.mcp_server", # Convention: tools/mcp_server.py
582
- "mcp_server", # Alternative: mcp_server.py in root
583
- ]
584
- for module_path in auto_detect_modules:
585
- try:
586
- mcp_module = importlib.import_module(module_path)
587
- if hasattr(mcp_module, "mcp"):
588
- logger.info(f"Auto-detected local MCP server: {module_path}")
589
- mcp_server_configs = [{"type": "local", "module": module_path, "id": "auto-detected"}]
590
- break
591
- except ImportError:
592
- continue
593
-
594
- # Fall back to REM's default MCP server if no local server found
595
- if not mcp_server_configs:
596
- logger.debug("No local MCP server found, using REM default")
597
- mcp_server_configs = [{"type": "local", "module": "rem.mcp_server", "id": "rem"}]
636
+ logger.info("No local MCP server found, using REM default (rem.mcp_server)")
637
+ mcp_server_configs = [{"type": "local", "module": "rem.mcp_server", "id": "rem"}]
598
638
 
599
639
  # Extract temperature and max_iterations from schema metadata (with fallback to settings defaults)
600
640
  if metadata:
601
641
  temperature = metadata.override_temperature if metadata.override_temperature is not None else settings.llm.default_temperature
602
642
  max_iterations = metadata.override_max_iterations if metadata.override_max_iterations is not None else settings.llm.default_max_iterations
603
- use_structured_output = metadata.structured_output
643
+ # Use schema-level structured_output if set, otherwise fall back to global setting
644
+ use_structured_output = metadata.structured_output if metadata.structured_output is not None else settings.llm.default_structured_output
604
645
  else:
605
646
  temperature = settings.llm.default_temperature
606
647
  max_iterations = settings.llm.default_max_iterations
607
- use_structured_output = True
648
+ use_structured_output = settings.llm.default_structured_output
608
649
 
609
650
  # Build list of tools - start with built-in tools
610
651
  tools = _get_builtin_tools()
@@ -727,6 +768,7 @@ async def create_agent(
727
768
 
728
769
  # Create tools from collected resource URIs
729
770
  # Pass the loaded MCP server so resources can be resolved from it
771
+ logger.info(f"Creating {len(resource_uris)} resource tools with mcp_server={'set' if loaded_mcp_server else 'None'}")
730
772
  for uri, usage in resource_uris:
731
773
  resource_tool = create_resource_tool(uri, usage, mcp_server=loaded_mcp_server)
732
774
  tools.append(resource_tool)
rem/agentic/schema.py CHANGED
@@ -215,12 +215,13 @@ class AgentSchemaMetadata(BaseModel):
215
215
  )
216
216
 
217
217
  # Structured output toggle
218
- structured_output: bool = Field(
219
- default=True,
218
+ structured_output: bool | None = Field(
219
+ default=None,
220
220
  description=(
221
221
  "Whether to enforce structured JSON output. "
222
222
  "When False, the agent produces free-form text and schema properties "
223
- "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)."
224
225
  ),
225
226
  )
226
227
 
@@ -3,6 +3,17 @@ REM tools for agent execution (CLI and API compatible).
3
3
 
4
4
  These tools work in both CLI and API contexts by initializing services on-demand.
5
5
  They wrap the service layer directly, not MCP tools.
6
+
7
+ Core tables (always available):
8
+ - resources: Documents, content chunks, artifacts
9
+ - moments: Temporal narratives extracted from resources (usually user-specific)
10
+ - ontologies: Domain entities with semantic links for further lookups (like a wiki)
11
+
12
+ Other tables (may vary by deployment):
13
+ - users, sessions, messages, files, schemas, feedbacks
14
+
15
+ Note: Not all tables are populated in all systems. Use FUZZY or SEARCH
16
+ to discover what data exists before assuming specific tables have content.
6
17
  """
7
18
 
8
19
  from typing import Any, Literal, cast
rem/api/main.py CHANGED
@@ -322,7 +322,7 @@ def create_app() -> FastAPI:
322
322
 
323
323
  app.add_middleware(
324
324
  AuthMiddleware,
325
- protected_paths=["/api/v1"],
325
+ protected_paths=["/api/v1", "/api/admin"],
326
326
  excluded_paths=["/api/auth", "/api/dev", "/api/v1/mcp/auth", "/api/v1/slack"],
327
327
  # Allow anonymous when auth is disabled, otherwise use setting
328
328
  allow_anonymous=(not settings.auth.enabled) or settings.auth.allow_anonymous,