Personal AI, On Personal Devices
Python
feat: add Google Contacts connector with People API sync
krypticmouseeb339294cb16
diff --git a/src/openjarvis/connectors/__init__.py b/src/openjarvis/connectors/__init__.pyindex 4b5fae08..6d9bfb53 100644--- a/src/openjarvis/connectors/__init__.py+++ b/src/openjarvis/connectors/__init__.py@@ -32,3 +32,8 @@ try:import openjarvis.connectors.granola # noqa: F401except ImportError:pass++try:+ import openjarvis.connectors.gcontacts # noqa: F401+except ImportError:+ passdiff --git a/src/openjarvis/connectors/gcontacts.py b/src/openjarvis/connectors/gcontacts.pynew file mode 100644index 00000000..22ca843a--- /dev/null+++ b/src/openjarvis/connectors/gcontacts.py@@ -0,0 +1,329 @@+"""Google Contacts connector — bulk contact sync via the People REST API v1.++Uses OAuth 2.0 tokens stored locally (see :mod:`openjarvis.connectors.oauth`).+All network calls are isolated in module-level functions (``_gcontacts_api_*``)+to make them trivially mockable in tests.+"""++from __future__ import annotations++from datetime import datetime+from typing import Any, Dict, Iterator, List, Optional++import httpx++from openjarvis.connectors._stubs import BaseConnector, Document, SyncStatus+from openjarvis.connectors.oauth import (+ build_google_auth_url,+ 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+# ---------------------------------------------------------------------------++_GCONTACTS_API_BASE = "https://people.googleapis.com/v1"+_GCONTACTS_SCOPE = "https://www.googleapis.com/auth/contacts.readonly"+_DEFAULT_CREDENTIALS_PATH = str(DEFAULT_CONFIG_DIR / "connectors" / "gcontacts.json")++# ---------------------------------------------------------------------------+# Module-level API functions (easy to patch in tests)+# ---------------------------------------------------------------------------+++def _gcontacts_api_list(+ token: str,+ *,+ page_token: Optional[str] = None,+) -> Dict[str, Any]:+ """Call the People API ``people/me/connections`` endpoint.++ Parameters+ ----------+ token:+ OAuth access token.+ page_token:+ Pagination token from a previous response's ``nextPageToken``.++ Returns+ -------+ dict+ Raw API response containing a ``connections`` list and optional+ ``nextPageToken``.+ """+ params: Dict[str, Any] = {+ "personFields": "names,emailAddresses,phoneNumbers,organizations",+ "pageSize": 100,+ }+ if page_token:+ params["pageToken"] = page_token++ resp = httpx.get(+ f"{_GCONTACTS_API_BASE}/people/me/connections",+ headers={"Authorization": f"Bearer {token}"},+ params=params,+ timeout=30.0,+ )+ resp.raise_for_status()+ return resp.json()+++# ---------------------------------------------------------------------------+# Helper functions+# ---------------------------------------------------------------------------+++def _format_contact(person: Dict[str, Any]) -> str:+ """Return a human-readable text representation of a contact.++ Parameters+ ----------+ person:+ Raw person resource dict from the People API.++ Returns+ -------+ str+ Multi-line formatted text suitable for indexing.+ """+ lines: List[str] = []++ # Name+ names: List[Dict[str, Any]] = person.get("names", [])+ display_name = names[0].get("displayName", "") if names else ""+ if display_name:+ lines.append(f"Name: {display_name}")++ # Email addresses+ email_addresses: List[Dict[str, Any]] = person.get("emailAddresses", [])+ for email_entry in email_addresses:+ value = email_entry.get("value", "")+ if value:+ lines.append(f"Email: {value}")++ # Phone numbers+ phone_numbers: List[Dict[str, Any]] = person.get("phoneNumbers", [])+ for phone_entry in phone_numbers:+ value = phone_entry.get("value", "")+ if value:+ lines.append(f"Phone: {value}")++ # Organizations+ organizations: List[Dict[str, Any]] = person.get("organizations", [])+ for org_entry in organizations:+ org_name = org_entry.get("name", "")+ title = org_entry.get("title", "")+ if org_name:+ lines.append(f"Organization: {org_name}")+ if title:+ lines.append(f"Title: {title}")++ return "\n".join(lines)+++# ---------------------------------------------------------------------------+# GContactsConnector+# ---------------------------------------------------------------------------++[email protected]("gcontacts")+class GContactsConnector(BaseConnector):+ """Connector that syncs contacts from Google Contacts via the People API v1.++ Authentication is handled through Google 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/gcontacts.json``.+ """++ connector_id = "gcontacts"+ display_name = "Google Contacts"+ 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+ # Accept any non-empty dict that contains at least one key+ # (simplified: real impl would also check expiry / refresh token)+ return bool(tokens)++ def disconnect(self) -> None:+ """Delete the stored credentials file."""+ delete_tokens(self._credentials_path)++ def auth_url(self) -> str:+ """Return a Google OAuth consent URL requesting ``contacts.readonly`` scope."""+ return build_google_auth_url(+ client_id="", # placeholder — real client_id from config+ scopes=[_GCONTACTS_SCOPE],+ )++ 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,+ ) -> Iterator[Document]:+ """Yield :class:`Document` objects for Google Contacts.++ Paginates through the people/me/connections endpoint and converts+ each person resource into a Document.++ Parameters+ ----------+ since:+ Not yet used (People API does not support server-side date filtering+ for connections).+ cursor:+ ``nextPageToken`` from a previous sync to resume pagination.+ """+ tokens = load_tokens(self._credentials_path)+ if not tokens:+ return++ token: str = tokens.get("token", tokens.get("access_token", ""))+ if not token:+ return++ page_token: Optional[str] = cursor+ synced = 0++ while True:+ list_resp = _gcontacts_api_list(token, page_token=page_token)+ connections: List[Dict[str, Any]] = list_resp.get("connections", [])++ for person in connections:+ resource_name: str = person.get("resourceName", "")+ if not resource_name:+ continue++ names: List[Dict[str, Any]] = person.get("names", [])+ display_name = names[0].get("displayName", "") if names else ""++ email_addresses: List[Dict[str, Any]] = person.get("emailAddresses", [])+ primary_email = (+ email_addresses[0].get("value", "") if email_addresses else ""+ )++ content = _format_contact(person)++ doc = Document(+ doc_id=f"gcontacts:{resource_name}",+ source="gcontacts",+ doc_type="contact",+ content=content,+ title=display_name,+ author=primary_email,+ metadata={+ "resource_name": resource_name,+ },+ )+ synced += 1+ yield doc++ next_page: Optional[str] = list_resp.get("nextPageToken")+ if not next_page:+ self._last_cursor = None+ break+ page_token = next_page+ self._last_cursor = next_page++ 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 two MCP tool specs for real-time Google Contacts queries."""+ return [+ ToolSpec(+ name="contacts_find",+ description=(+ "Search Google Contacts by name, email, or organization. "+ "Returns matching contacts with their email addresses, "+ "phone numbers, and organization details."+ ),+ parameters={+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": (+ "Search term to match against contact name, "+ "email address, or organization"+ ),+ },+ "max_results": {+ "type": "integer",+ "description": "Maximum number of contacts to return",+ "default": 20,+ },+ },+ "required": ["query"],+ },+ category="communication",+ ),+ ToolSpec(+ name="contacts_get_info",+ description=(+ "Retrieve full details for a specific Google Contact by "+ "their resource name or email address. Returns all available "+ "fields including phone numbers, organization, and title."+ ),+ parameters={+ "type": "object",+ "properties": {+ "identifier": {+ "type": "string",+ "description": (+ "Contact resource name (e.g. 'people/c123') "+ "or email address"+ ),+ },+ },+ "required": ["identifier"],+ },+ category="communication",+ ),+ ]diff --git a/tests/connectors/test_gcontacts.py b/tests/connectors/test_gcontacts.pynew file mode 100644index 00000000..a7ce6ead--- /dev/null+++ b/tests/connectors/test_gcontacts.py@@ -0,0 +1,176 @@+"""Tests for GContactsConnector — OAuth-authenticated Google Contacts sync connector.++All People 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++# ---------------------------------------------------------------------------+# Helpers — fake API payloads+# ---------------------------------------------------------------------------++_CONNECTIONS_RESPONSE = {+ "connections": [+ {+ "resourceName": "people/c1",+ "names": [{"displayName": "Alice Smith"}],+ "emailAddresses": [{"value": "[email protected]"}],+ "phoneNumbers": [{"value": "+1-555-0100"}],+ "organizations": [{"name": "Acme Corp", "title": "VP Engineering"}],+ },+ {+ "resourceName": "people/c2",+ "names": [{"displayName": "Bob Jones"}],+ "emailAddresses": [{"value": "[email protected]"}],+ "phoneNumbers": [],+ "organizations": [{"name": "Acme Corp", "title": "Designer"}],+ },+ ],+ "nextPageToken": None,+}+++def _make_credentials(tmp_path: Path) -> Path:+ """Write a minimal fake credentials file and return its path."""+ creds = tmp_path / "gcontacts.json"+ creds.write_text(json.dumps({"token": "fake-access-token"}), encoding="utf-8")+ return creds+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def connector(tmp_path: Path):+ """GContactsConnector pointing at a tmp credentials path (no file yet)."""+ from openjarvis.connectors.gcontacts import GContactsConnector # noqa: PLC0415++ creds_path = str(tmp_path / "gcontacts.json")+ return GContactsConnector(credentials_path=creds_path)+++# ---------------------------------------------------------------------------+# Test 1 — not connected without a credentials file+# ---------------------------------------------------------------------------+++def test_not_connected(connector) -> None:+ """is_connected() returns False when no credentials file exists."""+ assert connector.is_connected() is False+++# ---------------------------------------------------------------------------+# Test 2 — auth_url contains contacts.readonly scope+# ---------------------------------------------------------------------------+++def test_auth_url(connector) -> None:+ """auth_url() returns a URL to Google's OAuth endpoint with contacts scope."""+ url = connector.auth_url()+ assert isinstance(url, str)+ assert url.startswith("https://accounts.google.com/o/oauth2/v2/auth")+ assert "contacts.readonly" in url+++# ---------------------------------------------------------------------------+# Test 3 — sync yields contacts with correct fields (mocked API)+# ---------------------------------------------------------------------------+++@patch("openjarvis.connectors.gcontacts._gcontacts_api_list")+def test_sync_yields_contacts(+ mock_list,+ connector,+ tmp_path: Path,+) -> None:+ """sync() yields one Document per contact with correct metadata."""+ # 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 mock+ mock_list.return_value = _CONNECTIONS_RESPONSE++ docs: List[Document] = list(connector.sync())++ assert len(docs) == 2++ # --- Contact 1: Alice ---+ doc1 = next(d for d in docs if d.doc_id == "gcontacts:people/c1")+ assert doc1.source == "gcontacts"+ assert doc1.doc_type == "contact"+ assert doc1.title == "Alice Smith"+ assert doc1.author == "[email protected]"+ assert "[email protected]" in doc1.content+ assert "Acme Corp" in doc1.content++ # --- Contact 2: Bob ---+ doc2 = next(d for d in docs if d.doc_id == "gcontacts:people/c2")+ assert doc2.doc_type == "contact"+ assert doc2.title == "Bob Jones"+ assert doc2.author == "[email protected]"+ assert "[email protected]" in doc2.content+ assert "Acme Corp" in doc2.content++ # Verify the API was called once (single page, no nextPageToken)+ mock_list.assert_called_once()+++# ---------------------------------------------------------------------------+# Test 4 — 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 5 — mcp_tools returns the two expected tool specs+# ---------------------------------------------------------------------------+++def test_mcp_tools(connector) -> None:+ """mcp_tools() returns exactly 2 tools with the required names."""+ tools = connector.mcp_tools()+ names = {t.name for t in tools}+ assert len(tools) == 2+ assert "contacts_find" in names+ assert "contacts_get_info" in names+++# ---------------------------------------------------------------------------+# Test 6 — ConnectorRegistry contains "gcontacts" after import+# ---------------------------------------------------------------------------+++def test_registry() -> None:+ """GContactsConnector can be registered and retrieved via ConnectorRegistry."""+ from openjarvis.connectors.gcontacts import GContactsConnector # noqa: PLC0415++ # The registry is cleared before each test by the autouse conftest fixture,+ # so we imperatively re-register here (same pattern as test_gcalendar.py).+ ConnectorRegistry.register_value("gcontacts", GContactsConnector)+ assert ConnectorRegistry.contains("gcontacts")+ cls = ConnectorRegistry.get("gcontacts")+ assert cls.connector_id == "gcontacts"