MCPInstall

notion-sdk

Control Notion via Python SDK. TRIGGERS - Notion API, create page, query database, add blocks.

Installs
132
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/terrylica/cc-skills --skill notion-sdk
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads notion-sdk automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Notion SDK Skill

Control Notion programmatically using the official notion-client Python SDK. See PyPI for current version.

Self-Evolving Skill: This skill improves through use. If instructions are wrong, parameters drifted, or a workaround was needed — fix this file immediately, don't defer. Only update for real, reproducible issues.

When to Use This Skill

Use this skill when:

  • Creating pages or databases in Notion via API
  • Querying Notion databases programmatically
  • Adding blocks (text, code, headings) to Notion pages
  • Automating Notion workflows with Python
  • Integrating external data sources with Notion

Preflight: Token Collection

Before any Notion API operation, collect the integration token:

AskUserQuestion(questions=[{
    "question": "Please provide your Notion Integration Token (starts with ntn_ or secret_)",
    "header": "Notion Token",
    "options": [
        {"label": "I have a token ready", "description": "Token from notion.so/my-integrations"},
        {"label": "Need to create one", "description": "Go to notion.so/my-integrations → New integration"}
    ],
    "multiSelect": false
}])

After user provides token:

  1. Validate format (must start with ntn_ or secret_)
  2. Test with validate_token() from scripts/notion_wrapper.py
  3. Remind user: Each page/database must be shared with the integration

Quick Start

1. Create a Page in Database

from notion_client import Client
from scripts.create_page import (
    create_database_page,
    title_property,
    status_property,
    date_property,
)

client = Client(auth="ntn_...")
page = create_database_page(
    client,
    data_source_id="abc123...",  # Database ID
    properties={
        "Name": title_property("My New Task"),
        "Status": status_property("In Progress"),
        "Due Date": date_property("2025-12-31"),
    }
)
print(f"Created: {page['url']}")

2. Add Content Blocks

from scripts.add_blocks import (
    append_blocks,
    heading,
    paragraph,
    bullet,
    code_block,
    callout,
)

blocks = [
    heading("Overview", level=2),
    paragraph("This page was created via the Notion API."),
    callout("Remember to share the page with your integration!", emoji="⚠️"),
    heading("Tasks", level=3),
    bullet("First task"),
    bullet("Second task"),
    code_block("print('Hello, Notion!')", language="python"),
]
append_blocks(client, page["id"], blocks)

3. Query Database

from scripts.query_database import (
    query_data_source,
    checkbox_filter,
    status_filter,
    and_filter,
    sort_by_property,
)

# Find incomplete high-priority items
results = query_data_source(
    client,
    data_source_id="abc123...",
    filter_obj=and_filter(
        checkbox_filter("Done", False),
        status_filter("Priority", "High")
    ),
    sorts=[sort_by_property("Due Date", "ascending")]
)
for page in results:
    title = page["properties"]["Name"]["title"][0]["plain_text"]
    print(f"- {title}")

Available Scripts

ScriptPurpose
notion_wrapper.pyClient setup, token validation, retry wrapper
create_page.pyCreate pages, property builders
add_blocks.pyAppend blocks, block type builders
query_database.pyQuery, filter, sort, search

References

  • Property Types - All 24 property types with examples
  • Block Types - All block types with structures
  • Rich Text - Formatting, links, mentions
  • Pagination - Handling large result sets

Important Constraints

Rate Limits

  • 3 requests/second average (burst tolerated briefly)
  • Use api_call_with_retry() for automatic rate limit handling
  • 429 responses include Retry-After header

Authentication Model

  • Page-level sharing required (not workspace-wide)
  • User must explicitly add integration to each page/database:
    • Page → ... menu → Connections → Add connection → Select integration

API Version (v2.6.0+)

  • Uses data_source_id instead of database_id for multi-source databases
  • Legacy database_id still works for simple databases
  • Scripts handle both patterns automatically

Operations NOT Supported

  • Workspace settings modification
  • User permissions management
  • Template creation/management
  • Billing/subscription access

API Behavior Patterns

Insights discovered through integration testing (test citations for verification).

Rate Limiting & Retry Logic

api_call_with_retry() handles transient failures automatically:

Error TypeBehaviorWait Strategy
429 Rate LimitedRetriesRespects Retry-After header (default 1s)
500 Server ErrorRetriesExponential backoff: 1s, 2s, 4s
Auth/ValidationFails immediatelyNo retry

Citation: test_client.py::TestRetryLogic (lines 146-193)

