Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions backend/app/api/endpoints/admin/im_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ def _kind_to_response(kind: Kind) -> IMChannelResponse:
name=kind.name,
namespace=kind.namespace,
channel_type=spec.get("channelType", "dingtalk"),
bot_purpose=spec.get("botPurpose", "wegent_chat"),
is_enabled=spec.get("isEnabled", True),
config=_mask_config(config), # Mask sensitive fields
default_team_id=spec.get("defaultTeamId", 0),
Expand All @@ -110,6 +111,7 @@ def _create_messager_json(
name: str,
namespace: str,
channel_type: str,
bot_purpose: str,
is_enabled: bool,
config: Dict[str, Any],
default_team_id: int,
Expand All @@ -125,6 +127,7 @@ def _create_messager_json(
},
"spec": {
"channelType": channel_type,
"botPurpose": bot_purpose,
"isEnabled": is_enabled,
"config": _encrypt_config(config), # Encrypt sensitive fields
"defaultTeamId": default_team_id,
Expand All @@ -133,6 +136,20 @@ def _create_messager_json(
}


def _validate_bot_purpose_update(
*,
existing_purpose: str,
requested_purpose: Optional[str],
) -> None:
"""Reject changing IM bot purpose after channel creation."""
if requested_purpose is None or requested_purpose == existing_purpose:
return
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="IM bot purpose cannot be changed after creation",
)


class IMChannelAdapter:
"""Adapter to make Kind behave like IMChannel for ChannelManager."""

Expand All @@ -142,6 +159,7 @@ def __init__(self, kind: Kind):
self.id = kind.id
self.name = kind.name
self.channel_type = spec.get("channelType", "dingtalk")
self.bot_purpose = spec.get("botPurpose", "wegent_chat")
self.is_enabled = spec.get("isEnabled", True)
# Decrypt config for actual use
self.config = _decrypt_config(spec.get("config", {}))
Expand Down Expand Up @@ -261,6 +279,7 @@ async def create_im_channel(
name=channel_data.name,
namespace=channel_data.namespace,
channel_type=channel_data.channel_type,
bot_purpose=channel_data.bot_purpose,
is_enabled=channel_data.is_enabled,
config=channel_data.config,
default_team_id=channel_data.default_team_id or 0,
Expand Down Expand Up @@ -338,6 +357,10 @@ async def update_im_channel(
spec = current_json.get("spec", {})
was_enabled = spec.get("isEnabled", True)
needs_restart = False
_validate_bot_purpose_update(
existing_purpose=spec.get("botPurpose", "wegent_chat"),
requested_purpose=channel_data.bot_purpose,
)

# Update fields
if channel_data.name is not None:
Expand Down
36 changes: 32 additions & 4 deletions backend/app/api/endpoints/im_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

"""Private IM session task-continuation endpoints."""

from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.api.dependencies import get_db
Expand Down Expand Up @@ -37,15 +37,30 @@
)
@trace_async("list_private_im_sessions", "im.api")
async def list_private_sessions(
bot_purpose: str | None = Query(
default=None,
description="Filter private sessions by IM bot purpose",
),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> IMPrivateSessionListResponse:
"""List the current user's private IM sessions."""

sessions = await im_session_service.list_user_sessions(db, user_id=current_user.id)
items: list[IMPrivateSessionOut] = []
for session in sessions:
session_bot_purpose = await im_session_service.get_session_bot_purpose(
db,
session,
)
if bot_purpose and session_bot_purpose != bot_purpose:
continue
items.append(
_private_session_out(session, bot_purpose=session_bot_purpose),
)
Comment on lines +52 to +60

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Normalize unsupported bot_purpose values before serialization.

At Line 52, session_bot_purpose is passed through directly. If a channel carries an unexpected persisted value, this path can fail the private-session response instead of safely defaulting.

🛠️ Suggested fix
+SUPPORTED_BOT_PURPOSES = {"wegent_chat", "wework_local"}
+
 async def list_private_sessions(
@@
     for session in sessions:
-        session_bot_purpose = await im_session_service.get_session_bot_purpose(
+        raw_bot_purpose = await im_session_service.get_session_bot_purpose(
             db,
             session,
         )
+        session_bot_purpose = (
+            raw_bot_purpose
+            if raw_bot_purpose in SUPPORTED_BOT_PURPOSES
+            else "wegent_chat"
+        )
         if bot_purpose and session_bot_purpose != bot_purpose:
             continue
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/api/endpoints/im_sessions.py` around lines 52 - 60, The
session_bot_purpose value retrieved from
im_session_service.get_session_bot_purpose() may contain unexpected or
unsupported values that will cause serialization to fail. Add normalization
logic for session_bot_purpose after it is retrieved but before it is passed to
the _private_session_out() function to safely handle any unexpected values by
defaulting to a valid fallback value when needed.

return IMPrivateSessionListResponse(
total=len(sessions),
items=[_private_session_out(session) for session in sessions],
total=len(items),
items=items,
)


Expand Down Expand Up @@ -86,17 +101,30 @@ async def bind_task_private_sessions(
)


def _private_session_out(session: IMPrivateSession) -> IMPrivateSessionOut:
def _private_session_out(
session: IMPrivateSession,
*,
bot_purpose: str,
) -> IMPrivateSessionOut:
runtime_task = session.active_runtime_task or {}
current_target_label = None
if runtime_task:
current_target_label = str(
runtime_task.get("title") or runtime_task.get("localTaskId") or ""
)
return IMPrivateSessionOut(
session_key=session.session_key,
channel_type=session.channel_type,
channel_label=im_session_service.get_channel_label(session.channel_type),
channel_id=session.channel_id,
bot_purpose=bot_purpose,
conversation_id=session.conversation_id,
sender_id=session.sender_id,
display_name=session.display_name,
mode=session.mode,
state=session.state,
active_task_id=session.active_task_id,
current_target_type="wework_runtime_task" if runtime_task else None,
current_target_label=current_target_label,
last_seen_at=session.last_seen_at,
)
6 changes: 6 additions & 0 deletions backend/app/mcp_server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
- /mcp/knowledge/sse - Knowledge MCP streamable HTTP transport endpoint
- /mcp/knowledge-external - Trusted external knowledge integration MCP root
- /mcp/knowledge-external/sse - External knowledge MCP streamable HTTP transport endpoint
- /mcp/im-control - Private IM session control MCP module root
- /mcp/im-control/sse - Private IM session control MCP streamable HTTP transport endpoint
New MCP servers should follow /mcp/<name>/sse for streamable HTTP transport.

The MCP Server runs as part of the Backend FastAPI application and uses
Expand All @@ -32,7 +34,9 @@
)
from .server import (
ExternalKnowledgeUser,
ensure_im_control_tools_registered,
ensure_knowledge_tools_registered,
get_mcp_im_control_config,
get_mcp_system_config,
register_mcp_apps,
set_external_knowledge_auth_handler,
Expand All @@ -46,8 +50,10 @@
__all__ = [
# Server functions
"get_mcp_system_config",
"get_mcp_im_control_config",
"register_mcp_apps",
"ensure_knowledge_tools_registered",
"ensure_im_control_tools_registered",
"set_external_knowledge_auth_handler",
"ExternalKnowledgeUser",
# Auth functions
Expand Down
81 changes: 81 additions & 0 deletions backend/app/mcp_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
- /mcp/knowledge/sse - Knowledge MCP streamable HTTP transport endpoint
- /mcp/knowledge-external - Trusted external knowledge integration MCP root
- /mcp/knowledge-external/sse - External knowledge MCP streamable HTTP transport endpoint
- /mcp/im-control - Private IM session control MCP module root
- /mcp/im-control/sse - Private IM session control MCP streamable HTTP transport endpoint
New MCP servers should follow /mcp/<name>/sse for streamable HTTP transport.

The MCP Server uses FastMCP with HTTP Streamable transport and integrates
Expand Down Expand Up @@ -65,6 +67,8 @@
PROMPT_OPTIMIZATION_MCP_TRANSPORT_PATH = "/sse"
SUBSCRIPTION_MCP_MOUNT_PATH = "/mcp/subscription"
SUBSCRIPTION_MCP_TRANSPORT_PATH = "/sse"
IM_CONTROL_MCP_MOUNT_PATH = "/mcp/im-control"
IM_CONTROL_MCP_TRANSPORT_PATH = "/sse"


@dataclass(frozen=True)
Expand Down Expand Up @@ -521,6 +525,50 @@ def ensure_subscription_tools_registered() -> None:
_register_subscription_tools()


# ============== IM Control MCP Server ==============
# Provides private IM session state control tools
# Available via Skill configuration
# Uses decorator-based auto-registration from @mcp_tool decorated endpoints

im_control_mcp_server = FastMCP(
"wegent-im-control-mcp",
stateless_http=True,
json_response=True,
streamable_http_path="/",
transport_security=_build_transport_security_settings(),
)

# Store for im_control MCP request context (used by McpAppSpec)
_im_control_request_token_info: contextvars.ContextVar[Optional[TaskTokenInfo]] = (
contextvars.ContextVar("_im_control_request_token_info", default=None)
)

# Flag to track if tools have been registered
_im_control_tools_registered = False


def _register_im_control_tools() -> None:
"""Register im_control tools from @mcp_tool decorated functions."""
global _im_control_tools_registered
if _im_control_tools_registered:
return

from app.mcp_server.tool_registry import register_tools_to_server
from app.mcp_server.tools import ( # noqa: F401 side-effect: triggers @mcp_tool registration
im_control,
)

count = register_tools_to_server(im_control_mcp_server, "im_control")
logger.info(f"[MCP:IMControl] Registered {count} tools from decorated endpoints")

_im_control_tools_registered = True


def ensure_im_control_tools_registered() -> None:
"""Ensure im_control MCP tools are registered."""
_register_im_control_tools()


# ============== Starlette App Factory ==============

_SYSTEM_MCP_SPEC = McpAppSpec(
Expand Down Expand Up @@ -578,12 +626,24 @@ def ensure_subscription_tools_registered() -> None:
include_root_metadata=True,
)

_IM_CONTROL_MCP_SPEC = McpAppSpec(
name="im_control",
service_name="wegent-im-control-mcp",
mount_path=IM_CONTROL_MCP_MOUNT_PATH,
transport_path=IM_CONTROL_MCP_TRANSPORT_PATH,
server=im_control_mcp_server,
token_context=_im_control_request_token_info,
log_prefix="IMControl",
include_root_metadata=True,
)

MCP_APP_SPECS = (
_SYSTEM_MCP_SPEC,
_KNOWLEDGE_MCP_SPEC,
_INTERACTIVE_FORM_MCP_SPEC,
_PROMPT_OPTIMIZATION_MCP_SPEC,
_SUBSCRIPTION_MCP_SPEC,
_IM_CONTROL_MCP_SPEC,
)


Expand Down Expand Up @@ -617,6 +677,8 @@ def _build_mcp_app(spec: McpAppSpec) -> Starlette:
ensure_prompt_optimization_tools_registered()
elif spec.name == "subscription":
ensure_subscription_tools_registered()
elif spec.name == "im_control":
ensure_im_control_tools_registered()

@asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[None]:
Expand Down Expand Up @@ -663,6 +725,7 @@ async def auth_middleware(request: Request, call_next):
"interactive_form_question",
"prompt_optimization",
"subscription",
"im_control",
):
mcp_ctx = MCPRequestContext(
token_info=token_info,
Expand Down Expand Up @@ -848,6 +911,24 @@ def get_mcp_prompt_optimization_config(
)


def get_mcp_im_control_config(backend_url: str, auth_token: str) -> Dict[str, Any]:
"""Get im_control MCP server configuration for Skill injection.

Args:
backend_url: Backend URL (e.g., "http://localhost:8000")
auth_token: Authentication token for MCP server (uses placeholder for Skill)

Returns:
MCP server configuration dictionary
"""
return _build_streamable_http_config(
name="wegent-im-control",
url=f"{backend_url}{IM_CONTROL_MCP_MOUNT_PATH}{IM_CONTROL_MCP_TRANSPORT_PATH}",
auth_token=auth_token,
timeout=60,
)


def _normalize_prefix(prefix: str) -> str:
if not prefix:
return ""
Expand Down
Loading
Loading