Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

feat: add project id scoping for tools backend changes (#6529)

Ari Webb4092820f3a22
diff --git a/alembic/versions/2e5e90d3cdf8_add_project_id_to_tools.py b/alembic/versions/2e5e90d3cdf8_add_project_id_to_tools.py
new file mode 100644
index 000000000..0aa5dd376
--- /dev/null
+++ b/alembic/versions/2e5e90d3cdf8_add_project_id_to_tools.py
@@ -0,0 +1,27 @@
+"""add project_id to tools
+
+Revision ID: 2e5e90d3cdf8
+Revises: af842aa6f743
+Create Date: 2025-12-03 11:55:57.355341
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "2e5e90d3cdf8"
+down_revision: Union[str, None] = "af842aa6f743"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column("tools", sa.Column("project_id", sa.String(), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("tools", "project_id")
diff --git a/fern/openapi.json b/fern/openapi.json
index 29d1d1b4b..3927b1a45 100644
--- a/fern/openapi.json
+++ b/fern/openapi.json
@@ -36194,6 +36194,18 @@
],
"title": "Metadata",
"description": "A dictionary of additional metadata for the tool."
+ },
+ "project_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id",
+ "description": "The project id of the tool."
}
},
"additionalProperties": false,
@@ -39823,6 +39835,18 @@
],
"title": "Metadata",
"description": "A dictionary of additional metadata for the tool."
+ },
+ "project_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id",
+ "description": "The project id of the tool."
}
},
"additionalProperties": false,
diff --git a/letta/orm/message.py b/letta/orm/message.py
index 3a6072893..dd800f321 100644
--- a/letta/orm/message.py
+++ b/letta/orm/message.py
@@ -25,6 +25,7 @@ class Message(SqlalchemyBase, OrganizationMixin, AgentMixin):
Index("ix_messages_org_agent", "organization_id", "agent_id"),
# Composite index for optimizing the frequently-run query:
Index("ix_messages_run_sequence", "run_id", "sequence_id"),
+ Index("idx_messages_step_id", "step_id"),
)
__pydantic_model__ = PydanticMessage
diff --git a/letta/orm/step_metrics.py b/letta/orm/step_metrics.py
index 941bef16c..ead5feda7 100644
--- a/letta/orm/step_metrics.py
+++ b/letta/orm/step_metrics.py
@@ -1,7 +1,7 @@
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Optional
-from sqlalchemy import BigInteger, ForeignKey, String
+from sqlalchemy import BigInteger, ForeignKey, Index, String
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, Session, mapped_column, relationship
@@ -21,6 +21,7 @@ class StepMetrics(SqlalchemyBase, ProjectMixin, AgentMixin):
"""Tracks performance metrics for agent steps."""
__tablename__ = "step_metrics"
+ __table_args__ = (Index("ix_step_metrics_run_id", "run_id"),)
__pydantic_model__ = PydanticStepMetrics
id: Mapped[str] = mapped_column(
diff --git a/letta/orm/tool.py b/letta/orm/tool.py
index 10274bba8..2034cc350 100644
--- a/letta/orm/tool.py
+++ b/letta/orm/tool.py
@@ -3,7 +3,7 @@ from typing import TYPE_CHECKING, List, Optional
from sqlalchemy import JSON, Index, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
-from letta.orm.mixins import OrganizationMixin
+from letta.orm.mixins import OrganizationMixin, ProjectMixin
from letta.orm.sqlalchemy_base import SqlalchemyBase
# TODO everything in functions should live in this model
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
from letta.orm.organization import Organization
-class Tool(SqlalchemyBase, OrganizationMixin):
+class Tool(SqlalchemyBase, OrganizationMixin, ProjectMixin):
"""Represents an available tool that the LLM can invoke.
NOTE: polymorphic inheritance makes more sense here as a TODO. We want a superset of tools
diff --git a/letta/schemas/tool.py b/letta/schemas/tool.py
index f1d950f7b..858921b75 100644
--- a/letta/schemas/tool.py
+++ b/letta/schemas/tool.py
@@ -68,6 +68,9 @@ class Tool(BaseTool):
last_updated_by_id: Optional[str] = Field(None, description="The id of the user that made this Tool.")
metadata_: Optional[Dict[str, Any]] = Field(default_factory=dict, description="A dictionary of additional metadata for the tool.")
+ # project scoping
+ project_id: Optional[str] = Field(None, description="The project id of the tool.")
+
@model_validator(mode="after")
def refresh_source_code_and_json_schema(self):
"""
diff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.py
index 63227a6da..ea28564ce 100644
--- a/letta/server/rest_api/routers/v1/tools.py
+++ b/letta/server/rest_api/routers/v1/tools.py
@@ -148,6 +148,7 @@ async def count_tools(
search=search,
return_only_letta_tools=return_only_letta_tools,
exclude_letta_tools=exclude_letta_tools,
+ project_id=headers.project_id,
)
@@ -268,6 +269,7 @@ async def list_tools(
tool_ids=final_tool_ids,
search=search,
return_only_letta_tools=return_only_letta_tools,
+ project_id=headers.project_id,
)
@@ -322,6 +324,9 @@ async def create_tool(
"""
actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)
tool = Tool(**request.model_dump(exclude_unset=True))
+ # Set project_id from header if provided
+ if headers.project_id:
+ tool.project_id = headers.project_id
modal_sandbox_enabled = bool(headers.experimental_params.modal_sandbox) if headers.experimental_params else False
return await server.tool_manager.create_or_update_tool_async(
pydantic_tool=tool, actor=actor, modal_sandbox_enabled=modal_sandbox_enabled
@@ -339,8 +344,12 @@ async def upsert_tool(
"""
actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id)
modal_sandbox_enabled = bool(headers.experimental_params.modal_sandbox) if headers.experimental_params else False
+ tool = Tool(**request.model_dump(exclude_unset=True))
+ # Set project_id from header if provided
+ if headers.project_id:
+ tool.project_id = headers.project_id
tool = await server.tool_manager.create_or_update_tool_async(
- pydantic_tool=Tool(**request.model_dump(exclude_unset=True)), actor=actor, modal_sandbox_enabled=modal_sandbox_enabled
+ pydantic_tool=tool, actor=actor, modal_sandbox_enabled=modal_sandbox_enabled
)
return tool
diff --git a/letta/services/tool_manager.py b/letta/services/tool_manager.py
index 2a755f028..6b52cd704 100644
--- a/letta/services/tool_manager.py
+++ b/letta/services/tool_manager.py
@@ -615,6 +615,7 @@ class ToolManager:
tool_ids: Optional[List[str]] = None,
search: Optional[str] = None,
return_only_letta_tools: bool = False,
+ project_id: Optional[str] = None,
) -> List[PydanticTool]:
"""List all tools with pagination support."""
tools = await self._list_tools_async(
@@ -629,6 +630,7 @@ class ToolManager:
tool_ids=tool_ids,
search=search,
return_only_letta_tools=return_only_letta_tools,
+ project_id=project_id,
)
# Check if all base tools are present if we requested all the tools w/o cursor
@@ -656,6 +658,7 @@ class ToolManager:
tool_ids=tool_ids,
search=search,
return_only_letta_tools=return_only_letta_tools,
+ project_id=project_id,
)
return tools
@@ -675,6 +678,7 @@ class ToolManager:
tool_ids: Optional[List[str]] = None,
search: Optional[str] = None,
return_only_letta_tools: bool = False,
+ project_id: Optional[str] = None,
) -> List[PydanticTool]:
"""List all tools with optional pagination."""
tools_to_delete = []
@@ -683,6 +687,10 @@ class ToolManager:
# Start with base query
query = select(ToolModel).where(ToolModel.organization_id == actor.organization_id)
+ # Apply project_id filter - include tools where project_id matches OR project_id is None (global tools)
+ if project_id is not None:
+ query = query.where(or_(ToolModel.project_id == project_id, ToolModel.project_id.is_(None)))
+
# Apply tool_types filter
if tool_types is not None:
query = query.where(ToolModel.tool_type.in_(tool_types))
@@ -791,6 +799,7 @@ class ToolManager:
search: Optional[str] = None,
return_only_letta_tools: bool = False,
exclude_letta_tools: bool = False,
+ project_id: Optional[str] = None,
) -> int:
"""Count tools with the same filtering logic as list_tools_async."""
async with db_registry.async_session() as session:
@@ -798,6 +807,10 @@ class ToolManager:
# Start with base query
query = select(func.count(ToolModel.id)).where(ToolModel.organization_id == actor.organization_id)
+ # Apply project_id filter - include tools where project_id matches OR project_id is None (global tools)
+ if project_id is not None:
+ query = query.where(or_(ToolModel.project_id == project_id, ToolModel.project_id.is_(None)))
+
# Apply tool_types filter
if tool_types is not None:
query = query.where(ToolModel.tool_type.in_(tool_types))
diff --git a/tests/managers/test_agent_manager.py b/tests/managers/test_agent_manager.py
index 06b6798d2..2584459a6 100644
--- a/tests/managers/test_agent_manager.py
+++ b/tests/managers/test_agent_manager.py
@@ -1494,6 +1494,7 @@ async def test_agent_state_schema_unchanged(server: SyncServer):
"created_by_id",
"last_updated_by_id",
"metadata_",
+ "project_id",
}
actual_tool_fields = set(tool_fields.keys())
if actual_tool_fields != expected_tool_fields:
diff --git a/tests/managers/test_tool_manager.py b/tests/managers/test_tool_manager.py
index 46e1a56ef..81e0c428a 100644
--- a/tests/managers/test_tool_manager.py
+++ b/tests/managers/test_tool_manager.py
@@ -2174,6 +2174,225 @@ async def test_update_tool_name(server: SyncServer, default_user, default_organi
assert updated_tool3.json_schema["name"] == "matched_name"
+async def test_list_tools_with_project_id_filtering(server: SyncServer, default_user):
+ """Test listing tools with project_id filtering - global vs project-scoped tools."""
+
+ # Create separate functions for each tool (name must match function name)
+ def global_tool_func() -> str:
+ """A global tool with no project_id.
+
+ Returns:
+ str: Test result
+ """
+ return "global_result"
+
+ def project_a_tool_func() -> str:
+ """A tool scoped to project A.
+
+ Returns:
+ str: Test result
+ """
+ return "project_a_result"
+
+ def project_b_tool_func() -> str:
+ """A tool scoped to project B.
+
+ Returns:
+ str: Test result
+ """
+ return "project_b_result"
+
+ # Create a global tool (project_id = None)
+ global_tool = PydanticTool(
+ name="global_tool_func",
+ description="A global tool with no project_id",
+ source_code=parse_source_code(global_tool_func),
+ source_type="python",
+ tool_type=ToolType.CUSTOM,
+ project_id=None, # Global tool
+ )
+ global_tool.json_schema = generate_schema_for_tool_creation(global_tool)
+ global_tool = await server.tool_manager.create_or_update_tool_async(global_tool, actor=default_user)
+
+ # Create a tool scoped to project_a
+ project_a_id = f"project-{uuid.uuid4()}"
+ project_a_tool = PydanticTool(
+ name="project_a_tool_func",
+ description="A tool scoped to project A",
+ source_code=parse_source_code(project_a_tool_func),
+ source_type="python",
+ tool_type=ToolType.CUSTOM,
+ project_id=project_a_id,
+ )
+ project_a_tool.json_schema = generate_schema_for_tool_creation(project_a_tool)
+ project_a_tool = await server.tool_manager.create_or_update_tool_async(project_a_tool, actor=default_user)
+
+ # Create a tool scoped to project_b
+ project_b_id = f"project-{uuid.uuid4()}"
+ project_b_tool = PydanticTool(
+ name="project_b_tool_func",
+ description="A tool scoped to project B",
+ source_code=parse_source_code(project_b_tool_func),
+ source_type="python",
+ tool_type=ToolType.CUSTOM,
+ project_id=project_b_id,
+ )
+ project_b_tool.json_schema = generate_schema_for_tool_creation(project_b_tool)
+ project_b_tool = await server.tool_manager.create_or_update_tool_async(project_b_tool, actor=default_user)
+
+ # Test 1: When no project_id is provided, list ALL tools
+ all_tools = await server.tool_manager.list_tools_async(actor=default_user, upsert_base_tools=False, project_id=None)
+ all_tool_names = {t.name for t in all_tools}
+ assert "global_tool_func" in all_tool_names
+ assert "project_a_tool_func" in all_tool_names
+ assert "project_b_tool_func" in all_tool_names
+
+ # Test 2: When project_a_id is provided, list only global + project_a tools
+ project_a_tools = await server.tool_manager.list_tools_async(actor=default_user, upsert_base_tools=False, project_id=project_a_id)
+ project_a_tool_names = {t.name for t in project_a_tools}
+ assert "global_tool_func" in project_a_tool_names # Global tools should be included
+ assert "project_a_tool_func" in project_a_tool_names # Project A tool should be included
+ assert "project_b_tool_func" not in project_a_tool_names # Project B tool should NOT be included
+
+ # Test 3: When project_b_id is provided, list only global + project_b tools
+ project_b_tools = await server.tool_manager.list_tools_async(actor=default_user, upsert_base_tools=False, project_id=project_b_id)
+ project_b_tool_names = {t.name for t in project_b_tools}
+ assert "global_tool_func" in project_b_tool_names # Global tools should be included
+ assert "project_b_tool_func" in project_b_tool_names # Project B tool should be included
+ assert "project_a_tool_func" not in project_b_tool_names # Project A tool should NOT be included
+
+ # Test 4: When a non-existent project_id is provided, list only global tools
+ non_existent_project_id = f"project-{uuid.uuid4()}"
+ non_existent_project_tools = await server.tool_manager.list_tools_async(
+ actor=default_user, upsert_base_tools=False, project_id=non_existent_project_id
+ )
+ non_existent_tool_names = {t.name for t in non_existent_project_tools}
+ assert "global_tool_func" in non_existent_tool_names # Global tools should be included
+ assert "project_a_tool_func" not in non_existent_tool_names
+ assert "project_b_tool_func" not in non_existent_tool_names
+
+
+async def test_count_tools_with_project_id_filtering(server: SyncServer, default_user):
+ """Test counting tools with project_id filtering - global vs project-scoped tools."""
+
+ # Create separate functions for each tool
+ def count_global_tool_0() -> str:
+ """Global tool 0 for counting.
+
+ Returns:
+ str: Test result
+ """
+ return "count_result"
+
+ def count_global_tool_1() -> str:
+ """Global tool 1 for counting.
+
+ Returns:
+ str: Test result
+ """
+ return "count_result"
+
+ def count_project_a_tool_0() -> str:
+ """Project A tool 0 for counting.
+
+ Returns:
+ str: Test result
+ """
+ return "count_result"
+
+ def count_project_a_tool_1() -> str:
+ """Project A tool 1 for counting.
+
+ Returns:
+ str: Test result
+ """
+ return "count_result"
+
+ def count_project_a_tool_2() -> str:
+ """Project A tool 2 for counting.
+
+ Returns:
+ str: Test result
+ """
+ return "count_result"
+
+ def count_project_b_tool() -> str:
+ """Project B tool for counting.
+
+ Returns:
+ str: Test result
+ """
+ return "count_result"
+
+ global_funcs = [count_global_tool_0, count_global_tool_1]
+ project_a_funcs = [count_project_a_tool_0, count_project_a_tool_1, count_project_a_tool_2]
+
+ # Create 2 global tools
+ for tool_func in global_funcs:
+ global_tool = PydanticTool(
+ name=tool_func.__name__,
+ description="Global tool for counting",
+ source_code=parse_source_code(tool_func),
+ source_type="python",
+ tool_type=ToolType.CUSTOM,
+ project_id=None,
+ )
+ global_tool.json_schema = generate_schema_for_tool_creation(global_tool)
+ await server.tool_manager.create_or_update_tool_async(global_tool, actor=default_user)
+
+ # Create 3 tools scoped to project_a
+ project_a_id = f"project-{uuid.uuid4()}"
+ for tool_func in project_a_funcs:
+ project_a_tool = PydanticTool(
+ name=tool_func.__name__,
+ description="Project A tool for counting",
+ source_code=parse_source_code(tool_func),
+ source_type="python",
+ tool_type=ToolType.CUSTOM,
+ project_id=project_a_id,
+ )
+ project_a_tool.json_schema = generate_schema_for_tool_creation(project_a_tool)
+ await server.tool_manager.create_or_update_tool_async(project_a_tool, actor=default_user)
+
+ # Create 1 tool scoped to project_b
+ project_b_id = f"project-{uuid.uuid4()}"
+ project_b_tool_pydantic = PydanticTool(
+ name="count_project_b_tool",
+ description="Project B tool for counting",
+ source_code=parse_source_code(count_project_b_tool),
+ source_type="python",
+ tool_type=ToolType.CUSTOM,
+ project_id=project_b_id,
+ )
+ project_b_tool_pydantic.json_schema = generate_schema_for_tool_creation(project_b_tool_pydantic)
+ await server.tool_manager.create_or_update_tool_async(project_b_tool_pydantic, actor=default_user)
+
+ # Test 1: Count without project_id filter should count all custom tools we created (2 + 3 + 1 = 6)
+ all_count = await server.tool_manager.count_tools_async(actor=default_user, tool_types=[ToolType.CUSTOM.value], search="count_")
+ assert all_count == 6
+
+ # Test 2: Count with project_a_id should count global + project_a tools (2 + 3 = 5)
+ project_a_count = await server.tool_manager.count_tools_async(
+ actor=default_user, tool_types=[ToolType.CUSTOM.value], search="count_", project_id=project_a_id
+ )
+ assert project_a_count == 5
+
+ # Test 3: Count with project_b_id should count global + project_b tools (2 + 1 = 3)
+ project_b_count = await server.tool_manager.count_tools_async(
+ actor=default_user, tool_types=[ToolType.CUSTOM.value], search="count_", project_id=project_b_id
+ )
+ assert project_b_count == 3
+
+ # Test 4: Count with non-existent project_id should only count global tools (2)
+ non_existent_project_id = f"project-{uuid.uuid4()}"
+ global_only_count = await server.tool_manager.count_tools_async(
+ actor=default_user, tool_types=[ToolType.CUSTOM.value], search="count_", project_id=non_existent_project_id
+ )
+ assert global_only_count == 2
+
+
@pytest.mark.asyncio
async def test_list_tools_with_corrupted_tool(server: SyncServer, default_user, print_tool):
"""Test that list_tools still works even if there's a corrupted tool (missing json_schema) in the database."""