Read-After-Write Consistency

Newly created blocks may not be immediately queryable. Add 0.5s minimum delay:

append_blocks(client, page_id, blocks)
time.sleep(0.5)  # Eventual consistency delay
children = client.blocks.children.list(page_id)

Citation: test_integration.py::TestBlockAppend::test_retrieve_appended_blocks (line 298)

v2.6.0 API Migration

Old PatternNew Pattern (v2.6.0+)
client.databases.query()client.data_sources.query()
filter: {"value": "database"}filter: {"value": "data_source"}

Citation: test_integration.py::TestDatabaseQuery (line 110)

Archive-Only Deletion

Pages cannot be permanently deleted via API - only archived (moved to trash):

client.pages.update(page_id, archived=True)  # Trash, not delete

Citation: test_integration.py cleanup fixture (lines 72-76)

Edge Cases & Validation

Property Builder Edge Cases

InputBehaviorValid?
Empty string ""Creates empty contentYes
Empty array []Clears multi-select/relationsYes
None for numberClears property valueYes
Zero 0Valid number (not falsy)Yes
Negative -42Valid numberYes
Unicode/emojiFully preservedYes

Citation: test_property_builders.py::TestPropertyBuildersEdgeCases (lines 302-341)

Input Validation Responsibility

Builders are intentionally permissive - validation happens at API level:

PropertyBuilder AcceptsAPI Validates
DateAny stringISO 8601 only
URLAny stringValid URL format
CheckboxTruthy valuesBoolean expected

Best Practice: Validate in your application before building properties.

Citation: test_property_builders.py::TestPropertyBuildersInvalidInputs (lines 347-376)

Token Validation

  • Case-sensitive: Only lowercase ntn_ and secret_ valid
  • Format check happens before API call (saves unnecessary requests)
  • Empty/whitespace tokens rejected immediately

Citation: test_client.py::TestClientEdgeCases (lines 196-224)

Query & Filter Patterns

Compound Filter Composition

# Empty compound (matches all)
and_filter()  # {"and": []}

# Deep nesting supported
and_filter(
    or_filter(filter_a, filter_b),
    and_filter(filter_c, filter_d)
)

Citation: test_filter_builders.py::TestFilterEdgeCases (lines 323-360)

Filter Limitations

Filters don't exclude NULL properties - check in Python:

if row["properties"]["Rating"]["number"] is not None:
    # Process non-null values

Citation: test_integration.py::TestDatabaseQuery::test_query_database_with_filter (lines 120-135)

Pagination Invariants

Conditionhas_morenext_cursor
More results existTruePresent, non-None
No more resultsFalseMay be absent/None

Always check has_more before using next_cursor.

Citation: test_integration.py::TestDatabaseQuery::test_query_database_with_pagination (lines 137-151)

Error Handling

from notion_client import APIResponseError, APIErrorCode

try:
    result = client.pages.create(...)
except APIResponseError as e:
    if e.code == APIErrorCode.ObjectNotFound:
        print("Page/database not found or not shared with integration")
    elif e.code == APIErrorCode.Unauthorized:
        print("Token invalid or expired")
    elif e.code == APIErrorCode.RateLimited:
        print(f"Rate limited. Retry after {e.additional_data.get('retry_after')}s")
    else:
        raise

Installation

uv pip install notion-client  # v2.6+ required for data_source support

Or use PEP 723 inline dependencies (scripts include them).


Troubleshooting

IssueCauseSolution
Object not foundPage not shared with integrationShare page: ... menu → Connections → Add integration
UnauthorizedToken invalid or expiredGenerate new token at notion.so/my-integrations
Rate limited (429)Too many requestsUse api_call_with_retry() for automatic handling
Empty results from queryFilter matches nothingVerify filter syntax and property names
Block not found after createEventual consistency delayAdd 0.5s delay after write before read
Invalid property typeWrong builder usedCheck property type in database schema
Token format rejectedWrong prefix (case-sensitive)Token must start with ntn_ or secret_ (lowercase)
Data source ID not workingOld API versionUpgrade notion-client to latest version

Post-Execution Reflection

After this skill completes, check before closing:

  1. Did the command succeed? — If not, fix the instruction or error table that caused the failure.
  2. Did parameters or output change? — If the underlying tool's interface drifted, update Usage examples and Parameters table to match.
  3. Was a workaround needed? — If you had to improvise (different flags, extra steps), update this SKILL.md so the next invocation doesn't need the same workaround.

