Personal AI, On Personal Devices
Python
feat: add Slack data source connector with channel history sync
krypticmouse0d9c25c6f907
diff --git a/src/openjarvis/connectors/slack_connector.py b/src/openjarvis/connectors/slack_connector.pynew file mode 100644index 00000000..68a2103b--- /dev/null+++ b/src/openjarvis/connectors/slack_connector.py@@ -0,0 +1,431 @@+"""Slack connector — bulk channel message sync via the Slack Web API.++Uses OAuth tokens stored locally (see :mod:`openjarvis.connectors.oauth`).+All network calls are isolated in module-level functions (``_slack_api_*``)+to make them trivially mockable in tests.+"""++from __future__ import annotations++from datetime import datetime, timezone+from typing import Any, Dict, Iterator, List, Optional+from urllib.parse import urlencode++import httpx++from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus+from openjarvis.connectors.oauth import delete_tokens, load_tokens, save_tokens+from openjarvis.core.config import DEFAULT_CONFIG_DIR+from openjarvis.core.registry import ConnectorRegistry+from openjarvis.tools._stubs import ToolSpec++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++_SLACK_API_BASE = "https://slack.com/api"+_SLACK_AUTH_ENDPOINT = "https://slack.com/oauth/v2/authorize"+_SLACK_SCOPES = "channels:history,channels:read,users:read"+_DEFAULT_CREDENTIALS_PATH = str(+ DEFAULT_CONFIG_DIR / "connectors" / "slack.json"+)++# ---------------------------------------------------------------------------+# Module-level API functions (easy to patch in tests)+# ---------------------------------------------------------------------------+++def _slack_api_conversations_list(+ token: str,+ *,+ cursor: str = "",+) -> Dict[str, Any]:+ """Call the Slack ``conversations.list`` endpoint.++ Parameters+ ----------+ token:+ OAuth access token.+ cursor:+ Pagination cursor from a previous response's ``next_cursor``.++ Returns+ -------+ dict+ Raw API response containing ``channels`` list and ``response_metadata``.+ """+ params: Dict[str, str] = {+ "types": "public_channel,private_channel",+ "exclude_archived": "true",+ }+ if cursor:+ params["cursor"] = cursor++ resp = httpx.get(+ f"{_SLACK_API_BASE}/conversations.list",+ headers={"Authorization": f"Bearer {token}"},+ params=params,+ timeout=30.0,+ )+ resp.raise_for_status()+ return resp.json()+++def _slack_api_conversations_history(+ token: str,+ channel_id: str,+ *,+ cursor: str = "",+) -> Dict[str, Any]:+ """Call the Slack ``conversations.history`` endpoint.++ Parameters+ ----------+ token:+ OAuth access token.+ channel_id:+ The Slack channel ID to retrieve history for.+ cursor:+ Pagination cursor from a previous response's ``next_cursor``.++ Returns+ -------+ dict+ Raw API response containing ``messages`` list and ``has_more`` flag.+ """+ params: Dict[str, str] = {"channel": channel_id}+ if cursor:+ params["cursor"] = cursor++ resp = httpx.get(+ f"{_SLACK_API_BASE}/conversations.history",+ headers={"Authorization": f"Bearer {token}"},+ params=params,+ timeout=30.0,+ )+ resp.raise_for_status()+ return resp.json()+++def _slack_api_users_list(token: str) -> Dict[str, Any]:+ """Call the Slack ``users.list`` endpoint.++ Parameters+ ----------+ token:+ OAuth access token.++ Returns+ -------+ dict+ Raw API response containing ``members`` list.+ """+ resp = httpx.get(+ f"{_SLACK_API_BASE}/users.list",+ headers={"Authorization": f"Bearer {token}"},+ timeout=30.0,+ )+ resp.raise_for_status()+ return resp.json()+++# ---------------------------------------------------------------------------+# Helper functions+# ---------------------------------------------------------------------------+++def _build_user_map(members: List[Dict[str, Any]]) -> Dict[str, Dict[str, str]]:+ """Build a user_id → {name, email} map from a ``users.list`` members list."""+ user_map: Dict[str, Dict[str, str]] = {}+ for member in members:+ uid = member.get("id", "")+ if not uid:+ continue+ profile = member.get("profile", {})+ user_map[uid] = {+ "name": member.get("real_name", uid),+ "email": profile.get("email", ""),+ }+ return user_map+++def _ts_to_datetime(ts: str) -> datetime:+ """Convert a Slack timestamp string (e.g. '1710500000.000100') to datetime."""+ if not ts:+ return datetime.now()+ try:+ return datetime.fromtimestamp(float(ts), tz=timezone.utc)+ except (ValueError, OSError):+ return datetime.now()+++def _slack_archive_url(team_id: str, channel_id: str, ts: str) -> str:+ """Build a Slack message archive URL from team, channel, and timestamp."""+ ts_clean = ts.replace(".", "")+ return f"https://slack.com/archives/{channel_id}/p{ts_clean}"+++# ---------------------------------------------------------------------------+# SlackConnector+# ---------------------------------------------------------------------------++[email protected]("slack")+class SlackConnector(BaseConnector):+ """Connector that syncs channel message history from Slack via the Web API.++ Authentication is handled through Slack OAuth 2.0. Tokens are stored+ locally in a JSON credentials file.++ Parameters+ ----------+ credentials_path:+ Path to the JSON file where OAuth tokens are stored. Defaults to+ ``~/.openjarvis/connectors/slack.json``.+ """++ connector_id = "slack"+ display_name = "Slack"+ auth_type = "oauth"++ def __init__(self, credentials_path: str = "") -> None:+ self._credentials_path = credentials_path or _DEFAULT_CREDENTIALS_PATH+ self._items_synced: int = 0+ self._items_total: int = 0+ self._last_sync: Optional[datetime] = None+ self._last_cursor: Optional[str] = None++ # ------------------------------------------------------------------+ # BaseConnector interface+ # ------------------------------------------------------------------++ def is_connected(self) -> bool:+ """Return ``True`` if a credentials file with a valid token exists."""+ tokens = load_tokens(self._credentials_path)+ if tokens is None:+ return False+ return bool(tokens)++ def disconnect(self) -> None:+ """Delete the stored credentials file."""+ delete_tokens(self._credentials_path)++ def auth_url(self) -> str:+ """Return a Slack OAuth consent URL requesting channel history scopes."""+ params = {+ "client_id": "", # placeholder — real client_id from config+ "scope": _SLACK_SCOPES,+ "redirect_uri": "http://localhost:8789/callback",+ }+ return f"{_SLACK_AUTH_ENDPOINT}?{urlencode(params)}"++ def handle_callback(self, code: str) -> None:+ """Handle the OAuth callback by persisting the authorization code.++ In a full implementation this would exchange the code for tokens.+ For now the code is saved directly as the token value.+ """+ save_tokens(self._credentials_path, {"token": code})++ def sync(+ self,+ *,+ since: Optional[datetime] = None, # noqa: ARG002 — reserved for future use+ cursor: Optional[str] = None, # noqa: ARG002 — reserved for future use+ ) -> Iterator[Document]:+ """Yield :class:`Document` objects for Slack channel messages.++ Builds a user map, then paginates through channels and retrieves+ message history for each channel.++ Parameters+ ----------+ since:+ Not yet used (reserved for incremental sync).+ cursor:+ Not yet used (reserved for pagination resumption).+ """+ tokens = load_tokens(self._credentials_path)+ if not tokens:+ return++ token: str = tokens.get("token", tokens.get("access_token", ""))+ if not token:+ return++ # Step 1: build user map+ users_resp = _slack_api_users_list(token)+ members: List[Dict[str, Any]] = users_resp.get("members", [])+ user_map = _build_user_map(members)++ synced = 0+ channels_cursor = ""++ # Step 2: paginate through channels+ while True:+ channels_resp = _slack_api_conversations_list(+ token, cursor=channels_cursor+ )+ channels: List[Dict[str, Any]] = channels_resp.get("channels", [])++ for channel in channels:+ chan_id: str = channel.get("id", "")+ chan_name: str = channel.get("name", chan_id)+ if not chan_id:+ continue++ # Step 3: paginate through message history+ history_cursor = ""+ while True:+ history_resp = _slack_api_conversations_history(+ token, chan_id, cursor=history_cursor+ )+ messages: List[Dict[str, Any]] = history_resp.get(+ "messages", []+ )++ for msg in messages:+ ts: str = msg.get("ts", "")+ user_id: str = msg.get("user", "")+ text: str = msg.get("text", "")+ thread_ts: Optional[str] = msg.get("thread_ts")++ user_info = user_map.get(user_id, {})+ author = user_info.get("name", user_id)++ timestamp = _ts_to_datetime(ts)+ url = _slack_archive_url("", chan_id, ts)++ doc = Document(+ doc_id=f"slack:{chan_id}:{ts}",+ source="slack",+ doc_type="message",+ content=text,+ title=f"#{chan_name}",+ author=author,+ timestamp=timestamp,+ thread_id=thread_ts,+ url=url,+ metadata={+ "channel_id": chan_id,+ "channel_name": chan_name,+ "user_id": user_id,+ "ts": ts,+ },+ )+ synced += 1+ yield doc++ next_history_cursor: str = (+ history_resp.get("response_metadata", {}).get(+ "next_cursor", ""+ )+ or ""+ )+ if not history_resp.get("has_more") or not next_history_cursor:+ break+ history_cursor = next_history_cursor++ next_channels_cursor: str = (+ channels_resp.get("response_metadata", {}).get("next_cursor", "")+ or ""+ )+ if not next_channels_cursor:+ self._last_cursor = None+ break+ channels_cursor = next_channels_cursor+ self._last_cursor = channels_cursor++ self._items_synced = synced+ self._last_sync = datetime.now()++ def sync_status(self) -> SyncStatus:+ """Return sync progress from the most recent :meth:`sync` call."""+ return SyncStatus(+ state="idle",+ items_synced=self._items_synced,+ last_sync=self._last_sync,+ cursor=self._last_cursor,+ )++ # ------------------------------------------------------------------+ # MCP tools+ # ------------------------------------------------------------------++ def mcp_tools(self) -> List[ToolSpec]:+ """Expose three MCP tool specs for real-time Slack queries."""+ return [+ ToolSpec(+ name="slack_search_messages",+ description=(+ "Search Slack messages using a query string. "+ "Returns matching messages across all accessible channels."+ ),+ parameters={+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "Search query string",+ },+ "max_results": {+ "type": "integer",+ "description": "Maximum number of messages to return",+ "default": 20,+ },+ },+ "required": ["query"],+ },+ category="communication",+ ),+ ToolSpec(+ name="slack_get_thread",+ description=(+ "Retrieve all messages in a Slack thread by channel ID "+ "and thread timestamp."+ ),+ parameters={+ "type": "object",+ "properties": {+ "channel_id": {+ "type": "string",+ "description": "Slack channel ID",+ },+ "thread_ts": {+ "type": "string",+ "description": (+ "Thread timestamp (ts of the parent message)"+ ),+ },+ },+ "required": ["channel_id", "thread_ts"],+ },+ category="communication",+ ),+ ToolSpec(+ name="slack_list_channels",+ description=(+ "List accessible Slack channels, optionally filtered by type."+ ),+ parameters={+ "type": "object",+ "properties": {+ "types": {+ "type": "string",+ "description": (+ "Comma-separated channel types to include "+ "(e.g. 'public_channel,private_channel')"+ ),+ "default": "public_channel,private_channel",+ },+ "max_results": {+ "type": "integer",+ "description": "Maximum number of channels to return",+ "default": 100,+ },+ },+ "required": [],+ },+ category="communication",+ ),+ ]diff --git a/tests/connectors/test_slack_connector.py b/tests/connectors/test_slack_connector.pynew file mode 100644index 00000000..b47a341a--- /dev/null+++ b/tests/connectors/test_slack_connector.py@@ -0,0 +1,219 @@+"""Tests for SlackConnector — OAuth-authenticated Slack channel message sync.++All Slack API calls are mocked; no network access is required.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import List+from unittest.mock import patch++import pytest++from openjarvis.connectors._stubs import Document+from openjarvis.core.registry import ConnectorRegistry++# ---------------------------------------------------------------------------+# Fake API payloads+# ---------------------------------------------------------------------------++_CHANNELS_RESPONSE = {+ "channels": [+ {"id": "C001", "name": "general", "is_member": True},+ {"id": "C002", "name": "engineering", "is_member": True},+ ],+ "response_metadata": {"next_cursor": ""},+}++_HISTORY_RESPONSE = {+ "messages": [+ {+ "ts": "1710500000.000100",+ "user": "U001",+ "text": "Let's discuss the API redesign.",+ "thread_ts": "1710500000.000100",+ },+ {+ "ts": "1710500060.000200",+ "user": "U002",+ "text": "Sounds good, I'll prepare a doc.",+ },+ ],+ "has_more": False,+}++_USERS_RESPONSE = {+ "members": [+ {"id": "U001", "real_name": "Alice", "profile": {"email": "[email protected]"}},+ {"id": "U002", "real_name": "Bob", "profile": {"email": "[email protected]"}},+ ],+}+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def connector(tmp_path: Path):+ """SlackConnector pointing at a tmp credentials path (no file yet)."""+ from openjarvis.connectors.slack_connector import SlackConnector # noqa: PLC0415++ creds_path = str(tmp_path / "slack.json")+ return SlackConnector(credentials_path=creds_path)+++# ---------------------------------------------------------------------------+# Test 1 — not connected without a credentials file+# ---------------------------------------------------------------------------+++def test_not_connected_without_credentials(connector) -> None:+ """is_connected() returns False when no credentials file exists."""+ assert connector.is_connected() is False+++# ---------------------------------------------------------------------------+# Test 2 — auth_type is "oauth"+# ---------------------------------------------------------------------------+++def test_auth_type_is_oauth(connector) -> None:+ """SlackConnector.auth_type must be 'oauth'."""+ assert connector.auth_type == "oauth"+++# ---------------------------------------------------------------------------+# Test 3 — auth_url contains "slack.com"+# ---------------------------------------------------------------------------+++def test_auth_url(connector) -> None:+ """auth_url() returns a URL pointing to Slack's OAuth endpoint."""+ url = connector.auth_url()+ assert isinstance(url, str)+ assert "slack.com" in url+ assert "channels:history" in url or "channels%3Ahistory" in url+++# ---------------------------------------------------------------------------+# Test 4 — sync yields documents with correct fields (mocked API)+# ---------------------------------------------------------------------------+++@patch("openjarvis.connectors.slack_connector._slack_api_conversations_list")+@patch("openjarvis.connectors.slack_connector._slack_api_conversations_history")+@patch("openjarvis.connectors.slack_connector._slack_api_users_list")+def test_sync_yields_documents(+ mock_users,+ mock_history,+ mock_channels,+ connector,+ tmp_path: Path,+) -> None:+ """sync() yields one Document per message with correct metadata.++ With 2 channels each having 2 messages, we expect exactly 4 documents.+ """+ # Set up fake credentials so is_connected() returns True+ creds_path = Path(connector._credentials_path)+ creds_path.write_text(+ json.dumps({"token": "fake-access-token"}), encoding="utf-8"+ )++ # Configure mocks+ mock_users.return_value = _USERS_RESPONSE+ mock_channels.return_value = _CHANNELS_RESPONSE+ mock_history.return_value = _HISTORY_RESPONSE++ docs: List[Document] = list(connector.sync())++ # 2 channels × 2 messages = 4 documents+ assert len(docs) == 4++ # Verify all docs have correct source and doc_type+ for doc in docs:+ assert doc.source == "slack"+ assert doc.doc_type == "message"++ # Check a specific document from #general+ doc_c001 = next(+ (d for d in docs if d.doc_id == "slack:C001:1710500000.000100"), None+ )+ assert doc_c001 is not None+ assert doc_c001.title == "#general"+ assert doc_c001.author == "Alice"+ assert doc_c001.content == "Let's discuss the API redesign."+ assert doc_c001.thread_id == "1710500000.000100"+ assert doc_c001.metadata["channel_id"] == "C001"+ assert doc_c001.metadata["channel_name"] == "general"++ # Check a specific document from #engineering+ doc_c002 = next(+ (d for d in docs if d.doc_id == "slack:C002:1710500060.000200"), None+ )+ assert doc_c002 is not None+ assert doc_c002.title == "#engineering"+ assert doc_c002.author == "Bob"+ assert doc_c002.content == "Sounds good, I'll prepare a doc."+ assert doc_c002.thread_id is None++ # Verify the API was called correctly+ mock_users.assert_called_once()+ assert mock_channels.call_count == 1+ # conversations.history called once per channel (2 channels)+ assert mock_history.call_count == 2+++# ---------------------------------------------------------------------------+# Test 5 — disconnect removes the credentials file+# ---------------------------------------------------------------------------+++def test_disconnect(connector, tmp_path: Path) -> None:+ """disconnect() deletes the credentials file."""+ creds_path = Path(connector._credentials_path)+ creds_path.write_text(+ json.dumps({"token": "fake-access-token"}), encoding="utf-8"+ )+ assert connector.is_connected() is True++ connector.disconnect()++ assert not creds_path.exists()+ assert connector.is_connected() is False+++# ---------------------------------------------------------------------------+# Test 6 — mcp_tools returns the three expected tool specs+# ---------------------------------------------------------------------------+++def test_mcp_tools(connector) -> None:+ """mcp_tools() returns exactly 3 tools with the required names."""+ tools = connector.mcp_tools()+ names = {t.name for t in tools}+ assert len(tools) == 3+ assert "slack_search_messages" in names+ assert "slack_get_thread" in names+ assert "slack_list_channels" in names+++# ---------------------------------------------------------------------------+# Test 7 — ConnectorRegistry contains "slack" after import+# ---------------------------------------------------------------------------+++def test_registry() -> None:+ """SlackConnector can be registered and retrieved via ConnectorRegistry."""+ from openjarvis.connectors.slack_connector import SlackConnector # noqa: PLC0415++ # The registry is cleared before each test by the autouse conftest fixture,+ # so we imperatively re-register here (same pattern as test_gmail.py).+ ConnectorRegistry.register_value("slack", SlackConnector)+ assert ConnectorRegistry.contains("slack")+ cls = ConnectorRegistry.get("slack")+ assert cls.connector_id == "slack"