Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(blocks): add NotionReadPage block (#10760)

Aayush Shahddff09a8e401
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.default
index c20eef0893..a00af85724 100644
--- a/autogpt_platform/backend/.env.default
+++ b/autogpt_platform/backend/.env.default
@@ -66,6 +66,11 @@ NVIDIA_API_KEY=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
+# Notion OAuth App server credentials - https://developers.notion.com/docs/authorization
+# Configure a public integration
+NOTION_CLIENT_ID=
+NOTION_CLIENT_SECRET=
+
# Google OAuth App server credentials - https://console.cloud.google.com/apis/credentials, and enable gmail api and set scopes
# https://console.cloud.google.com/apis/credentials/consent ?project=<your_project_id>
# You'll need to add/enable the following scopes (minimum):
diff --git a/autogpt_platform/backend/backend/blocks/notion/_api.py b/autogpt_platform/backend/backend/blocks/notion/_api.py
new file mode 100644
index 0000000000..5647f540db
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/notion/_api.py
@@ -0,0 +1,536 @@
+"""
+Notion API helper functions and client for making authenticated requests.
+"""
+
+from typing import Any, Dict, List, Optional
+
+from backend.data.model import OAuth2Credentials
+from backend.util.request import Requests
+
+NOTION_VERSION = "2022-06-28"
+
+
+class NotionAPIException(Exception):
+ """Exception raised for Notion API errors."""
+
+ def __init__(self, message: str, status_code: int):
+ super().__init__(message)
+ self.status_code = status_code
+
+
+class NotionClient:
+ """Client for interacting with the Notion API."""
+
+ def __init__(self, credentials: OAuth2Credentials):
+ self.credentials = credentials
+ self.headers = {
+ "Authorization": credentials.auth_header(),
+ "Notion-Version": NOTION_VERSION,
+ "Content-Type": "application/json",
+ }
+ self.requests = Requests()
+
+ async def get_page(self, page_id: str) -> dict:
+ """
+ Fetch a page by ID.
+
+ Args:
+ page_id: The ID of the page to fetch.
+
+ Returns:
+ The page object from Notion API.
+ """
+ url = f"https://api.notion.com/v1/pages/{page_id}"
+ response = await self.requests.get(url, headers=self.headers)
+
+ if not response.ok:
+ raise NotionAPIException(
+ f"Failed to fetch page: {response.status} - {response.text()}",
+ response.status,
+ )
+
+ return response.json()
+
+ async def get_blocks(self, block_id: str, recursive: bool = True) -> List[dict]:
+ """
+ Fetch all blocks from a page or block.
+
+ Args:
+ block_id: The ID of the page or block to fetch children from.
+ recursive: Whether to fetch nested blocks recursively.
+
+ Returns:
+ List of block objects.
+ """
+ blocks = []
+ cursor = None
+
+ while True:
+ url = f"https://api.notion.com/v1/blocks/{block_id}/children"
+ params = {"page_size": 100}
+ if cursor:
+ params["start_cursor"] = cursor
+
+ response = await self.requests.get(url, headers=self.headers, params=params)
+
+ if not response.ok:
+ raise NotionAPIException(
+ f"Failed to fetch blocks: {response.status} - {response.text()}",
+ response.status,
+ )
+
+ data = response.json()
+ current_blocks = data.get("results", [])
+
+ # If recursive, fetch children for blocks that have them
+ if recursive:
+ for block in current_blocks:
+ if block.get("has_children"):
+ block["children"] = await self.get_blocks(
+ block["id"], recursive=True
+ )
+
+ blocks.extend(current_blocks)
+
+ if not data.get("has_more"):
+ break
+ cursor = data.get("next_cursor")
+
+ return blocks
+
+ async def query_database(
+ self,
+ database_id: str,
+ filter_obj: Optional[dict] = None,
+ sorts: Optional[List[dict]] = None,
+ page_size: int = 100,
+ ) -> dict:
+ """
+ Query a database with optional filters and sorts.
+
+ Args:
+ database_id: The ID of the database to query.
+ filter_obj: Optional filter object for the query.
+ sorts: Optional list of sort objects.
+ page_size: Number of results per page.
+
+ Returns:
+ Query results including pages and pagination info.
+ """
+ url = f"https://api.notion.com/v1/databases/{database_id}/query"
+
+ payload: Dict[str, Any] = {"page_size": page_size}
+ if filter_obj:
+ payload["filter"] = filter_obj
+ if sorts:
+ payload["sorts"] = sorts
+
+ response = await self.requests.post(url, headers=self.headers, json=payload)
+
+ if not response.ok:
+ raise NotionAPIException(
+ f"Failed to query database: {response.status} - {response.text()}",
+ response.status,
+ )
+
+ return response.json()
+
+ async def create_page(
+ self,
+ parent: dict,
+ properties: dict,
+ children: Optional[List[dict]] = None,
+ icon: Optional[dict] = None,
+ cover: Optional[dict] = None,
+ ) -> dict:
+ """
+ Create a new page.
+
+ Args:
+ parent: Parent object (page_id or database_id).
+ properties: Page properties.
+ children: Optional list of block children.
+ icon: Optional icon object.
+ cover: Optional cover object.
+
+ Returns:
+ The created page object.
+ """
+ url = "https://api.notion.com/v1/pages"
+
+ payload: Dict[str, Any] = {"parent": parent, "properties": properties}
+
+ if children:
+ payload["children"] = children
+ if icon:
+ payload["icon"] = icon
+ if cover:
+ payload["cover"] = cover
+
+ response = await self.requests.post(url, headers=self.headers, json=payload)
+
+ if not response.ok:
+ raise NotionAPIException(
+ f"Failed to create page: {response.status} - {response.text()}",
+ response.status,
+ )
+
+ return response.json()
+
+ async def update_page(self, page_id: str, properties: dict) -> dict:
+ """
+ Update a page's properties.
+
+ Args:
+ page_id: The ID of the page to update.
+ properties: Properties to update.
+
+ Returns:
+ The updated page object.
+ """
+ url = f"https://api.notion.com/v1/pages/{page_id}"
+
+ response = await self.requests.patch(
+ url, headers=self.headers, json={"properties": properties}
+ )
+
+ if not response.ok:
+ raise NotionAPIException(
+ f"Failed to update page: {response.status} - {response.text()}",
+ response.status,
+ )
+
+ return response.json()
+
+ async def append_blocks(self, block_id: str, children: List[dict]) -> dict:
+ """
+ Append blocks to a page or block.
+
+ Args:
+ block_id: The ID of the page or block to append to.
+ children: List of block objects to append.
+
+ Returns:
+ Response with the created blocks.
+ """
+ url = f"https://api.notion.com/v1/blocks/{block_id}/children"
+
+ response = await self.requests.patch(
+ url, headers=self.headers, json={"children": children}
+ )
+
+ if not response.ok:
+ raise NotionAPIException(
+ f"Failed to append blocks: {response.status} - {response.text()}",
+ response.status,
+ )
+
+ return response.json()
+
+ async def search(
+ self,
+ query: str = "",
+ filter_obj: Optional[dict] = None,
+ sort: Optional[dict] = None,
+ page_size: int = 100,
+ ) -> dict:
+ """
+ Search for pages and databases.
+
+ Args:
+ query: Search query text.
+ filter_obj: Optional filter object.
+ sort: Optional sort object.
+ page_size: Number of results per page.
+
+ Returns:
+ Search results.
+ """
+ url = "https://api.notion.com/v1/search"
+
+ payload: Dict[str, Any] = {"page_size": page_size}
+ if query:
+ payload["query"] = query
+ if filter_obj:
+ payload["filter"] = filter_obj
+ if sort:
+ payload["sort"] = sort
+
+ response = await self.requests.post(url, headers=self.headers, json=payload)
+
+ if not response.ok:
+ raise NotionAPIException(
+ f"Search failed: {response.status} - {response.text()}", response.status
+ )
+
+ return response.json()
+
+
+# Conversion helper functions
+
+
+def parse_rich_text(rich_text_array: List[dict]) -> str:
+ """
+ Extract plain text from a Notion rich text array.
+
+ Args:
+ rich_text_array: Array of rich text objects from Notion.
+
+ Returns:
+ Plain text string.
+ """
+ if not rich_text_array:
+ return ""
+
+ text_parts = []
+ for text_obj in rich_text_array:
+ if "plain_text" in text_obj:
+ text_parts.append(text_obj["plain_text"])
+
+ return "".join(text_parts)
+
+
+def rich_text_to_markdown(rich_text_array: List[dict]) -> str:
+ """
+ Convert Notion rich text array to markdown with formatting.
+
+ Args:
+ rich_text_array: Array of rich text objects from Notion.
+
+ Returns:
+ Markdown formatted string.
+ """
+ if not rich_text_array:
+ return ""
+
+ markdown_parts = []
+
+ for text_obj in rich_text_array:
+ text = text_obj.get("plain_text", "")
+ annotations = text_obj.get("annotations", {})
+
+ # Apply formatting based on annotations
+ if annotations.get("code"):
+ text = f"`{text}`"
+ else:
+ if annotations.get("bold"):
+ text = f"**{text}**"
+ if annotations.get("italic"):
+ text = f"*{text}*"
+ if annotations.get("strikethrough"):
+ text = f"~~{text}~~"
+ if annotations.get("underline"):
+ text = f"<u>{text}</u>"
+
+ # Handle links
+ if text_obj.get("href"):
+ text = f"[{text}]({text_obj['href']})"
+
+ markdown_parts.append(text)
+
+ return "".join(markdown_parts)
+
+
+def block_to_markdown(block: dict, indent_level: int = 0) -> str:
+ """
+ Convert a single Notion block to markdown.
+
+ Args:
+ block: Block object from Notion API.
+ indent_level: Current indentation level for nested blocks.
+
+ Returns:
+ Markdown string representation of the block.
+ """
+ block_type = block.get("type")
+ indent = " " * indent_level
+ markdown_lines = []
+
+ # Handle different block types
+ if block_type == "paragraph":
+ text = rich_text_to_markdown(block["paragraph"].get("rich_text", []))
+ if text:
+ markdown_lines.append(f"{indent}{text}")
+
+ elif block_type == "heading_1":
+ text = parse_rich_text(block["heading_1"].get("rich_text", []))
+ markdown_lines.append(f"{indent}# {text}")
+
+ elif block_type == "heading_2":
+ text = parse_rich_text(block["heading_2"].get("rich_text", []))
+ markdown_lines.append(f"{indent}## {text}")
+
+ elif block_type == "heading_3":
+ text = parse_rich_text(block["heading_3"].get("rich_text", []))
+ markdown_lines.append(f"{indent}### {text}")
+
+ elif block_type == "bulleted_list_item":
+ text = rich_text_to_markdown(block["bulleted_list_item"].get("rich_text", []))
+ markdown_lines.append(f"{indent}- {text}")
+
+ elif block_type == "numbered_list_item":
+ text = rich_text_to_markdown(block["numbered_list_item"].get("rich_text", []))
+ # Note: This is simplified - proper numbering would need context
+ markdown_lines.append(f"{indent}1. {text}")
+
+ elif block_type == "to_do":
+ text = rich_text_to_markdown(block["to_do"].get("rich_text", []))
+ checked = "x" if block["to_do"].get("checked") else " "
+ markdown_lines.append(f"{indent}- [{checked}] {text}")
+
+ elif block_type == "toggle":
+ text = rich_text_to_markdown(block["toggle"].get("rich_text", []))
+ markdown_lines.append(f"{indent}<details>")
+ markdown_lines.append(f"{indent}<summary>{text}</summary>")
+ markdown_lines.append(f"{indent}")
+ # Process children if they exist
+ if block.get("children"):
+ for child in block["children"]:
+ child_markdown = block_to_markdown(child, indent_level + 1)
+ if child_markdown:
+ markdown_lines.append(child_markdown)
+ markdown_lines.append(f"{indent}</details>")
+
+ elif block_type == "code":
+ code = parse_rich_text(block["code"].get("rich_text", []))
+ language = block["code"].get("language", "")
+ markdown_lines.append(f"{indent}```{language}")
+ markdown_lines.append(f"{indent}{code}")
+ markdown_lines.append(f"{indent}```")
+
+ elif block_type == "quote":
+ text = rich_text_to_markdown(block["quote"].get("rich_text", []))
+ markdown_lines.append(f"{indent}> {text}")
+
+ elif block_type == "divider":
+ markdown_lines.append(f"{indent}---")
+
+ elif block_type == "image":
+ image = block["image"]
+ url = image.get("external", {}).get("url") or image.get("file", {}).get(
+ "url", ""
+ )
+ caption = parse_rich_text(image.get("caption", []))
+ alt_text = caption if caption else "Image"
+ markdown_lines.append(f"{indent}![{alt_text}]({url})")
+ if caption:
+ markdown_lines.append(f"{indent}*{caption}*")
+
+ elif block_type == "video":
+ video = block["video"]
+ url = video.get("external", {}).get("url") or video.get("file", {}).get(
+ "url", ""
+ )
+ caption = parse_rich_text(video.get("caption", []))
+ markdown_lines.append(f"{indent}[Video]({url})")
+ if caption:
+ markdown_lines.append(f"{indent}*{caption}*")
+
+ elif block_type == "file":
+ file = block["file"]
+ url = file.get("external", {}).get("url") or file.get("file", {}).get("url", "")
+ caption = parse_rich_text(file.get("caption", []))
+ name = caption if caption else "File"
+ markdown_lines.append(f"{indent}[{name}]({url})")
+
+ elif block_type == "bookmark":
+ url = block["bookmark"].get("url", "")
+ caption = parse_rich_text(block["bookmark"].get("caption", []))
+ markdown_lines.append(f"{indent}[{caption if caption else url}]({url})")
+
+ elif block_type == "equation":
+ expression = block["equation"].get("expression", "")
+ markdown_lines.append(f"{indent}$${expression}$$")
+
+ elif block_type == "callout":
+ text = rich_text_to_markdown(block["callout"].get("rich_text", []))
+ icon = block["callout"].get("icon", {})
+ if icon.get("emoji"):
+ markdown_lines.append(f"{indent}> {icon['emoji']} {text}")
+ else:
+ markdown_lines.append(f"{indent}> ℹ️ {text}")
+
+ elif block_type == "child_page":
+ title = block["child_page"].get("title", "Untitled")
+ markdown_lines.append(f"{indent}📄 [{title}](notion://page/{block['id']})")
+
+ elif block_type == "child_database":
+ title = block["child_database"].get("title", "Untitled Database")
+ markdown_lines.append(f"{indent}🗂️ [{title}](notion://database/{block['id']})")
+
+ elif block_type == "table":
+ # Tables are complex - for now just indicate there's a table
+ markdown_lines.append(
+ f"{indent}[Table with {block['table'].get('table_width', 0)} columns]"
+ )
+
+ elif block_type == "column_list":
+ # Process columns
+ if block.get("children"):
+ markdown_lines.append(f"{indent}<div style='display: flex'>")
+ for column in block["children"]:
+ markdown_lines.append(f"{indent}<div style='flex: 1'>")
+ if column.get("children"):
+ for child in column["children"]:
+ child_markdown = block_to_markdown(child, indent_level + 1)
+ if child_markdown:
+ markdown_lines.append(child_markdown)
+ markdown_lines.append(f"{indent}</div>")
+ markdown_lines.append(f"{indent}</div>")
+
+ # Handle children for blocks that haven't been processed yet
+ elif block.get("children") and block_type not in ["toggle", "column_list"]:
+ for child in block["children"]:
+ child_markdown = block_to_markdown(child, indent_level)
+ if child_markdown:
+ markdown_lines.append(child_markdown)
+
+ return "\n".join(markdown_lines) if markdown_lines else ""
+
+
+def blocks_to_markdown(blocks: List[dict]) -> str:
+ """
+ Convert a list of Notion blocks to a markdown document.
+
+ Args:
+ blocks: List of block objects from Notion API.
+
+ Returns:
+ Complete markdown document as a string.
+ """
+ markdown_parts = []
+
+ for i, block in enumerate(blocks):
+ markdown = block_to_markdown(block)
+ if markdown:
+ markdown_parts.append(markdown)
+ # Add spacing between top-level blocks (except lists)
+ if i < len(blocks) - 1:
+ next_type = blocks[i + 1].get("type", "")
+ current_type = block.get("type", "")
+ # Don't add extra spacing between list items
+ list_types = {"bulleted_list_item", "numbered_list_item", "to_do"}
+ if not (current_type in list_types and next_type in list_types):
+ markdown_parts.append("")
+
+ return "\n".join(markdown_parts)
+
+
+def extract_page_title(page: dict) -> str:
+ """
+ Extract the title from a Notion page object.
+
+ Args:
+ page: Page object from Notion API.
+
+ Returns:
+ Page title as a string.
+ """
+ properties = page.get("properties", {})
+
+ # Find the title property (it has type "title")
+ for prop_name, prop_value in properties.items():
+ if prop_value.get("type") == "title":
+ return parse_rich_text(prop_value.get("title", []))
+
+ return "Untitled"
diff --git a/autogpt_platform/backend/backend/blocks/notion/_auth.py b/autogpt_platform/backend/backend/blocks/notion/_auth.py
new file mode 100644
index 0000000000..1c367525db
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/notion/_auth.py
@@ -0,0 +1,42 @@
+from typing import Literal
+
+from pydantic import SecretStr
+
+from backend.data.model import CredentialsField, CredentialsMetaInput, OAuth2Credentials
+from backend.integrations.providers import ProviderName
+from backend.util.settings import Secrets
+
+secrets = Secrets()
+NOTION_OAUTH_IS_CONFIGURED = bool(
+ secrets.notion_client_id and secrets.notion_client_secret
+)
+
+NotionCredentials = OAuth2Credentials
+NotionCredentialsInput = CredentialsMetaInput[
+ Literal[ProviderName.NOTION], Literal["oauth2"]
+]
+
+
+def NotionCredentialsField() -> NotionCredentialsInput:
+ """Creates a Notion OAuth2 credentials field."""
+ return CredentialsField(
+ description="Connect your Notion account. Ensure the pages/databases are shared with the integration."
+ )
+
+
+# Test credentials for Notion OAuth2
+TEST_CREDENTIALS = OAuth2Credentials(
+ id="01234567-89ab-cdef-0123-456789abcdef",
+ provider="notion",
+ access_token=SecretStr("test_access_token"),
+ title="Mock Notion OAuth",
+ scopes=["read_content", "insert_content", "update_content"],
+ username="testuser",
+)
+
+TEST_CREDENTIALS_INPUT = {
+ "provider": TEST_CREDENTIALS.provider,
+ "id": TEST_CREDENTIALS.id,
+ "type": TEST_CREDENTIALS.type,
+ "title": TEST_CREDENTIALS.title,
+}
diff --git a/autogpt_platform/backend/backend/blocks/notion/create_page.py b/autogpt_platform/backend/backend/blocks/notion/create_page.py
new file mode 100644
index 0000000000..cd7a259c40
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/notion/create_page.py
@@ -0,0 +1,360 @@
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+from pydantic import model_validator
+
+from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema
+from backend.data.model import OAuth2Credentials, SchemaField
+
+from ._api import NotionClient
+from ._auth import (
+ NOTION_OAUTH_IS_CONFIGURED,
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ NotionCredentialsField,
+ NotionCredentialsInput,
+)
+
+
+class NotionCreatePageBlock(Block):
+ """Create a new page in Notion with content."""
+
+ class Input(BlockSchema):
+ credentials: NotionCredentialsInput = NotionCredentialsField()
+ parent_page_id: Optional[str] = SchemaField(
+ description="Parent page ID to create the page under. Either this OR parent_database_id is required.",
+ default=None,
+ )
+ parent_database_id: Optional[str] = SchemaField(
+ description="Parent database ID to create the page in. Either this OR parent_page_id is required.",
+ default=None,
+ )
+ title: str = SchemaField(
+ description="Title of the new page",
+ )
+ content: Optional[str] = SchemaField(
+ description="Content for the page. Can be plain text or markdown - will be converted to Notion blocks.",
+ default=None,
+ )
+ properties: Optional[Dict[str, Any]] = SchemaField(
+ description="Additional properties for database pages (e.g., {'Status': 'In Progress', 'Priority': 'High'})",
+ default=None,
+ )
+ icon_emoji: Optional[str] = SchemaField(
+ description="Emoji to use as the page icon (e.g., '📄', '🚀')", default=None
+ )
+
+ @model_validator(mode="after")
+ def validate_parent(self):
+ """Ensure either parent_page_id or parent_database_id is provided."""
+ if not self.parent_page_id and not self.parent_database_id:
+ raise ValueError(
+ "Either parent_page_id or parent_database_id must be provided"
+ )
+ if self.parent_page_id and self.parent_database_id:
+ raise ValueError(
+ "Only one of parent_page_id or parent_database_id should be provided, not both"
+ )
+ return self
+
+ class Output(BlockSchema):
+ page_id: str = SchemaField(description="ID of the created page.")
+ page_url: str = SchemaField(description="URL of the created page.")
+ error: str = SchemaField(description="Error message if the operation failed.")
+
+ def __init__(self):
+ super().__init__(
+ id="c15febe0-66ce-4c6f-aebd-5ab351653804",
+ description="Create a new page in Notion. Requires EITHER a parent_page_id OR parent_database_id. Supports markdown content.",
+ categories={BlockCategory.PRODUCTIVITY},
+ input_schema=NotionCreatePageBlock.Input,
+ output_schema=NotionCreatePageBlock.Output,
+ disabled=not NOTION_OAUTH_IS_CONFIGURED,
+ test_input={
+ "parent_page_id": "00000000-0000-0000-0000-000000000000",
+ "title": "Test Page",
+ "content": "This is test content.",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_output=[
+ ("page_id", "12345678-1234-1234-1234-123456789012"),
+ (
+ "page_url",
+ "https://notion.so/Test-Page-12345678123412341234123456789012",
+ ),
+ ],
+ test_credentials=TEST_CREDENTIALS,
+ test_mock={
+ "create_page": lambda *args, **kwargs: (
+ "12345678-1234-1234-1234-123456789012",
+ "https://notion.so/Test-Page-12345678123412341234123456789012",
+ )
+ },
+ )
+
+ @staticmethod
+ def _markdown_to_blocks(content: str) -> List[dict]:
+ """Convert markdown content to Notion block objects."""
+ if not content:
+ return []
+
+ blocks = []
+ lines = content.split("\n")
+ i = 0
+
+ while i < len(lines):
+ line = lines[i]
+
+ # Skip empty lines
+ if not line.strip():
+ i += 1
+ continue
+
+ # Headings
+ if line.startswith("### "):
+ blocks.append(
+ {
+ "type": "heading_3",
+ "heading_3": {
+ "rich_text": [
+ {"type": "text", "text": {"content": line[4:].strip()}}
+ ]
+ },
+ }
+ )
+ elif line.startswith("## "):
+ blocks.append(
+ {
+ "type": "heading_2",
+ "heading_2": {
+ "rich_text": [
+ {"type": "text", "text": {"content": line[3:].strip()}}
+ ]
+ },
+ }
+ )
+ elif line.startswith("# "):
+ blocks.append(
+ {
+ "type": "heading_1",
+ "heading_1": {
+ "rich_text": [
+ {"type": "text", "text": {"content": line[2:].strip()}}
+ ]
+ },
+ }
+ )
+ # Bullet points
+ elif line.strip().startswith("- "):
+ blocks.append(
+ {
+ "type": "bulleted_list_item",
+ "bulleted_list_item": {
+ "rich_text": [
+ {
+ "type": "text",
+ "text": {"content": line.strip()[2:].strip()},
+ }
+ ]
+ },
+ }
+ )
+ # Numbered list
+ elif line.strip() and line.strip()[0].isdigit() and ". " in line:
+ content_start = line.find(". ") + 2
+ blocks.append(
+ {
+ "type": "numbered_list_item",
+ "numbered_list_item": {
+ "rich_text": [
+ {
+ "type": "text",
+ "text": {"content": line[content_start:].strip()},
+ }
+ ]
+ },
+ }
+ )
+ # Code block
+ elif line.strip().startswith("```"):
+ code_lines = []
+ language = line[3:].strip() or "plain text"
+ i += 1
+ while i < len(lines) and not lines[i].strip().startswith("```"):
+ code_lines.append(lines[i])
+ i += 1
+ blocks.append(
+ {
+ "type": "code",
+ "code": {
+ "rich_text": [
+ {
+ "type": "text",
+ "text": {"content": "\n".join(code_lines)},
+ }
+ ],
+ "language": language,
+ },
+ }
+ )
+ # Quote
+ elif line.strip().startswith("> "):
+ blocks.append(
+ {
+ "type": "quote",
+ "quote": {
+ "rich_text": [
+ {
+ "type": "text",
+ "text": {"content": line.strip()[2:].strip()},
+ }
+ ]
+ },
+ }
+ )
+ # Horizontal rule
+ elif line.strip() in ["---", "***", "___"]:
+ blocks.append({"type": "divider", "divider": {}})
+ # Regular paragraph
+ else:
+ # Parse for basic markdown formatting
+ text_content = line.strip()
+ rich_text = []
+
+ # Simple bold/italic parsing (this is simplified)
+ if "**" in text_content or "*" in text_content:
+ # For now, just pass as plain text
+ # A full implementation would parse and create proper annotations
+ rich_text = [{"type": "text", "text": {"content": text_content}}]
+ else:
+ rich_text = [{"type": "text", "text": {"content": text_content}}]
+
+ blocks.append(
+ {"type": "paragraph", "paragraph": {"rich_text": rich_text}}
+ )
+
+ i += 1
+
+ return blocks
+
+ @staticmethod
+ def _build_properties(
+ title: str, additional_properties: Optional[Dict[str, Any]] = None
+ ) -> Dict[str, Any]:
+ """Build properties object for page creation."""
+ properties: Dict[str, Any] = {
+ "title": {"title": [{"type": "text", "text": {"content": title}}]}
+ }
+
+ if additional_properties:
+ for key, value in additional_properties.items():
+ if key.lower() == "title":
+ continue # Skip title as we already have it
+
+ # Try to intelligently map property types
+ if isinstance(value, bool):
+ properties[key] = {"checkbox": value}
+ elif isinstance(value, (int, float)):
+ properties[key] = {"number": value}
+ elif isinstance(value, list):
+ # Assume multi-select
+ properties[key] = {
+ "multi_select": [{"name": str(item)} for item in value]
+ }
+ elif isinstance(value, str):
+ # Could be select, rich_text, or other types
+ # For simplicity, try common patterns
+ if key.lower() in ["status", "priority", "type", "category"]:
+ properties[key] = {"select": {"name": value}}
+ elif key.lower() in ["url", "link"]:
+ properties[key] = {"url": value}
+ elif key.lower() in ["email"]:
+ properties[key] = {"email": value}
+ else:
+ properties[key] = {
+ "rich_text": [{"type": "text", "text": {"content": value}}]
+ }
+
+ return properties
+
+ @staticmethod
+ async def create_page(
+ credentials: OAuth2Credentials,
+ title: str,
+ parent_page_id: Optional[str] = None,
+ parent_database_id: Optional[str] = None,
+ content: Optional[str] = None,
+ properties: Optional[Dict[str, Any]] = None,
+ icon_emoji: Optional[str] = None,
+ ) -> tuple[str, str]:
+ """
+ Create a new Notion page.
+
+ Returns:
+ Tuple of (page_id, page_url)
+ """
+ if not parent_page_id and not parent_database_id:
+ raise ValueError(
+ "Either parent_page_id or parent_database_id must be provided"
+ )
+ if parent_page_id and parent_database_id:
+ raise ValueError(
+ "Only one of parent_page_id or parent_database_id should be provided, not both"
+ )
+
+ client = NotionClient(credentials)
+
+ # Build parent object
+ if parent_page_id:
+ parent = {"type": "page_id", "page_id": parent_page_id}
+ else:
+ parent = {"type": "database_id", "database_id": parent_database_id}
+
+ # Build properties
+ page_properties = NotionCreatePageBlock._build_properties(title, properties)
+
+ # Convert content to blocks if provided
+ children = None
+ if content:
+ children = NotionCreatePageBlock._markdown_to_blocks(content)
+
+ # Build icon if provided
+ icon = None
+ if icon_emoji:
+ icon = {"type": "emoji", "emoji": icon_emoji}
+
+ # Create the page
+ result = await client.create_page(
+ parent=parent, properties=page_properties, children=children, icon=icon
+ )
+
+ page_id = result.get("id", "")
+ page_url = result.get("url", "")
+
+ if not page_id or not page_url:
+ raise ValueError("Failed to get page ID or URL from Notion response")
+
+ return page_id, page_url
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: OAuth2Credentials,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ page_id, page_url = await self.create_page(
+ credentials,
+ input_data.title,
+ input_data.parent_page_id,
+ input_data.parent_database_id,
+ input_data.content,
+ input_data.properties,
+ input_data.icon_emoji,
+ )
+ yield "page_id", page_id
+ yield "page_url", page_url
+ except Exception as e:
+ yield "error", str(e) if str(e) else "Unknown error"
diff --git a/autogpt_platform/backend/backend/blocks/notion/read_database.py b/autogpt_platform/backend/backend/blocks/notion/read_database.py
new file mode 100644
index 0000000000..115842940d
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/notion/read_database.py
@@ -0,0 +1,285 @@
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional
+
+from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema
+from backend.data.model import OAuth2Credentials, SchemaField
+
+from ._api import NotionClient, parse_rich_text
+from ._auth import (
+ NOTION_OAUTH_IS_CONFIGURED,
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ NotionCredentialsField,
+ NotionCredentialsInput,
+)
+
+
+class NotionReadDatabaseBlock(Block):
+ """Query a Notion database and retrieve entries with their properties."""
+
+ class Input(BlockSchema):
+ credentials: NotionCredentialsInput = NotionCredentialsField()
+ database_id: str = SchemaField(
+ description="Notion database ID. Must be accessible by the connected integration.",
+ )
+ filter_property: Optional[str] = SchemaField(
+ description="Property name to filter by (e.g., 'Status', 'Priority')",
+ default=None,
+ )
+ filter_value: Optional[str] = SchemaField(
+ description="Value to filter for in the specified property", default=None
+ )
+ sort_property: Optional[str] = SchemaField(
+ description="Property name to sort by", default=None
+ )
+ sort_direction: Optional[str] = SchemaField(
+ description="Sort direction: 'ascending' or 'descending'",
+ default="ascending",
+ )
+ limit: int = SchemaField(
+ description="Maximum number of entries to retrieve",
+ default=100,
+ ge=1,
+ le=100,
+ )
+
+ class Output(BlockSchema):
+ entries: List[Dict[str, Any]] = SchemaField(
+ description="List of database entries with their properties."
+ )
+ entry: Dict[str, Any] = SchemaField(
+ description="Individual database entry (yields one per entry found)."
+ )
+ entry_ids: List[str] = SchemaField(
+ description="List of entry IDs for batch operations."
+ )
+ entry_id: str = SchemaField(
+ description="Individual entry ID (yields one per entry found)."
+ )
+ count: int = SchemaField(description="Number of entries retrieved.")
+ database_title: str = SchemaField(description="Title of the database.")
+ error: str = SchemaField(description="Error message if the operation failed.")
+
+ def __init__(self):
+ super().__init__(
+ id="fcd53135-88c9-4ba3-be50-cc6936286e6c",
+ description="Query a Notion database with optional filtering and sorting, returning structured entries.",
+ categories={BlockCategory.PRODUCTIVITY},
+ input_schema=NotionReadDatabaseBlock.Input,
+ output_schema=NotionReadDatabaseBlock.Output,
+ disabled=not NOTION_OAUTH_IS_CONFIGURED,
+ test_input={
+ "database_id": "00000000-0000-0000-0000-000000000000",
+ "limit": 10,
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_output=[
+ (
+ "entries",
+ [{"Name": "Test Entry", "Status": "Active", "_id": "test-123"}],
+ ),
+ ("entry_ids", ["test-123"]),
+ (
+ "entry",
+ {"Name": "Test Entry", "Status": "Active", "_id": "test-123"},
+ ),
+ ("entry_id", "test-123"),
+ ("count", 1),
+ ("database_title", "Test Database"),
+ ],
+ test_credentials=TEST_CREDENTIALS,
+ test_mock={
+ "query_database": lambda *args, **kwargs: (
+ [{"Name": "Test Entry", "Status": "Active", "_id": "test-123"}],
+ 1,
+ "Test Database",
+ )
+ },
+ )
+
+ @staticmethod
+ def _parse_property_value(prop: dict) -> Any:
+ """Parse a Notion property value into a simple Python type."""
+ prop_type = prop.get("type")
+
+ if prop_type == "title":
+ return parse_rich_text(prop.get("title", []))
+ elif prop_type == "rich_text":
+ return parse_rich_text(prop.get("rich_text", []))
+ elif prop_type == "number":
+ return prop.get("number")
+ elif prop_type == "select":
+ select = prop.get("select")
+ return select.get("name") if select else None
+ elif prop_type == "multi_select":
+ return [item.get("name") for item in prop.get("multi_select", [])]
+ elif prop_type == "date":
+ date = prop.get("date")
+ if date:
+ return date.get("start")
+ return None
+ elif prop_type == "checkbox":
+ return prop.get("checkbox", False)
+ elif prop_type == "url":
+ return prop.get("url")
+ elif prop_type == "email":
+ return prop.get("email")
+ elif prop_type == "phone_number":
+ return prop.get("phone_number")
+ elif prop_type == "people":
+ return [
+ person.get("name", person.get("id"))
+ for person in prop.get("people", [])
+ ]
+ elif prop_type == "files":
+ files = prop.get("files", [])
+ return [
+ f.get(
+ "name",
+ f.get("external", {}).get("url", f.get("file", {}).get("url")),
+ )
+ for f in files
+ ]
+ elif prop_type == "relation":
+ return [rel.get("id") for rel in prop.get("relation", [])]
+ elif prop_type == "formula":
+ formula = prop.get("formula", {})
+ return formula.get(formula.get("type"))
+ elif prop_type == "rollup":
+ rollup = prop.get("rollup", {})
+ return rollup.get(rollup.get("type"))
+ elif prop_type == "created_time":
+ return prop.get("created_time")
+ elif prop_type == "created_by":
+ return prop.get("created_by", {}).get(
+ "name", prop.get("created_by", {}).get("id")
+ )
+ elif prop_type == "last_edited_time":
+ return prop.get("last_edited_time")
+ elif prop_type == "last_edited_by":
+ return prop.get("last_edited_by", {}).get(
+ "name", prop.get("last_edited_by", {}).get("id")
+ )
+ else:
+ # Return the raw value for unknown types
+ return prop
+
+ @staticmethod
+ def _build_filter(property_name: str, value: str) -> dict:
+ """Build a simple filter object for a property."""
+ # This is a simplified filter - in reality, you'd need to know the property type
+ # For now, we'll try common filter types
+ return {
+ "or": [
+ {"property": property_name, "rich_text": {"contains": value}},
+ {"property": property_name, "title": {"contains": value}},
+ {"property": property_name, "select": {"equals": value}},
+ {"property": property_name, "multi_select": {"contains": value}},
+ ]
+ }
+
+ @staticmethod
+ async def query_database(
+ credentials: OAuth2Credentials,
+ database_id: str,
+ filter_property: Optional[str] = None,
+ filter_value: Optional[str] = None,
+ sort_property: Optional[str] = None,
+ sort_direction: str = "ascending",
+ limit: int = 100,
+ ) -> tuple[List[Dict[str, Any]], int, str]:
+ """
+ Query a Notion database and parse the results.
+
+ Returns:
+ Tuple of (entries_list, count, database_title)
+ """
+ client = NotionClient(credentials)
+
+ # Build filter if specified
+ filter_obj = None
+ if filter_property and filter_value:
+ filter_obj = NotionReadDatabaseBlock._build_filter(
+ filter_property, filter_value
+ )
+
+ # Build sorts if specified
+ sorts = None
+ if sort_property:
+ sorts = [{"property": sort_property, "direction": sort_direction}]
+
+ # Query the database
+ result = await client.query_database(
+ database_id, filter_obj=filter_obj, sorts=sorts, page_size=limit
+ )
+
+ # Parse the entries
+ entries = []
+ for page in result.get("results", []):
+ entry = {}
+ properties = page.get("properties", {})
+
+ for prop_name, prop_value in properties.items():
+ entry[prop_name] = NotionReadDatabaseBlock._parse_property_value(
+ prop_value
+ )
+
+ # Add metadata
+ entry["_id"] = page.get("id")
+ entry["_url"] = page.get("url")
+ entry["_created_time"] = page.get("created_time")
+ entry["_last_edited_time"] = page.get("last_edited_time")
+
+ entries.append(entry)
+
+ # Get database title (we need to make a separate call for this)
+ try:
+ database_url = f"https://api.notion.com/v1/databases/{database_id}"
+ db_response = await client.requests.get(
+ database_url, headers=client.headers
+ )
+ if db_response.ok:
+ db_data = db_response.json()
+ db_title = parse_rich_text(db_data.get("title", []))
+ else:
+ db_title = "Unknown Database"
+ except Exception:
+ db_title = "Unknown Database"
+
+ return entries, len(entries), db_title
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: OAuth2Credentials,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ entries, count, db_title = await self.query_database(
+ credentials,
+ input_data.database_id,
+ input_data.filter_property,
+ input_data.filter_value,
+ input_data.sort_property,
+ input_data.sort_direction or "ascending",
+ input_data.limit,
+ )
+ # Yield the complete list for batch operations
+ yield "entries", entries
+
+ # Extract and yield IDs as a list for batch operations
+ entry_ids = [entry["_id"] for entry in entries if "_id" in entry]
+ yield "entry_ids", entry_ids
+
+ # Yield each individual entry and its ID for single connections
+ for entry in entries:
+ yield "entry", entry
+ if "_id" in entry:
+ yield "entry_id", entry["_id"]
+
+ yield "count", count
+ yield "database_title", db_title
+ except Exception as e:
+ yield "error", str(e) if str(e) else "Unknown error"
diff --git a/autogpt_platform/backend/backend/blocks/notion/read_page.py b/autogpt_platform/backend/backend/blocks/notion/read_page.py
new file mode 100644
index 0000000000..f3d50f93a2
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/notion/read_page.py
@@ -0,0 +1,64 @@
+from __future__ import annotations
+
+from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema
+from backend.data.model import OAuth2Credentials, SchemaField
+
+from ._api import NotionClient
+from ._auth import (
+ NOTION_OAUTH_IS_CONFIGURED,
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ NotionCredentialsField,
+ NotionCredentialsInput,
+)
+
+
+class NotionReadPageBlock(Block):
+ """Read a Notion page by ID and return its raw JSON."""
+
+ class Input(BlockSchema):
+ credentials: NotionCredentialsInput = NotionCredentialsField()
+ page_id: str = SchemaField(
+ description="Notion page ID. Must be accessible by the connected integration. You can get this from the page URL notion.so/A-Page-586edd711467478da59fe3ce29a1ffab would be 586edd711467478da59fe35e29a1ffab",
+ )
+
+ class Output(BlockSchema):
+ page: dict = SchemaField(description="Raw Notion page JSON.")
+ error: str = SchemaField(description="Error message if the operation failed.")
+
+ def __init__(self):
+ super().__init__(
+ id="5246cc1d-34b7-452b-8fc5-3fb25fd8f542",
+ description="Read a Notion page by its ID and return its raw JSON.",
+ categories={BlockCategory.PRODUCTIVITY},
+ input_schema=NotionReadPageBlock.Input,
+ output_schema=NotionReadPageBlock.Output,
+ disabled=not NOTION_OAUTH_IS_CONFIGURED,
+ test_input={
+ "page_id": "00000000-0000-0000-0000-000000000000",
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_output=[("page", dict)],
+ test_credentials=TEST_CREDENTIALS,
+ test_mock={
+ "get_page": lambda *args, **kwargs: {"object": "page", "id": "mocked"}
+ },
+ )
+
+ @staticmethod
+ async def get_page(credentials: OAuth2Credentials, page_id: str) -> dict:
+ client = NotionClient(credentials)
+ return await client.get_page(page_id)
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: OAuth2Credentials,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ page = await self.get_page(credentials, input_data.page_id)
+ yield "page", page
+ except Exception as e:
+ yield "error", str(e) if str(e) else "Unknown error"
diff --git a/autogpt_platform/backend/backend/blocks/notion/read_page_markdown.py b/autogpt_platform/backend/backend/blocks/notion/read_page_markdown.py
new file mode 100644
index 0000000000..323b748e1b
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/notion/read_page_markdown.py
@@ -0,0 +1,109 @@
+from __future__ import annotations
+
+from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema
+from backend.data.model import OAuth2Credentials, SchemaField
+
+from ._api import NotionClient, blocks_to_markdown, extract_page_title
+from ._auth import (
+ NOTION_OAUTH_IS_CONFIGURED,
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ NotionCredentialsField,
+ NotionCredentialsInput,
+)
+
+
+class NotionReadPageMarkdownBlock(Block):
+ """Read a Notion page and convert it to clean Markdown format."""
+
+ class Input(BlockSchema):
+ credentials: NotionCredentialsInput = NotionCredentialsField()
+ page_id: str = SchemaField(
+ description="Notion page ID. Must be accessible by the connected integration. You can get this from the page URL notion.so/A-Page-586edd711467478da59fe35e29a1ffab would be 586edd711467478da59fe35e29a1ffab",
+ )
+ include_title: bool = SchemaField(
+ description="Whether to include the page title as a header in the markdown",
+ default=True,
+ )
+
+ class Output(BlockSchema):
+ markdown: str = SchemaField(description="Page content in Markdown format.")
+ title: str = SchemaField(description="Page title.")
+ error: str = SchemaField(description="Error message if the operation failed.")
+
+ def __init__(self):
+ super().__init__(
+ id="d1312c4d-fae2-4e70-893d-f4d07cce1d4e",
+ description="Read a Notion page and convert it to Markdown format with proper formatting for headings, lists, links, and rich text.",
+ categories={BlockCategory.PRODUCTIVITY},
+ input_schema=NotionReadPageMarkdownBlock.Input,
+ output_schema=NotionReadPageMarkdownBlock.Output,
+ disabled=not NOTION_OAUTH_IS_CONFIGURED,
+ test_input={
+ "page_id": "00000000-0000-0000-0000-000000000000",
+ "include_title": True,
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_output=[
+ ("markdown", "# Test Page\n\nThis is test content."),
+ ("title", "Test Page"),
+ ],
+ test_credentials=TEST_CREDENTIALS,
+ test_mock={
+ "get_page_markdown": lambda *args, **kwargs: (
+ "# Test Page\n\nThis is test content.",
+ "Test Page",
+ )
+ },
+ )
+
+ @staticmethod
+ async def get_page_markdown(
+ credentials: OAuth2Credentials, page_id: str, include_title: bool = True
+ ) -> tuple[str, str]:
+ """
+ Get a Notion page and convert it to markdown.
+
+ Args:
+ credentials: OAuth2 credentials for Notion.
+ page_id: The ID of the page to fetch.
+ include_title: Whether to include the page title in the markdown.
+
+ Returns:
+ Tuple of (markdown_content, title)
+ """
+ client = NotionClient(credentials)
+
+ # Get page metadata
+ page = await client.get_page(page_id)
+ title = extract_page_title(page)
+
+ # Get all blocks from the page
+ blocks = await client.get_blocks(page_id, recursive=True)
+
+ # Convert blocks to markdown
+ content_markdown = blocks_to_markdown(blocks)
+
+ # Combine title and content if requested
+ if include_title and title:
+ full_markdown = f"# {title}\n\n{content_markdown}"
+ else:
+ full_markdown = content_markdown
+
+ return full_markdown, title
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: OAuth2Credentials,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ markdown, title = await self.get_page_markdown(
+ credentials, input_data.page_id, input_data.include_title
+ )
+ yield "markdown", markdown
+ yield "title", title
+ except Exception as e:
+ yield "error", str(e) if str(e) else "Unknown error"
diff --git a/autogpt_platform/backend/backend/blocks/notion/search.py b/autogpt_platform/backend/backend/blocks/notion/search.py
new file mode 100644
index 0000000000..24ef67fe41
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/notion/search.py
@@ -0,0 +1,225 @@
+from __future__ import annotations
+
+from typing import List, Optional
+
+from pydantic import BaseModel
+
+from backend.data.block import Block, BlockCategory, BlockOutput, BlockSchema
+from backend.data.model import OAuth2Credentials, SchemaField
+
+from ._api import NotionClient, extract_page_title, parse_rich_text
+from ._auth import (
+ NOTION_OAUTH_IS_CONFIGURED,
+ TEST_CREDENTIALS,
+ TEST_CREDENTIALS_INPUT,
+ NotionCredentialsField,
+ NotionCredentialsInput,
+)
+
+
+class NotionSearchResult(BaseModel):
+ """Typed model for Notion search results."""
+
+ id: str
+ type: str # 'page' or 'database'
+ title: str
+ url: str
+ created_time: Optional[str] = None
+ last_edited_time: Optional[str] = None
+ parent_type: Optional[str] = None # 'page', 'database', or 'workspace'
+ parent_id: Optional[str] = None
+ icon: Optional[str] = None # emoji icon if present
+ is_inline: Optional[bool] = None # for databases only
+
+
+class NotionSearchBlock(Block):
+ """Search across your Notion workspace for pages and databases."""
+
+ class Input(BlockSchema):
+ credentials: NotionCredentialsInput = NotionCredentialsField()
+ query: str = SchemaField(
+ description="Search query text. Leave empty to get all accessible pages/databases.",
+ default="",
+ )
+ filter_type: Optional[str] = SchemaField(
+ description="Filter results by type: 'page' or 'database'. Leave empty for both.",
+ default=None,
+ )
+ limit: int = SchemaField(
+ description="Maximum number of results to return", default=20, ge=1, le=100
+ )
+
+ class Output(BlockSchema):
+ results: List[NotionSearchResult] = SchemaField(
+ description="List of search results with title, type, URL, and metadata."
+ )
+ result: NotionSearchResult = SchemaField(
+ description="Individual search result (yields one per result found)."
+ )
+ result_ids: List[str] = SchemaField(
+ description="List of IDs from search results for batch operations."
+ )
+ count: int = SchemaField(description="Number of results found.")
+ error: str = SchemaField(description="Error message if the operation failed.")
+
+ def __init__(self):
+ super().__init__(
+ id="313515dd-9848-46ea-9cd6-3c627c892c56",
+ description="Search your Notion workspace for pages and databases by text query.",
+ categories={BlockCategory.PRODUCTIVITY, BlockCategory.SEARCH},
+ input_schema=NotionSearchBlock.Input,
+ output_schema=NotionSearchBlock.Output,
+ disabled=not NOTION_OAUTH_IS_CONFIGURED,
+ test_input={
+ "query": "project",
+ "limit": 5,
+ "credentials": TEST_CREDENTIALS_INPUT,
+ },
+ test_output=[
+ (
+ "results",
+ [
+ NotionSearchResult(
+ id="123",
+ type="page",
+ title="Project Plan",
+ url="https://notion.so/Project-Plan-123",
+ )
+ ],
+ ),
+ ("result_ids", ["123"]),
+ (
+ "result",
+ NotionSearchResult(
+ id="123",
+ type="page",
+ title="Project Plan",
+ url="https://notion.so/Project-Plan-123",
+ ),
+ ),
+ ("count", 1),
+ ],
+ test_credentials=TEST_CREDENTIALS,
+ test_mock={
+ "search_workspace": lambda *args, **kwargs: (
+ [
+ NotionSearchResult(
+ id="123",
+ type="page",
+ title="Project Plan",
+ url="https://notion.so/Project-Plan-123",
+ )
+ ],
+ 1,
+ )
+ },
+ )
+
+ @staticmethod
+ async def search_workspace(
+ credentials: OAuth2Credentials,
+ query: str = "",
+ filter_type: Optional[str] = None,
+ limit: int = 20,
+ ) -> tuple[List[NotionSearchResult], int]:
+ """
+ Search the Notion workspace.
+
+ Returns:
+ Tuple of (results_list, count)
+ """
+ client = NotionClient(credentials)
+
+ # Build filter if type is specified
+ filter_obj = None
+ if filter_type:
+ filter_obj = {"property": "object", "value": filter_type}
+
+ # Execute search
+ response = await client.search(
+ query=query, filter_obj=filter_obj, page_size=limit
+ )
+
+ # Parse results
+ results = []
+ for item in response.get("results", []):
+ result_data = {
+ "id": item.get("id", ""),
+ "type": item.get("object", ""),
+ "url": item.get("url", ""),
+ "created_time": item.get("created_time"),
+ "last_edited_time": item.get("last_edited_time"),
+ "title": "", # Will be set below
+ }
+
+ # Extract title based on type
+ if item.get("object") == "page":
+ # For pages, get the title from properties
+ result_data["title"] = extract_page_title(item)
+
+ # Add parent info
+ parent = item.get("parent", {})
+ if parent.get("type") == "page_id":
+ result_data["parent_type"] = "page"
+ result_data["parent_id"] = parent.get("page_id")
+ elif parent.get("type") == "database_id":
+ result_data["parent_type"] = "database"
+ result_data["parent_id"] = parent.get("database_id")
+ elif parent.get("type") == "workspace":
+ result_data["parent_type"] = "workspace"
+
+ # Add icon if present
+ icon = item.get("icon")
+ if icon and icon.get("type") == "emoji":
+ result_data["icon"] = icon.get("emoji")
+
+ elif item.get("object") == "database":
+ # For databases, get title from the title array
+ result_data["title"] = parse_rich_text(item.get("title", []))
+
+ # Add database-specific metadata
+ result_data["is_inline"] = item.get("is_inline", False)
+
+ # Add parent info
+ parent = item.get("parent", {})
+ if parent.get("type") == "page_id":
+ result_data["parent_type"] = "page"
+ result_data["parent_id"] = parent.get("page_id")
+ elif parent.get("type") == "workspace":
+ result_data["parent_type"] = "workspace"
+
+ # Add icon if present
+ icon = item.get("icon")
+ if icon and icon.get("type") == "emoji":
+ result_data["icon"] = icon.get("emoji")
+
+ results.append(NotionSearchResult(**result_data))
+
+ return results, len(results)
+
+ async def run(
+ self,
+ input_data: Input,
+ *,
+ credentials: OAuth2Credentials,
+ **kwargs,
+ ) -> BlockOutput:
+ try:
+ results, count = await self.search_workspace(
+ credentials, input_data.query, input_data.filter_type, input_data.limit
+ )
+
+ # Yield the complete list for batch operations
+ yield "results", results
+
+ # Extract and yield IDs as a list for batch operations
+ result_ids = [r.id for r in results]
+ yield "result_ids", result_ids
+
+ # Yield each individual result for single connections
+ for result in results:
+ yield "result", result
+
+ yield "count", count
+ except Exception as e:
+ yield "error", str(e) if str(e) else "Unknown error"
diff --git a/autogpt_platform/backend/test/sdk/test_sdk_registry.py b/autogpt_platform/backend/test/sdk/test_sdk_registry.py
index d412f905df..f82abd57cb 100644
--- a/autogpt_platform/backend/test/sdk/test_sdk_registry.py
+++ b/autogpt_platform/backend/test/sdk/test_sdk_registry.py
@@ -153,7 +153,7 @@ class TestAutoRegistry:
try:
# Use ProviderBuilder which calls register_api_key and creates the credential
- provider = (
+ (
ProviderBuilder("test_provider")
.with_api_key("TEST_API_KEY", "Test API Key")
.build()