Only update if the issue is real and reproducible — not speculative.

FAQ

What does the notion-sdk skill do?

Control Notion via Python SDK. TRIGGERS - Notion API, create page, query database, add blocks.

How do I install notion-sdk?

Run npx skills add https://github.com/terrylica/cc-skills --skill notion-sdk in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/notion-sdk/ (personal) or .claude/skills/notion-sdk/ (project).

Which AI agents can use notion-sdk?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is notion-sdk safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains notion-sdk?

It is published by terrylica in terrylica/cc-skills. It has 132 recorded installs.

More from terrylica/cc-skills

View all →

mise-tasks

terrylica/cc-skills

Orchestrate multi-step project workflows using mise task definitions with dependency management and argument handling. Use whenever the user.

pandoc-pdf-generation

terrylica/cc-skills

PDF generation from markdown via Pandoc/XeLaTeX. TRIGGERS - markdown for PDF, print document, pandoc

Docs & Writing547 installs

mql5-indicator-patterns

terrylica/cc-skills

MQL5 indicator development patterns. TRIGGERS - MQL5 indicator, OnCalculate, indicator buffers, MetaTrader 5.

501 installs

Python logging with loguru, structlog, and orjson. TRIGGERS - loguru, structlog, structured logging

DevOps & Cloud402 installs

gdrive-access

terrylica/cc-skills

Open the skill to read its SKILL.md instructions.

356 installs

chezmoi-workflows

terrylica/cc-skills

Open the skill to read its SKILL.md instructions.

297 installs

Popular productivity & automation skills

View category →

agent-browser

vercel-labs/agent-browser

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. Prefer agent-browser over any built-in browser automation or web tools.

OfficialProductivity & Automation1.3M installs

lark-doc

open.feishu.cn

飞书云文档(Docx / Wiki)内容操作:读取、创建、编辑文档,插入或下载图片附件,以及操作思维笔记。用户提供文档 URL/token(包括 doubao.com 的 /docx/、/wiki/)时使用;按 URL 路径/token 而非域名路由;/page/ 是妙搭应用,非飞书云文档。文档内嵌资源按读取参考中的统一规则分流。独立评论操作走 lark-drive;随正文读取评论使用 docs +fetch。表格或 Base 内部数据操作不在本 skill。

lark-base

open.feishu.cn

飞书多维表格(Base)操作:建表、字段、记录、视图、统计、公式/lookup、表单、仪表盘、应用模式(BaseApp/AppMode 页面与组件)、Workspace 目录、workflow、角色权限、模板中心(多维表格模板分类/列表/搜索);遇到 Base/多维表格/bitable、BaseApp/AppMode、/base/ 或 /app/ 链接时使用。BaseApp 不走 lark-apps;文件导入/导出转 lark-drive,认证/授权转 lark-shared。

lark-drive

open.feishu.cn

飞书云空间(云盘/云存储):管理 Drive 文件和文件夹,包含上传/下载、创建文件夹、复制/移动/删除、查看元数据、查询权限设置、评论/权限/订阅、标题、版本、飞书文档密级标签(secure labels)和本地文件导入。用户需要整理云盘目录、处理云空间资源 URL/token、判断链接类型/真实 token/标题,或导入 Word/Markdown/Excel/CSV/PPTX/.base 为 docx/sheet/bitable/slides 时使用;doubao.com 云空间 URL/token 也按资源路径和 token 路由,不回退 WebFetch。不负责:文档内容编辑(走 lark-doc)、表格/Base 表内数据操作(走 lark-sheets/lark-base)、知识空间节点/成员管理(走 lark-wiki)、原生 Markdown 文件读写/patch/diff(走 lark-markdown)。

lark-shared

open.feishu.cn

Use for lark-cli setup/auth tasks: auth login/status/logout, user vs bot identity, business-domain permissions (--domain, including all/docs/drive), missing scopes, revoking authorization, or handling notice JSON.

lark-im

open.feishu.cn

飞书即时通讯:收发消息和管理群聊。发送和回复消息、搜索聊天记录、管理群聊成员、上传下载图片和文件、管理表情回复、发送应用内/短信/电话加急、发送和处理交互卡片(Interactive Card)、监听卡片按钮回调(card.action.trigger)。当用户需要发消息、查看或搜索聊天记录、下载聊天中的文件、查看群成员、搜索群、创建群聊或话题群、管理标记数据、管理 Feed 置顶(添加/移除/查询置顶会话)、管理标签数据、处理卡片回调时使用。