Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
chore(docs): remove legacy cookbook examples folder
Shawn Esquivelf77c9c7cdb10
diff --git a/docs/decisions/cookbooks-revamp-plan.md b/docs/decisions/cookbooks-revamp-plan.mdindex c80955dba..95c6d07ee 100644--- a/docs/decisions/cookbooks-revamp-plan.md+++ b/docs/decisions/cookbooks-revamp-plan.md@@ -178,6 +178,7 @@ Full-stack templates live as cloneable repos on GitHub. Docs pages describe what- `examples/` excluded from tsconfig.json (twoslash handles type-checking via `<include>`, Next.js `tsc` can't resolve local relative imports)- Welcome page revamped: hero cards (Tutorial + How it works), full-width Quickstart, AIToolsBanner component, Explore section- AIToolsBanner component has markdown fallback in `lib/source.ts` for LLM crawlers+- The legacy `docs/examples/` sample-code folder (14 standalone app folders) was removed — it was orphaned (not referenced by any `content/examples` `<include>`, the source config, or the `llms.txt`/`llms-full.txt` routes). The live `/examples` page is sourced from `content/examples/`.---diff --git a/docs/examples/app-connections-dashboard/connections-route.ts b/docs/examples/app-connections-dashboard/connections-route.tsdeleted file mode 100644index dfad6af5b..000000000--- a/docs/examples/app-connections-dashboard/connections-route.ts+++ /dev/null@@ -1,40 +0,0 @@-// region setup-import { Composio } from "@composio/core";--const composio = new Composio();--export const dynamic = "force-dynamic";-// endregion setup--// region list-export async function GET() {- const session = await composio.create("user_123");- const { items } = await session.toolkits({ limit: 50 });-- return Response.json({- // Filter out toolkits that don't require authentication- toolkits: items- .filter((t) => !t.isNoAuth)- .map((t) => ({- slug: t.slug,- name: t.name,- logo: t.logo,- isConnected: t.connection?.isActive ?? false,- connectedAccountId: t.connection?.connectedAccount?.id,- })),- });-}-// endregion list--// region connect-export async function POST(req: Request) {- const { toolkit }: { toolkit: string } = await req.json();- const origin = new URL(req.url).origin;- const session = await composio.create("user_123");- const connectionRequest = await session.authorize(toolkit, {- callbackUrl: origin,- });-- return Response.json({ redirectUrl: connectionRequest.redirectUrl });-}-// endregion connectdiff --git a/docs/examples/app-connections-dashboard/disconnect-route.ts b/docs/examples/app-connections-dashboard/disconnect-route.tsdeleted file mode 100644index e8b93b36d..000000000--- a/docs/examples/app-connections-dashboard/disconnect-route.ts+++ /dev/null@@ -1,10 +0,0 @@-import { Composio } from "@composio/core";--const composio = new Composio();--export async function POST(req: Request) {- const { connectedAccountId }: { connectedAccountId: string } =- await req.json();- await composio.connectedAccounts.delete(connectedAccountId);- return Response.json({ success: true });-}diff --git a/docs/examples/app-connections-dashboard/page.tsx b/docs/examples/app-connections-dashboard/page.tsxdeleted file mode 100644index 9aef27b5f..000000000--- a/docs/examples/app-connections-dashboard/page.tsx+++ /dev/null@@ -1,92 +0,0 @@-"use client";--import { useEffect, useState } from "react";--type Toolkit = {- slug: string;- name: string;- logo?: string;- isConnected: boolean;- connectedAccountId?: string;-};--export default function Dashboard() {- const [toolkits, setToolkits] = useState<Toolkit[]>([]);- async function fetchConnections() {- const res = await fetch("/api/connections", { cache: "no-store" });- const data = await res.json();- setToolkits(data.toolkits);- }-- useEffect(() => {- fetchConnections();- }, []);-- async function connect(slug: string) {- const res = await fetch("/api/connections", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ toolkit: slug }),- });- const { redirectUrl } = await res.json();- window.location.href = redirectUrl;- }-- async function disconnect(connectedAccountId: string) {- await fetch("/api/connections/disconnect", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ connectedAccountId }),- });- fetchConnections();- }-- return (- <main className="max-w-4xl mx-auto p-6">- <h1 className="text-2xl font-bold mb-2">App Connections</h1>- <p className="text-gray-500 mb-6">- Connect your apps to give your agent access.- </p>-- <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">- {toolkits.map((t) => (- <div- key={t.slug}- className="flex items-center justify-between p-4 border rounded-lg"- >- <div className="flex items-center gap-3">- {t.logo && (- <img src={t.logo} alt={t.name} className="w-8 h-8 rounded" />- )}- <div>- <p className="font-medium">{t.name}</p>- <p- className={`text-xs ${- t.isConnected ? "text-green-600" : "text-gray-400"- }`}- >- {t.isConnected ? "Connected" : "Not connected"}- </p>- </div>- </div>- {t.isConnected ? (- <button- onClick={() => disconnect(t.connectedAccountId!)}- className="px-3 py-1.5 text-sm border rounded hover:bg-gray-50"- >- Disconnect- </button>- ) : (- <button- onClick={() => connect(t.slug)}- className="px-3 py-1.5 text-sm bg-black text-white rounded hover:bg-gray-800"- >- Connect- </button>- )}- </div>- ))}- </div>- </main>- );-}diff --git a/docs/examples/background-agent/sweep.ts b/docs/examples/background-agent/sweep.tsdeleted file mode 100644index 4a6692a36..000000000--- a/docs/examples/background-agent/sweep.ts+++ /dev/null@@ -1,44 +0,0 @@-import "dotenv/config";-import { openai } from "@ai-sdk/openai";-import { generateText, stepCountIs } from "ai";-import { Composio } from "@composio/core";-import { VercelProvider } from "@composio/vercel";--// #region setup-const composio = new Composio({ provider: new VercelProvider() });-const userId = process.env.COMPOSIO_USER_ID ?? "default";-const model = openai("gpt-5.4");-// #endregion setup--// #region sweep-async function sweep() {- const session = await composio.create(userId);- const tools = await session.tools();-- const { text } = await generateText({- model,- tools,- stopWhen: stepCountIs(15),- prompt: `You are an autonomous background agent running a scheduled sweep.--Do the following, in order:--1. **GitHub**:Find pull requests where my review is requested.- List each PR with its title, repo, and link.--2. **Gmail**:Find emails from the last 24 hours that I haven't replied to.- List each with sender and subject.--3. **Slack**: Post a concise summary of your findings to the #morning-sweep channel.- Format it as a digest with sections for PRs and emails.- If nothing was found, say so.--If an app is not connected, skip it and note it in the summary.-Be concise and actionable.`,- });-- console.log(text);-}--sweep();-// #endregion sweepdiff --git a/docs/examples/chat-app/ToolCallDisplay.tsx b/docs/examples/chat-app/ToolCallDisplay.tsxdeleted file mode 100644index 5c82a2058..000000000--- a/docs/examples/chat-app/ToolCallDisplay.tsx+++ /dev/null@@ -1,46 +0,0 @@-"use client";--import { useState } from "react";--export function ToolCallDisplay({- toolName,- input,- output,- isLoading,-}: {- toolName: string;- input: unknown;- output?: unknown;- isLoading: boolean;-}) {- const [expanded, setExpanded] = useState(false);-- return (- <div className="my-1">- <button- onClick={() => setExpanded(!expanded)}- className={`inline-flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs transition-colors ${- isLoading- ? "border-gray-200 bg-gray-50 text-gray-500 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400"- : "border-gray-200 bg-gray-50 text-gray-700 hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800"- }`}- >- {isLoading ? (- <span className="inline-block h-3 w-3 animate-spin rounded-full border border-gray-300 border-t-gray-600 dark:border-gray-600 dark:border-t-gray-300" />- ) : (- <span className="text-green-600 dark:text-green-400">✓</span>- )}- <code className="font-mono">{toolName}</code>- {!isLoading && <span className="text-gray-400">{expanded ? "▴" : "▾"}</span>}- </button>-- {expanded && !isLoading && (- <pre className="mt-1 ml-1 max-h-40 max-w-full overflow-auto whitespace-pre-wrap break-words rounded-md border border-gray-200 bg-gray-50 p-2 text-xs text-gray-600 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400">- {output != null- ? String(JSON.stringify(output, null, 2))- : String(JSON.stringify(input, null, 2))}- </pre>- )}- </div>- );-}diff --git a/docs/examples/chat-app/page-with-tools.tsx b/docs/examples/chat-app/page-with-tools.tsxdeleted file mode 100644index 700c87541..000000000--- a/docs/examples/chat-app/page-with-tools.tsx+++ /dev/null@@ -1,100 +0,0 @@-// @noErrors-"use client";--import { useState } from "react";-import { useChat } from "@ai-sdk/react";-import { DefaultChatTransport, getToolName, isToolUIPart } from "ai";-import { ToolCallDisplay } from "../components/ToolCallDisplay";--export default function Chat() {- const [input, setInput] = useState("");- const { messages, sendMessage, status } = useChat({- transport: new DefaultChatTransport({ api: "/api/chat" }),- });-- const isLoading = status === "streaming" || status === "submitted";-- return (- <main className="max-w-2xl mx-auto p-6">- <h1 className="text-2xl font-bold mb-6">Composio Chat</h1>-- <div className="space-y-4 mb-6 min-h-[200px]">- {messages.length === 0 && (- <p className="text-gray-400 text-center py-12">- Try: "Star the composio repo on GitHub"- </p>- )}- {messages.map((m) => (- <div key={m.id} className="flex gap-2">- <span className="font-semibold shrink-0">- {m.role === "user" ? "You:" : "Agent:"}- </span>- <div className="flex-1 whitespace-pre-wrap">- {m.parts.map((part, i) => {- if (part.type === "text") {- return (- <span key={i}>- {String(part.text)- .split(/(https?:\/\/[^\s)]+)/g)- .map((segment, j) =>- segment.match(/^https?:\/\//) ? (- <a key={j} href={segment} target="_blank" rel="noopener noreferrer" className="text-blue-600 underline">{segment}</a>- ) : (- segment- )- )}- </span>- );- }- if (isToolUIPart(part)) {- return (- <ToolCallDisplay- key={part.toolCallId}- toolName={getToolName(part)}- input={part.input}- output={- part.state === "output-available"- ? part.output- : undefined- }- isLoading={part.state !== "output-available"}- />- );- }- return null;- })}- </div>- </div>- ))}- {isLoading && (- <p className="text-gray-400 text-sm">Thinking...</p>- )}- </div>-- <form- onSubmit={(e) => {- e.preventDefault();- if (!input.trim()) return;- sendMessage({ text: input });- setInput("");- }}- className="flex gap-2"- >- <input- value={input}- onChange={(e) => setInput(e.target.value)}- placeholder="Ask me anything..."- disabled={isLoading}- className="flex-1 p-3 border border-gray-300 rounded-lg"- />- <button- type="submit"- disabled={isLoading}- className="px-6 py-3 bg-white text-black font-medium rounded-lg hover:bg-gray-200 transition-colors disabled:opacity-50"- >- Send- </button>- </form>- </main>- );-}diff --git a/docs/examples/chat-app/page.tsx b/docs/examples/chat-app/page.tsxdeleted file mode 100644index 691e4a49b..000000000--- a/docs/examples/chat-app/page.tsx+++ /dev/null@@ -1,81 +0,0 @@-// @noErrors-"use client";--import { useState } from "react";-import { useChat } from "@ai-sdk/react";-import { DefaultChatTransport } from "ai";--export default function Chat() {- const [input, setInput] = useState("");- const { messages, sendMessage, status } = useChat({- transport: new DefaultChatTransport({ api: "/api/chat" }),- });-- const isLoading = status === "streaming" || status === "submitted";-- return (- <main className="max-w-2xl mx-auto p-6">- <h1 className="text-2xl font-bold mb-6">Composio Chat</h1>-- <div className="space-y-4 mb-6 min-h-[200px]">- {messages.length === 0 && (- <p className="text-gray-400 text-center py-12">- Try: "Star the composio repo on GitHub"- </p>- )}- {messages.map((m) => (- <div key={m.id} className="flex gap-2">- <span className="font-semibold shrink-0">- {m.role === "user" ? "You:" : "Agent:"}- </span>- <div className="whitespace-pre-wrap">- {m.parts.map((part, i) =>- part.type === "text" ? (- <span key={i}>- {String(part.text)- .split(/(https?:\/\/[^\s)]+)/g)- .map((segment, j) =>- segment.match(/^https?:\/\//) ? (- <a key={j} href={segment} target="_blank" rel="noopener noreferrer" className="text-blue-600 underline">{segment}</a>- ) : (- segment- )- )}- </span>- ) : null- )}- </div>- </div>- ))}- {isLoading && (- <p className="text-gray-400 text-sm">Thinking...</p>- )}- </div>-- <form- onSubmit={(e) => {- e.preventDefault();- if (!input.trim()) return;- sendMessage({ text: input });- setInput("");- }}- className="flex gap-2"- >- <input- value={input}- onChange={(e) => setInput(e.target.value)}- placeholder="Ask me anything..."- disabled={isLoading}- className="flex-1 p-3 border border-gray-300 rounded-lg"- />- <button- type="submit"- disabled={isLoading}- className="px-6 py-3 bg-white text-black font-medium rounded-lg hover:bg-gray-200 transition-colors disabled:opacity-50"- >- Send- </button>- </form>- </main>- );-}diff --git a/docs/examples/chat-app/route.ts b/docs/examples/chat-app/route.tsdeleted file mode 100644index 60cbc1dd9..000000000--- a/docs/examples/chat-app/route.ts+++ /dev/null@@ -1,40 +0,0 @@-import { openai } from "@ai-sdk/openai";-import { Composio } from "@composio/core";-import { VercelProvider } from "@composio/vercel";-import {- streamText,- convertToModelMessages,- generateId,- stepCountIs,- type UIMessage,-} from "ai";--const composio = new Composio({ provider: new VercelProvider() });--// In production, store session IDs per user in your database-let sessionId: string | null = null;--export async function POST(req: Request) {- const { messages }: { messages: UIMessage[] } = await req.json();-- // Reuse existing session or create a new one- const session = sessionId- ? await composio.use(sessionId)- : await composio.create("user_123");- sessionId = session.sessionId;-- const tools = await session.tools();-- const result = streamText({- model: openai("gpt-5.4"),- system: "You are a helpful assistant. Use Composio tools to help the user.",- messages: await convertToModelMessages(messages),- tools,- stopWhen: stepCountIs(10),- });-- return result.toUIMessageStreamResponse({- originalMessages: messages,- generateMessageId: () => generateId(),- });-}diff --git a/docs/examples/fast-api/main.py b/docs/examples/fast-api/main.pydeleted file mode 100644index 3b257d28f..000000000--- a/docs/examples/fast-api/main.py+++ /dev/null@@ -1,74 +0,0 @@-# region setup-from agents import Agent, Runner-from composio import Composio-from composio_openai_agents import OpenAIAgentsProvider-from fastapi import FastAPI-from pydantic import BaseModel--composio = Composio(provider=OpenAIAgentsProvider())--app = FastAPI()-# endregion setup---# region chat-class ChatRequest(BaseModel):- user_id: str- message: str--[email protected]("/chat")-def chat(request: ChatRequest):- """Send a message to an AI agent with access to all tools."""- session = composio.create(user_id=request.user_id)- tools = session.tools()-- agent = Agent(- name="Assistant",- instructions="You are a helpful assistant. Use tools to help the user.",- tools=tools,- )-- result = Runner.run_sync(starting_agent=agent, input=request.message)- return {"response": result.final_output}-# endregion chat---# region list-connections[email protected]("/connections/{user_id}")-def list_connections(user_id: str):- """List all toolkits and their connection status for a user."""- session = composio.create(user_id=user_id)- toolkits = session.toolkits()- return [- {"toolkit": t.slug, "connected": t.connection.is_active if t.connection else False}- for t in toolkits.items- ]-# endregion list-connections---# region check-connection[email protected]("/connections/{user_id}/{toolkit}")-def check_connection(user_id: str, toolkit: str):- """Check if a specific toolkit is connected for a user."""- session = composio.create(user_id=user_id, toolkits=[toolkit])- toolkits = session.toolkits()- for t in toolkits.items:- if t.slug == toolkit:- return {"toolkit": toolkit, "connected": t.connection.is_active if t.connection else False}- return {"toolkit": toolkit, "connected": False}-# endregion check-connection---# region connect-class ConnectRequest(BaseModel):- user_id: str--[email protected]("/connect/{toolkit}")-def connect_toolkit(toolkit: str, request: ConnectRequest):- """Start OAuth for a toolkit. Returns a URL to redirect the user to."""- session = composio.create(user_id=request.user_id, toolkits=[toolkit])- connection_request = session.authorize(toolkit)- return {"redirect_url": connection_request.redirect_url}-# endregion connectdiff --git a/docs/examples/gmail-labeler/main.py b/docs/examples/gmail-labeler/main.pydeleted file mode 100644index e81163e77..000000000--- a/docs/examples/gmail-labeler/main.py+++ /dev/null@@ -1,114 +0,0 @@-import sys--# region setup-import asyncio--from composio import Composio-from composio_claude_agent_sdk import ClaudeAgentSDKProvider-from claude_agent_sdk import query, ClaudeAgentOptions, create_sdk_mcp_server--composio = Composio(provider=ClaudeAgentSDKProvider())-# endregion setup---# region connect-def connect(user_id: str):- """Check if Gmail is connected. If not, start OAuth and wait."""- session = composio.create(user_id=user_id, toolkits=["gmail"])- toolkits = session.toolkits()-- for t in toolkits.items:- if t.slug == "gmail" and t.connection and t.connection.is_active:- print("Gmail is already connected.")- return-- connection_request = session.authorize("gmail")- print(f"Open this URL to connect Gmail:\n{connection_request.redirect_url}")- connection_request.wait_for_connection()- print("Connected.")-# endregion connect---# region label-async def label_email(session, message_id: str, subject: str, body: str):- """Use Claude to label an incoming email."""- tools = session.tools()- tool_server = create_sdk_mcp_server(name="composio", version="1.0.0", tools=tools)-- prompt = f"""You received a new email. Analyze it and apply an appropriate label.--Message ID: {message_id}-Subject: {subject}-Body: {body}--Steps:-1. List the existing Gmail labels.-2. Decide which label fits best, or create a new label if none fit.-3. Apply the label to this email using its message ID."""-- options = ClaudeAgentOptions(- system_prompt="You are an email organizer. Label incoming emails with the most appropriate Gmail label.",- permission_mode="bypassPermissions",- mcp_servers={"composio": tool_server},- )-- async for message in query(prompt=prompt, options=options):- print(message)-# endregion label---# region listen-def listen(user_id: str):- """Create a trigger, subscribe to events, and label incoming emails."""- session = composio.create(user_id=user_id, toolkits=["gmail"])-- trigger = composio.triggers.create(- slug="GMAIL_NEW_GMAIL_MESSAGE",- user_id=user_id,- trigger_config={},- )- print(f"Trigger created: {trigger.trigger_id}")-- loop = asyncio.new_event_loop()- subscription = composio.triggers.subscribe()-- @subscription.handle(trigger_id=trigger.trigger_id)- def handle_event(data):- payload = data.get("payload", {})- print(f"New email: {payload.get('subject', 'No subject')}")- try:- loop.run_until_complete(- label_email(- session,- message_id=payload.get("id", ""),- subject=payload.get("subject", ""),- body=payload.get("message_text", ""),- )- )- except Exception as e:- print(f"Error labeling email: {e}")-- print("Listening for new emails...")- subscription.wait_forever()-# endregion listen---if __name__ == "__main__":- if len(sys.argv) < 2:- print("Usage:")- print(" python main.py connect <user_id>")- print(" python main.py listen <user_id>")- sys.exit(1)-- command = sys.argv[1]-- if command == "connect":- uid = sys.argv[2] if len(sys.argv) > 2 else "default"- connect(uid)- elif command == "listen":- uid = sys.argv[2] if len(sys.argv) > 2 else "default"- listen(uid)- else:- print(f"Unknown command: {command}")- print("Use 'connect' or 'listen'.")- sys.exit(1)diff --git a/docs/examples/hono/server.ts b/docs/examples/hono/server.tsdeleted file mode 100644index 1cb8f56ab..000000000--- a/docs/examples/hono/server.ts+++ /dev/null@@ -1,88 +0,0 @@-import "dotenv/config";-import { serve } from "@hono/node-server";-import { Hono } from "hono";-import { OpenAI } from "openai";-import { Composio } from "@composio/core";-import { OpenAIProvider } from "@composio/openai";--// #region setup-const composio = new Composio({ provider: new OpenAIProvider() });-const openai = new OpenAI();--const app = new Hono();-// #endregion setup--// #region chat-app.post("/chat", async (c) => {- const { userId, message } = await c.req.json();-- const session = await composio.create(userId);- const tools = await session.tools();-- const messages: OpenAI.ChatCompletionMessageParam[] = [- { role: "system", content: "You are a helpful assistant. Use tools to help the user." },- { role: "user", content: message },- ];-- while (true) {- const response = await openai.chat.completions.create({- model: "gpt-5.4",- tools,- messages,- });-- const choice = response.choices[0];- if (!choice.message.tool_calls?.length) {- return c.json({ response: choice.message.content });- }-- messages.push(choice.message);- const toolResults = await composio.provider.handleToolCalls(userId, response);- messages.push(...toolResults);- }-});-// #endregion chat--// #region list-connections-app.get("/connections/:userId", async (c) => {- const userId = c.req.param("userId");-- const session = await composio.create(userId);- const toolkits = await session.toolkits();-- return c.json(- toolkits.items.map((t) => ({- toolkit: t.slug,- connected: t.connection?.isActive ?? false,- }))- );-});-// #endregion list-connections--// #region check-connection-app.get("/connections/:userId/:toolkit", async (c) => {- const userId = c.req.param("userId");- const toolkit = c.req.param("toolkit");-- const session = await composio.create(userId, { toolkits: [toolkit] });- const result = await session.toolkits();- const match = result.items.find((t) => t.slug === toolkit);-- return c.json({ toolkit, connected: match?.connection?.isActive ?? false });-});-// #endregion check-connection--// #region connect-app.post("/connect/:toolkit", async (c) => {- const toolkit = c.req.param("toolkit");- const { userId } = await c.req.json();-- const session = await composio.create(userId, { toolkits: [toolkit] });- const connectionRequest = await session.authorize(toolkit);-- return c.json({ redirectUrl: connectionRequest.redirectUrl });-});-// #endregion connect--serve({ fetch: app.fetch, port: 8000 });-console.log("Server running on http://localhost:8000");diff --git a/docs/examples/pr-review-agent/agent.py b/docs/examples/pr-review-agent/agent.pydeleted file mode 100644index dee457361..000000000--- a/docs/examples/pr-review-agent/agent.py+++ /dev/null@@ -1,89 +0,0 @@-import asyncio-import os--from agents import Agent, Runner-from composio_openai_agents import OpenAIAgentsProvider--from composio import Composio--composio = Composio(provider=OpenAIAgentsProvider())--session = composio.create(- user_id="user_123",- toolkits=["github"],-)--tools = session.tools()--agent = Agent(- name="PR Reviewer",- instructions="""You are PR-Reviewer, an AI code reviewer for GitHub pull requests.--**Step 1: Gather context**-- Fetch the PR details (title, description, author).-- List all changed files and read the diff.-- Check if the repo has a CLAUDE.md or AGENTS.md at the root.- If found, read it and treat its rules as your review checklist.--**Step 2: Analyze the diff**-Focus only on new code added in the PR. For each changed file, look for:-- Bugs and logic errors-- Security issues (exposed secrets, injection, XSS)-- Performance problems (unnecessary loops, N+1 queries)-- Violations of CLAUDE.md / AGENTS.md rules (if the file exists)-- Whether tests were added or updated--Do NOT flag:-- Style preferences or minor wording changes-- Issues in unchanged code that existed before the PR-- Missing docstrings, type hints, or comments-- Things that would be caught by a linter or CI--For each file, ask: "Would this change break something or mislead someone?"-If no, move on.--**Step 3: Post your review as a PR comment**-Use this format:--## PR Review--**Summary**: [2-3 sentences on what this PR does]--**Review effort [1-5]**: [1 = trivial, 5 = complex and risky]--### Key issues-| # | File | Lines | Category | Description |-|---|------|-------|----------|-------------|-| 1 | `file.py` | 12-15 | Possible bug | [description] |--Categories: `possible bug`, `security`, `performance`, `best practice`--If no issues found, write "No issues found" instead of the table.--### Security concerns-[Any security issues, or "None"]--### CLAUDE.md / AGENTS.md compliance-[Rule violations, or "No project rules file found" / "All rules followed"]--### Tests-[Were relevant tests added? Yes/No with brief explanation]--Be specific and actionable. Don't invent issues to seem thorough.-If the PR looks good, say so.""",- tools=tools,-)---async def main():- repo = os.environ.get("GITHUB_REPO", "composiohq/composio")- pr_number = os.environ.get("PR_NUMBER", "2800")-- result = await Runner.run(- starting_agent=agent,- input=f"Review pull request #{pr_number} in the {repo} repository.",- )- print(result.final_output)---asyncio.run(main())diff --git a/docs/examples/pr-review-agent/review.yml b/docs/examples/pr-review-agent/review.ymldeleted file mode 100644index 72d4e4d44..000000000--- a/docs/examples/pr-review-agent/review.yml+++ /dev/null@@ -1,28 +0,0 @@-name: PR Review Agent--on:- pull_request:- types: [opened, synchronize]--jobs:- review:- runs-on: ubuntu-latest- steps:- - name: Checkout- uses: actions/checkout@v4-- - name: Set up Python- uses: actions/setup-python@v5- with:- python-version: "3.12"-- - name: Install dependencies- run: pip install composio composio-openai-agents openai-agents-- - name: Run PR review- env:- COMPOSIO_API_KEY: ${{ secrets.COMPOSIO_API_KEY }}- OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}- GITHUB_REPO: ${{ github.repository }}- PR_NUMBER: ${{ github.event.pull_request.number }}- run: python agent.pydiff --git a/docs/examples/slack-summariser/main.py b/docs/examples/slack-summariser/main.pydeleted file mode 100644index 9c656680c..000000000--- a/docs/examples/slack-summariser/main.py+++ /dev/null@@ -1,73 +0,0 @@-import sys--# region setup-from agents import Agent, Runner-from composio import Composio-from composio_openai_agents import OpenAIAgentsProvider--composio = Composio(provider=OpenAIAgentsProvider())-# endregion setup---# region connect-def connect(user_id: str):- """Check if Slack is connected. If not, start OAuth and wait."""- session = composio.create(user_id=user_id, toolkits=["slack"])- toolkits = session.toolkits()-- for t in toolkits.items:- if t.slug == "slack" and t.connection and t.connection.is_active:- print("Slack is already connected.")- return-- connection_request = session.authorize("slack")- print(f"Open this URL to connect Slack:\n{connection_request.redirect_url}")- connection_request.wait_for_connection()- print("Connected.")-# endregion connect---# region summarize-def summarize(user_id: str, channel: str):- """Fetch recent messages from a Slack channel and summarize them."""- session = composio.create(user_id=user_id, toolkits=["slack"])- tools = session.tools()-- agent = Agent(- name="Slack Summarizer",- instructions=(- "You summarize Slack channel messages. "- "Fetch recent messages from the given channel and provide a concise summary "- "of the key topics, decisions, and action items."- ),- tools=tools,- )-- result = Runner.run_sync(- starting_agent=agent,- input=f"Summarize the recent messages from the #{channel} channel.",- )- print(result.final_output)-# endregion summarize---if __name__ == "__main__":- if len(sys.argv) < 2:- print("Usage:")- print(" python main.py connect <user_id>")- print(" python main.py summarize <user_id> <channel>")- sys.exit(1)-- command = sys.argv[1]-- if command == "connect":- user_id = sys.argv[2] if len(sys.argv) > 2 else "default"- connect(user_id)- elif command == "summarize":- user_id = sys.argv[2] if len(sys.argv) > 2 else "default"- channel = sys.argv[3] if len(sys.argv) > 3 else "general"- summarize(user_id, channel)- else:- print(f"Unknown command: {command}")- print("Use 'connect' or 'summarize'.")- sys.exit(1)diff --git a/docs/examples/standup-slackbot/.env.local.example b/docs/examples/standup-slackbot/.env.local.exampledeleted file mode 100644index 52a996593..000000000--- a/docs/examples/standup-slackbot/.env.local.example+++ /dev/null@@ -1,8 +0,0 @@-# Composio API key: https://app.composio.dev/settings-COMPOSIO_API_KEY=-# The "slackbot" auth config the bot connects through (ac_...)-COMPOSIO_SLACKBOT_AUTH_CONFIG_ID=-# Slack app signing secret, verifies interactivity requests-SLACK_SIGNING_SECRET=-# Shared secret the Vercel cron sends as `Authorization: Bearer <CRON_SECRET>`-CRON_SECRET=diff --git a/docs/examples/standup-slackbot/.gitignore b/docs/examples/standup-slackbot/.gitignoredeleted file mode 100644index e7f0a5d29..000000000--- a/docs/examples/standup-slackbot/.gitignore+++ /dev/null@@ -1,5 +0,0 @@-node_modules/-dist/-.env.local-.vercel/-.verceldiff --git a/docs/examples/standup-slackbot/README.md b/docs/examples/standup-slackbot/README.mddeleted file mode 100644index 0b2e5c2fc..000000000--- a/docs/examples/standup-slackbot/README.md+++ /dev/null@@ -1,95 +0,0 @@-# Daily Standup Slack Bot--An AI-powered Slack bot that runs daily standups. On a schedule it DMs each team member a reminder with a **Draft** button. Tapping it spins up a Composio tool-router session scoped to whatever that member has connected (GitHub, Linear, Notion, Calendar, and more), researches their recent activity, and writes a draft standup. The member reviews, edits if needed, and confirms, then the bot posts it into a daily thread in your standup channel as that member.--## How It Works--1. **On a schedule** (`vercel.json` cron, evaluated per-member in their timezone), the bot finds or creates today's thread in your standup channel and DMs each due member a reminder menu: **📝 Draft** and **🔌 Connect more tools**.-2. **Draft** opens a Composio tool-router session scoped to the member's connected toolkits, researches their activity, and writes the draft. No tools connected yet → the menu nudges them to connect first.-3. The member can **✏️ Edit** (a modal) or **✅ Confirm & Post**.-4. On confirm, the bot **posts into the daily thread as the member** (via their personal Slack connection). If they haven't connected personal Slack, it gives them copyable text instead.--Everything runs through Slack **interactivity** (buttons + modals): there are no inbound DM triggers to wire up.--## Stack--- **Runtime:** Vercel Serverless Functions (TypeScript)-- **AI:** Vercel AI SDK via AI Gateway-- **Integrations:** Composio SDK (slackbot + the toolkit catalogue you configure)-- **Database:** None--## Project Layout--```-standup.config.ts ← edit this: team, channel, schedule, toolkit catalogue-.env.local ← secrets (copy from .env.local.example)-api/- cron/standup.ts ← scheduled reminder- interactivity.ts ← button + modal handler- _utils/ ← shared helpers (Vercel ignores _-prefixed dirs as routes)- schedule.ts ← per-member due-checks, lookback window, name/date helpers- composio.ts ← Composio client, connections, tool-router session- slack.ts ← Slack Web API via Composio proxyExecute- agent.ts ← draft generation + the draft prompt- blocks.ts ← Block Kit message builders-scripts/setup.ts ← one-time: connect the bot's Slack account-```--## Setup--### 1. Create a Slack App--1. Go to [api.slack.com/apps](https://api.slack.com/apps) and create an app.-2. Add these **Bot Token Scopes** under OAuth & Permissions:- `chat:write`, `im:write`, `channels:history`, `channels:read`, `users:read`, `users:read.email`, `team:read`.-3. Under **Interactivity & Shortcuts**, turn Interactivity on and set the Request URL to:- `https://<your-deployment>/api/interactivity`-4. Install the app to your workspace and invite the bot to your standup channel.-5. Note your Slack app's **Client ID**, **Client Secret**, and **Signing Secret**.--### 2. Create a `slackbot` Auth Config in Composio--1. Open Auth Configs in the [Composio dashboard](https://app.composio.dev).-2. Toolkit: `slackbot`. Auth scheme: `OAUTH2`.-3. Toggle "Use your own developer credentials" and enter the Slack Client ID/Secret.-4. Add `team:read` to the **User Token Scopes**.-5. Create it and save the auth config ID (`ac_...`).--### 3. Configure secrets and your team--Copy `.env.local.example` to `.env.local` and fill it in:--| Variable | Value |-|----------|-------|-| `COMPOSIO_API_KEY` | Your Composio API key |-| `COMPOSIO_SLACKBOT_AUTH_CONFIG_ID` | The `ac_...` from step 2 |-| `SLACK_SIGNING_SECRET` | Your Slack app signing secret |-| `CRON_SECRET` | Any random string (secures the Vercel cron) |--Then edit `standup.config.ts`: set `standupChannel`, your `team` (slack email + github username, optional per-person time/timezone), and prune the `TOOLKITS` catalogue to the integrations you want.--### 4. Connect the bot's Slack account--```bash-npm install-npx tsx scripts/setup.ts # opens a browser OAuth link for the bot-npx tsx scripts/setup.ts --reconnect # re-run after changing Slack scopes-```--### 5. Deploy--```bash-vercel deploy --prod-```--Set the same four environment variables in the Vercel dashboard. Adjust the cron cadence in `vercel.json` (default: every 30 min on weekdays; each member is reminded only in the slot matching their configured time).--## Connecting member tools--Each member connects their own accounts (GitHub, Linear, etc.) by tapping **🔌 Connect more tools** on the reminder DM, and the bot generates per-member OAuth links on the fly. Drafts only ever pull from what a member has actually connected.--## Customizing--- **Add or remove a toolkit:** edit the `TOOLKITS` array in `standup.config.ts`. Each entry is a slug, label, emoji, and a `draftInstruction` that tells the agent what to pull and how to summarize it. No other code changes needed.-- **Change scope/wording:** the `draftInstruction` is where source-specific rules live (e.g. GitHub is scoped to a single org there).-- **Demo mode:** set `DEMO_MODE = true` in `standup.config.ts` to make every member due on every cron run.diff --git a/docs/examples/standup-slackbot/api/_utils/agent.ts b/docs/examples/standup-slackbot/api/_utils/agent.tsdeleted file mode 100644index 99ae43ec5..000000000--- a/docs/examples/standup-slackbot/api/_utils/agent.ts+++ /dev/null@@ -1,72 +0,0 @@-import { generateText, stepCountIs } from "ai";-import { Member, MODEL, TOOLKITS, GITHUB_ORG } from "../../standup.config";-import { lookbackWindow } from "./schedule";-import { createToolRouterSession } from "./composio";--/** The standup draft prompt, adapted to whichever toolkits the member connected. */-function buildDraftPrompt(- member: Member,- window: { date: string; label: string },- connectedSlugs: string[]-): string {- const connected = TOOLKITS.filter((t) => connectedSlugs.includes(t.slug));- const sources = connected.map((t) => ` - ${t.draftInstruction}`).join("\n");- const emojiLegend = connected.map((t) => `${t.emoji} ${t.label}`).join(", ");-- return `You are writing @${member.githubUsername}'s daily standup, covering-${window.label} (everything since ${window.date}).--You have a Composio tool-router session with these tools connected:-${connected.map((t) => t.label).join(", ")}.-Use the meta-tools to research yourself: search for the right tool per source,-then execute it. Do NOT guess activity. Investigate first, then write.--IMPORTANT: All tools above are ALREADY connected. Do NOT attempt to connect,-authenticate, or generate OAuth links. If a tool call fails, skip that source.-Never ask the user to connect anything.--What to look at (ONLY these connected sources):-${sources}--Keep tool requests small (filter by date, ~10 items, no full transcripts).--Output rules:- - 2 to 5 atomic, one-line updates. Prune noise.- - Start each line with the right source emoji: ${emojiLegend}. GitHub PRs use- 🟣 merged, 🟢 open, ⚪️ draft, 🔴 closed and include the *#number*.- - State WHAT they did and WHY it matters, plainly. Facts only, no speculation.- - NEVER use em dashes. Use colons, commas, or separate sentences.- - LINKS: this is posted to Slack, which does NOT support Markdown links. NEVER- write [text](url). Use Slack's link syntax <url|text> instead, e.g.- <https://github.com/${GITHUB_ORG}/repo/pull/893|#893>. A bare URL is also fine.- - CRITICAL: your reply is posted to Slack VERBATIM. It must contain ONLY the- bullet lines, each starting with its source emoji. No preamble ("Here's the- standup"), no narration ("I found 3 PRs"), no headings, no closing remarks,- no sign-off. The very first character of your reply is the first bullet's emoji.- - If no activity in range, your entire reply is exactly: "📭 No tracked activity ${window.label}."`;-}--/**- * Generate a member's standup draft by researching their CONNECTED tools. Spins- * up a Composio tool-router session scoped to those toolkits and lets the agent- * drive the meta-tools to gather activity. Returns the draft text only.- */-export async function generateDraftText(- member: Member,- connectedSlugs: string[]-): Promise<string> {- if (connectedSlugs.length === 0) return "";-- const session = await createToolRouterSession(member.slackEmail, connectedSlugs);- const tools = await session.tools();-- const { text } = await generateText({- model: MODEL,- system: buildDraftPrompt(member, lookbackWindow(member.standupTimezone), connectedSlugs),- prompt: `Research and write @${member.githubUsername}'s standup update.`,- tools,- stopWhen: stepCountIs(40),- });-- return text.trim();-}diff --git a/docs/examples/standup-slackbot/api/_utils/blocks.ts b/docs/examples/standup-slackbot/api/_utils/blocks.tsdeleted file mode 100644index 651ad0bd6..000000000--- a/docs/examples/standup-slackbot/api/_utils/blocks.ts+++ /dev/null@@ -1,212 +0,0 @@-// Block Kit builders for the standup menu / confirm / edit / connect flow.-// Plain data (no agent involvement) keeps the interactive messages deterministic.--export const ACTION_DRAFT = "standup_draft";-export const ACTION_CONNECT = "standup_connect";-export const ACTION_CONFIRM = "standup_confirm";-export const ACTION_EDIT = "standup_edit";-export const MODAL_EDIT_SUBMIT = "standup_edit_submit";-export const EDIT_INPUT_BLOCK = "standup_edit_block";-export const EDIT_INPUT_ACTION = "standup_edit_input";-// Stable id for the draft-body section, so the handler can recover the draft-// text by block_id instead of a fragile positional index.-export const DRAFT_BODY_BLOCK = "standup_draft_body";--// Context threaded through buttons/modals so the handler knows who/where without-// re-deriving it. Kept small (button `value` is capped at 2000 chars).-export type StandupContext = {- memberEmail: string;- threadTs: string; // parent daily-thread message ts- channelId: string; // the standup channel's ID-};--/** The daily reminder "menu": a nudge + Draft button (+ Connect if applicable). */-export function buildReminderMenu(- threadUrl: string,- ctx: StandupContext,- showConnect: boolean-) {- const value = JSON.stringify(ctx);- const buttons: Record<string, unknown>[] = [- {- type: "button",- style: "primary",- text: { type: "plain_text", text: "📝 Draft", emoji: true },- action_id: ACTION_DRAFT,- value,- },- ];- if (showConnect) {- buttons.push({- type: "button",- text: { type: "plain_text", text: "🔌 Connect more tools", emoji: true },- action_id: ACTION_CONNECT,- value,- });- }- return {- text: "Daily standup reminder",- blocks: [- {- type: "section",- text: {- type: "mrkdwn",- text: `📅 Time for your standup. Post your update in <${threadUrl}|today's thread>.\nTap *Draft* and I'll put together a draft from your connected tools.`,- },- },- { type: "actions", elements: buttons },- ],- };-}--/** "Researching…" placeholder shown while the draft is generated. */-export function buildLoadingMessage(label = "Researching your activity and drafting your standup…") {- return {- text: label,- blocks: [{ type: "section", text: { type: "mrkdwn", text: `⏳ ${label}` } }],- };-}--/** The draft DM: the draft text + Confirm/Edit buttons. */-export function buildDraftMessage(draft: string, ctx: StandupContext) {- const value = JSON.stringify(ctx);- const body = draft.trim()- ? draft- : "_No draft yet. Tap ✏️ Edit to write your update._";- return {- text: "Your standup draft is ready for review.",- blocks: [- {- type: "section",- text: { type: "mrkdwn", text: "*Your standup draft.* Review and post 👇" },- },- { type: "section", block_id: DRAFT_BODY_BLOCK, text: { type: "mrkdwn", text: body } },- { type: "divider" },- {- type: "actions",- elements: [- {- type: "button",- style: "primary",- text: { type: "plain_text", text: "✅ Confirm & Post", emoji: true },- action_id: ACTION_CONFIRM,- value,- },- {- type: "button",- text: { type: "plain_text", text: "✏️ Edit", emoji: true },- action_id: ACTION_EDIT,- value,- },- ],- },- ],- };-}--type DraftMessage = {- blocks?: Array<{ block_id?: string; text?: { text?: string } }>;-};--/** Recover the draft text from a posted draft message, by stable block_id. */-export function extractDraft(message: DraftMessage): string {- const block = (message.blocks ?? []).find(- (b) => b.block_id === DRAFT_BODY_BLOCK- );- return block?.text?.text ?? "";-}--/** Shown after posting from the user's own Slack account. */-export function buildPostedMessage(draft: string) {- return {- text: "Standup posted.",- blocks: [- { type: "section", text: { type: "mrkdwn", text: "✅ *Posted to the standup thread.*" } },- { type: "section", text: { type: "mrkdwn", text: draft } },- ],- };-}--/** Fallback when the member has no personal Slack: copyable text + thread link. */-export function buildCopyMessage(draft: string, threadUrl: string) {- return {- text: "Copy your standup into the thread.",- blocks: [- {- type: "section",- text: {- type: "mrkdwn",- text: `Here's your standup. Copy it and paste it into <${threadUrl}|today's thread>:`,- },- },- { type: "section", text: { type: "mrkdwn", text: "```" + draft + "```" } },- {- type: "context",- elements: [- {- type: "mrkdwn",- text: "_Connect your Slack (tap Connect on the reminder) to have me post it for you next time._",- },- ],- },- ],- };-}--/** Connect menu: one URL button per unconnected tool (opens its OAuth link). */-export function buildConnectMenu(links: { label: string; url: string }[]) {- // Slack actions blocks allow max 5 elements; chunk into rows of 5.- const rows: Record<string, unknown>[] = [];- for (let i = 0; i < links.length; i += 5) {- rows.push({- type: "actions",- elements: links.slice(i, i + 5).map((l) => ({- type: "button",- text: { type: "plain_text", text: `Connect ${l.label}`, emoji: true },- url: l.url,- })),- });- }- return {- text: "Connect tools to enrich your standup drafts.",- blocks: [- {- type: "section",- text: {- type: "mrkdwn",- text: "*Connect your tools* so I can draft from your real activity. All optional:",- },- },- ...rows,- ],- };-}--/** Edit modal: multiline input prefilled with the current draft. */-export function buildEditModal(- draft: string,- ctx: StandupContext,- dm: { channel: string; ts: string }-) {- return {- type: "modal",- callback_id: MODAL_EDIT_SUBMIT,- private_metadata: JSON.stringify({ ...ctx, dmChannel: dm.channel, dmTs: dm.ts }),- title: { type: "plain_text", text: "Edit standup" },- submit: { type: "plain_text", text: "Save" },- close: { type: "plain_text", text: "Cancel" },- blocks: [- {- type: "input",- block_id: EDIT_INPUT_BLOCK,- label: { type: "plain_text", text: "Your standup update" },- element: {- type: "plain_text_input",- action_id: EDIT_INPUT_ACTION,- multiline: true,- initial_value: draft,- },- },- ],- };-}diff --git a/docs/examples/standup-slackbot/api/_utils/composio.ts b/docs/examples/standup-slackbot/api/_utils/composio.tsdeleted file mode 100644index f87a72fd7..000000000--- a/docs/examples/standup-slackbot/api/_utils/composio.ts+++ /dev/null@@ -1,111 +0,0 @@-import { Composio } from "@composio/core";-import { VercelProvider } from "@composio/vercel";-import { TOOLKIT_SLUGS } from "../../standup.config";-import { env } from "./env";--export const composio = new Composio({- apiKey: env.COMPOSIO_API_KEY,- provider: new VercelProvider(),-});--// The bot's own Composio user. The slackbot OAuth connection lives here, so all-// bot Slack actions (posting to the channel, DMing members) execute as the bot.-export const BOT_USER = "default";--/** Active connected accounts for a user, optionally filtered to one toolkit.- * Filters server-side via `statuses` so we never see stale/expired ones. */-export async function listActiveAccounts(userId: string, toolkitSlug?: string) {- const res = await composio.connectedAccounts.list({- userIds: [userId],- statuses: ["ACTIVE"],- ...(toolkitSlug ? { toolkitSlugs: [toolkitSlug] } : {}),- });- return res.items;-}--// The bot's slackbot connected-account ID. proxyExecute needs it so the call-// authenticates as the bot (the project has several connections, so we can't-// rely on a default-account fallback). Resolved once and memoized.-let botAccountIdPromise: Promise<string | undefined> | undefined;-function getBotAccountId(): Promise<string | undefined> {- botAccountIdPromise ??= listActiveAccounts(BOT_USER, "slackbot")- .then((accounts) => accounts[0]?.id)- .then((id) => {- // Don't cache a miss: if the bot isn't connected yet, retry next call so a- // later setup/OAuth is picked up without waiting for a cold start.- if (!id) botAccountIdPromise = undefined;- return id;- });- return botAccountIdPromise;-}--// Wraps Composio's proxyExecute to call any Slack Web API endpoint as the bot-// (or a member, via accountId). Covers what the named SLACKBOT_* tools don't,-// like views.open for modals.-export async function slackApi<T = unknown>(- endpoint: string,- method: "GET" | "POST",- body?: Record<string, unknown>,- accountId?: string // override the bot account (e.g. post as a member)-): Promise<T> {- const connectedAccountId = accountId ?? (await getBotAccountId());- const res = await composio.tools.proxyExecute({- endpoint,- method,- ...(body ? { body } : {}),- ...(connectedAccountId ? { connectedAccountId } : {}),- });- // proxyExecute wraps Slack's JSON response in `data`.- return ((res as { data?: unknown }).data ?? res) as T;-}--/** Run a named Composio tool as a user (the bot by default). This is the normal- * path for actions a SLACKBOT or SLACK tool covers (sending a message, even- * one with Block Kit buttons, updating one, posting as a member). Returns the- * tool's `data`, which is the Slack API response. */-export async function slackTool<T = Record<string, unknown>>(- slug: string,- args: Record<string, unknown>,- userId: string = BOT_USER-): Promise<T> {- const res = await composio.tools.execute(slug, { userId, arguments: args });- return (res.data ?? {}) as T;-}--/** Which catalogue toolkits the member has actively connected. */-export async function getConnectedIntegrations(- memberEmail: string-): Promise<string[]> {- const active = await listActiveAccounts(memberEmail);- const slugs = new Set(active.map((a) => a.toolkit.slug));- return TOOLKIT_SLUGS.filter((s) => slugs.has(s));-}--/** Generate an OAuth connect link for one toolkit, for one member. */-export async function getConnectLink(- memberEmail: string,- toolkitSlug: string-): Promise<string | null> {- try {- const conn = await composio.toolkits.authorize(memberEmail, toolkitSlug);- return conn.redirectUrl ?? null;- } catch {- return null;- }-}--/**- * A tool-router session scoped to the given toolkits. `session.tools()` returns- * Composio's research meta-tools (search/execute/workbench) limited to these- * toolkits. `manageConnections: false` strips the connection meta-tools so the- * draft agent can research but never initiate an OAuth flow mid-draft.- */-export async function createToolRouterSession(- memberEmail: string,- toolkitSlugs: string[]-) {- return composio.create(memberEmail, {- toolkits: toolkitSlugs,- manageConnections: false,- });-}diff --git a/docs/examples/standup-slackbot/api/_utils/env.ts b/docs/examples/standup-slackbot/api/_utils/env.tsdeleted file mode 100644index d4e31aa6b..000000000--- a/docs/examples/standup-slackbot/api/_utils/env.ts+++ /dev/null@@ -1,31 +0,0 @@-import { config } from "dotenv";--// Load .env.local for local runs (scripts, `vercel dev`). Harmless on Vercel,-// where the file is absent and real environment variables are already set.-config({ path: ".env.local" });--// Validate every required var once at import time, so a misconfigured deploy-// fails fast with a clear message instead of a vague error mid-request.-const REQUIRED = [- "COMPOSIO_API_KEY",- "COMPOSIO_SLACKBOT_AUTH_CONFIG_ID", // the "slackbot" auth config (ac_...)- "SLACK_SIGNING_SECRET", // verifies Slack interactivity requests- "CRON_SECRET", // shared secret the Vercel cron presents-] as const;--type EnvKey = (typeof REQUIRED)[number];--function loadEnv(): Record<EnvKey, string> {- const missing = REQUIRED.filter((key) => !process.env[key]);- if (missing.length > 0) {- throw new Error(- `Missing required environment variable(s): ${missing.join(", ")}.\n` +- `Copy .env.local.example to .env.local and fill them in.`- );- }- return Object.fromEntries(- REQUIRED.map((key) => [key, process.env[key]!])- ) as Record<EnvKey, string>;-}--export const env = loadEnv();diff --git a/docs/examples/standup-slackbot/api/_utils/schedule.ts b/docs/examples/standup-slackbot/api/_utils/schedule.tsdeleted file mode 100644index cb7a314a9..000000000--- a/docs/examples/standup-slackbot/api/_utils/schedule.ts+++ /dev/null@@ -1,53 +0,0 @@-import dayjs from "dayjs";-import utc from "dayjs/plugin/utc";-import timezone from "dayjs/plugin/timezone";-import {- Member,- DEFAULT_STANDUP_TIME,- DEFAULT_STANDUP_TIMEZONE,- CRON_SLOT_MINUTES,- DEMO_MODE,-} from "../../standup.config";--dayjs.extend(utc);-dayjs.extend(timezone);--/** "soham.basu@…" → "Soham Basu". Keeps raw emails out of the public channel. */-export function memberName(member: Member): string {- return member.slackEmail- .split("@")[0]- .split(/[._]/)- .map((p) => p.charAt(0).toUpperCase() + p.slice(1))- .join(" ");-}--export function formatToday(): string {- return dayjs().tz(DEFAULT_STANDUP_TIMEZONE).format("dddd, MMMM D, YYYY");-}--/** Draft lookback: Monday reaches back to Friday, else the previous day.- * Computed in the member's own timezone so the window matches their day. */-export function lookbackWindow(- timezone: string = DEFAULT_STANDUP_TIMEZONE-): { date: string; label: string } {- const now = dayjs().tz(timezone);- const days = now.day() === 1 ? 3 : 1;- return {- date: now.subtract(days, "day").format("YYYY-MM-DD"),- label: days === 1 ? "since yesterday" : "since your last standup",- };-}--const memberStandupTime = (m: Member) => m.standupTime ?? DEFAULT_STANDUP_TIME;-const memberTimezone = (m: Member) => m.standupTimezone ?? DEFAULT_STANDUP_TIMEZONE;--/** Is this member due in the current cron slot, evaluated in their timezone? */-export function isMemberDue(member: Member): boolean {- if (DEMO_MODE) return true;- const now = dayjs().tz(memberTimezone(member));- const nowMin = now.hour() * 60 + now.minute();- const slotStart = Math.floor(nowMin / CRON_SLOT_MINUTES) * CRON_SLOT_MINUTES;- const [h, m] = memberStandupTime(member).split(":").map(Number);- const memberMin = h * 60 + m;- return memberMin >= slotStart && memberMin < slotStart + CRON_SLOT_MINUTES;-}diff --git a/docs/examples/standup-slackbot/api/_utils/slack.ts b/docs/examples/standup-slackbot/api/_utils/slack.tsdeleted file mode 100644index 5fa875e70..000000000--- a/docs/examples/standup-slackbot/api/_utils/slack.ts+++ /dev/null@@ -1,146 +0,0 @@-import { slackApi, slackTool, listActiveAccounts } from "./composio";--// The subset of Slack Web API response fields this bot reads. proxyExecute-// returns the raw Slack JSON, so one shared shape keeps call sites typed.-type SlackResponse = {- ok?: boolean;- error?: string;- ts?: string;- channel?: string;- permalink?: string;- user?: { id?: string };- channels?: Array<{ id: string; name: string }>;- messages?: Array<{ ts: string; text?: string }>;- response_metadata?: { next_cursor?: string };-};--export async function findUserIdByEmail(email: string): Promise<string | null> {- const data = await slackApi<SlackResponse>(- `/users.lookupByEmail?email=${encodeURIComponent(email)}`,- "GET"- );- return data.user?.id ?? null;-}--/** Resolve a channel ID from a "#channel-name" (or bare name). */-export async function findChannelId(channelName: string): Promise<string | null> {- const name = channelName.replace(/^#/, "");- let cursor: string | undefined;- for (let i = 0; i < 10; i++) {- const qs = new URLSearchParams({- types: "public_channel,private_channel",- limit: "200",- ...(cursor ? { cursor } : {}),- });- const data = await slackApi<SlackResponse>(`/conversations.list?${qs.toString()}`, "GET");- const match = (data.channels ?? []).find((c) => c.name === name);- if (match) return match.id;- cursor = data.response_metadata?.next_cursor || undefined;- if (!cursor) break;- }- return null;-}--/** Fetch recent top-level messages in a channel (newest first; threaded replies excluded). */-export async function getRecentMessages(- channelId: string,- limit = 50-): Promise<Array<{ ts: string; text: string }>> {- const data = await slackApi<SlackResponse>(- `/conversations.history?channel=${encodeURIComponent(channelId)}&limit=${limit}`,- "GET"- );- return (data.messages ?? []).map((m) => ({ ts: m.ts, text: m.text ?? "" }));-}--export async function postMessage(- channel: string,- text: string,- opts?: { thread_ts?: string; blocks?: unknown[] }-): Promise<{ ts: string } | null> {- // SLACKBOT_SEND_MESSAGE is the named tool: markdown_text for prose, or Block- // Kit `blocks` (buttons included). channel must be a channel/DM id, not a user id.- const data = await slackTool<SlackResponse>("SLACKBOT_SEND_MESSAGE", {- channel,- ...(opts?.blocks ? { blocks: opts.blocks } : { markdown_text: text }),- ...(opts?.thread_ts ? { thread_ts: opts.thread_ts } : {}),- });- return data.ts ? { ts: data.ts } : null;-}--// Stays on the proxy: this opens a DM by passing a user id as the channel, which-// the raw chat.postMessage allows but SLACKBOT_SEND_MESSAGE rejects (it wants a-// pre-opened D… channel id). The proxy lets us DM the member in one call.-export async function sendDmBlocks(- userId: string,- text: string,- blocks: unknown[]-): Promise<{ channel: string; ts: string } | null> {- const data = await slackApi<SlackResponse>("/chat.postMessage", "POST", {- channel: userId,- text,- blocks,- });- if (!data.ok || !data.channel || !data.ts) return null;- return { channel: data.channel, ts: data.ts };-}--/** Update an existing message (e.g. swap the draft after an edit). The named- * tool SLACKBOT_UPDATES_A_MESSAGE takes Block Kit blocks just like sending. */-export async function updateMessage(- channel: string,- ts: string,- _text: string,- blocks: unknown[]-): Promise<boolean> {- const data = await slackTool<SlackResponse>("SLACKBOT_UPDATES_A_MESSAGE", { channel, ts, blocks });- return data.ok !== false;-}--/** Permalink to a message (used to link members to today's thread). */-export async function getPermalink(- channel: string,- ts: string-): Promise<string | null> {- const data = await slackApi<SlackResponse>(- `/chat.getPermalink?channel=${encodeURIComponent(channel)}&message_ts=${ts}`,- "GET"- );- return data.permalink ?? null;-}--/** The member's OWN active Slack connected-account id (for posting as them). */-async function getMemberSlackAccountId(- memberEmail: string-): Promise<string | undefined> {- const [active] = await listActiveAccounts(memberEmail, "slack");- return active?.id;-}--/**- * Post into the thread AS the member, using their personal Slack connection.- * SLACK_SEND_MESSAGE (the slack user toolkit) run under their email as the- * userId, so it posts under their name. Returns false if they have no active- * personal Slack account.- */-export async function postAsUser(- memberEmail: string,- channel: string,- text: string,- threadTs: string-): Promise<boolean> {- const accountId = await getMemberSlackAccountId(memberEmail);- if (!accountId) return false;- const data = await slackTool<SlackResponse>(- "SLACK_SEND_MESSAGE",- { channel, markdown_text: text, thread_ts: threadTs },- memberEmail- );- return data.ok !== false;-}--/** Open a modal in response to a button click (needs trigger_id, <3s). */-export async function openModal(triggerId: string, view: unknown): Promise<boolean> {- const data = await slackApi<SlackResponse>("/views.open", "POST", { trigger_id: triggerId, view });- return !!data.ok;-}diff --git a/docs/examples/standup-slackbot/api/cron/standup.ts b/docs/examples/standup-slackbot/api/cron/standup.tsdeleted file mode 100644index e6e07ea37..000000000--- a/docs/examples/standup-slackbot/api/cron/standup.ts+++ /dev/null@@ -1,98 +0,0 @@-import type { VercelRequest, VercelResponse } from "@vercel/node";-import { team, standupChannel, TOOLKITS } from "../../standup.config";-import { formatToday, isMemberDue } from "../_utils/schedule";-import { getConnectedIntegrations } from "../_utils/composio";-import { buildReminderMenu } from "../_utils/blocks";-import {- findChannelId,- getRecentMessages,- postMessage,- getPermalink,- findUserIdByEmail,- sendDmBlocks,-} from "../_utils/slack";-import { env } from "../_utils/env";--export const maxDuration = 300;--export default async function handler(req: VercelRequest, res: VercelResponse) {- if (req.headers.authorization !== `Bearer ${env.CRON_SECRET}`) {- return res.status(401).json({ error: "Unauthorized" });- }-- const results: { member: string; status: string }[] = [];- // One shared thread per calendar day, keyed to the team timezone on purpose:- // everyone posts into the same thread even though reminders fire in each- // member's local time. (Per-member timezone here would fork the thread.)- const today = formatToday();-- // Only members whose configured time falls in this 30-minute slot.- const dueMembers = team.filter(isMemberDue);- if (dueMembers.length === 0) {- return res.status(200).json({ status: "no members due this slot" });- }-- try {- // Resolve the channel and find or create today's thread.- const channelId = await findChannelId(standupChannel);- if (!channelId) {- return res.status(500).json({- error: `Channel ${standupChannel} not found. Is the bot a member?`,- });- }-- const parentText = `📅 *Daily Standup: ${today}*\n_Standups are posted in this thread as folks confirm._`;- // Scan a generous window for today's parent. A high-volume channel could push- // it past this; a production bot would paginate or persist the thread ts.- const recent = await getRecentMessages(channelId, 200);- const threadTs =- recent.find((m) => m.text.includes("Daily Standup") && m.text.includes(today))- ?.ts ?? (await postMessage(channelId, parentText))?.ts;- if (!threadTs) {- return res.status(500).json({ error: "Failed to create daily thread" });- }- // Narrowed const so the per-member closure below sees a plain string.- const thread = threadTs;- const threadUrl = (await getPermalink(channelId, thread)) ?? "";-- // DM each due member the reminder menu, in parallel.- async function processMember(- member: (typeof team)[number]- ): Promise<{ member: string; status: string }> {- try {- const [connected, userId] = await Promise.all([- getConnectedIntegrations(member.slackEmail),- findUserIdByEmail(member.slackEmail),- ]);- const showConnect = connected.length < TOOLKITS.length;-- if (!userId) {- return { member: member.slackEmail, status: "error: no slack user" };- }-- const menu = buildReminderMenu(- threadUrl,- { memberEmail: member.slackEmail, threadTs: thread, channelId: channelId! },- showConnect- );- const dm = await sendDmBlocks(userId, menu.text, menu.blocks);- return {- member: member.slackEmail,- status: dm ? "reminded" : "error: dm failed",- };- } catch (error) {- const errMsg = error instanceof Error ? error.message : String(error);- return { member: member.slackEmail, status: `error: ${errMsg}` };- }- }-- results.push(...(await Promise.all(dueMembers.map(processMember))));- return res.status(200).json({ threadTs, threadUrl, results });- } catch (err) {- return res.status(500).json({- error: "Internal server error",- message: err instanceof Error ? err.message : String(err),- results,- });- }-}diff --git a/docs/examples/standup-slackbot/api/interactivity.ts b/docs/examples/standup-slackbot/api/interactivity.tsdeleted file mode 100644index a9dbeb796..000000000--- a/docs/examples/standup-slackbot/api/interactivity.ts+++ /dev/null@@ -1,249 +0,0 @@-import type { VercelRequest, VercelResponse } from "@vercel/node";-import { waitUntil } from "@vercel/functions";-import crypto from "crypto";-import { team, TOOLKITS } from "../standup.config";-import { memberName } from "./_utils/schedule";-import {- ACTION_DRAFT,- ACTION_CONNECT,- ACTION_CONFIRM,- ACTION_EDIT,- MODAL_EDIT_SUBMIT,- EDIT_INPUT_BLOCK,- EDIT_INPUT_ACTION,- buildLoadingMessage,- buildDraftMessage,- buildPostedMessage,- buildCopyMessage,- buildConnectMenu,- buildEditModal,- extractDraft,- StandupContext,-} from "./_utils/blocks";-import { getConnectedIntegrations, getConnectLink } from "./_utils/composio";-import { generateDraftText } from "./_utils/agent";-import {- openModal,- postMessage,- updateMessage,- postAsUser,- getPermalink,-} from "./_utils/slack";-import { env } from "./_utils/env";--export const maxDuration = 300;--// Disable Vercel's body parsing: Slack signs the EXACT raw bytes.-export const config = { api: { bodyParser: false } };--// The subset of a Slack interaction payload this handler reads.-type SlackAction = { action_id?: string; value?: string };-type SlackInteraction = {- type?: string;- trigger_id?: string;- actions?: SlackAction[];- message?: { ts?: string; blocks?: Array<{ block_id?: string; text?: { text?: string } }> };- container?: { channel_id?: string };- channel?: { id?: string };- view?: {- callback_id?: string;- private_metadata?: string;- state?: { values?: Record<string, Record<string, { value?: string }>> };- };-};-// What buildEditModal stuffs into the modal's private_metadata.-type StoredMeta = StandupContext & { dmChannel?: string; dmTs?: string };--function readRawBody(req: VercelRequest): Promise<string> {- return new Promise((resolve) => {- if (typeof req.body === "string") return resolve(req.body);- if (req.body && Buffer.isBuffer(req.body)) return resolve(req.body.toString("utf8"));- let data = "";- req.setEncoding?.("utf8");- req.on("data", (c) => (data += c));- req.on("end", () => resolve(data));- req.on("error", () => resolve(data));- });-}--// Implements Slack's documented request-verification algorithm (v0 basestring,-// 5-minute replay window, constant-time HMAC-SHA256 compare):-// https://docs.slack.dev/authentication/verifying-requests-from-slack-function verifySlackSignature(- rawBody: string,- signature: string | undefined,- timestamp: string | undefined,- signingSecret: string-): boolean {- if (!signature || !timestamp) return false;- const age = Math.abs(Date.now() / 1000 - Number(timestamp));- if (!Number.isFinite(age) || age > 300) return false;- const hmac =- "v0=" +- crypto- .createHmac("sha256", signingSecret)- .update(`v0:${timestamp}:${rawBody}`)- .digest("hex");- try {- return crypto.timingSafeEqual(Buffer.from(hmac), Buffer.from(signature));- } catch {- return false;- }-}--export default async function handler(req: VercelRequest, res: VercelResponse) {- if (req.method !== "POST") {- return res.status(405).json({ error: "Method not allowed" });- }-- const rawBody = await readRawBody(req);- if (- !verifySlackSignature(- rawBody,- req.headers["x-slack-signature"] as string,- req.headers["x-slack-request-timestamp"] as string,- env.SLACK_SIGNING_SECRET- )- ) {- return res.status(401).json({ error: "Invalid signature" });- }-- const payload: SlackInteraction = JSON.parse(- new URLSearchParams(rawBody).get("payload") || "{}"- );-- // Modal submit (edits): fast, respond inline.- if (payload.type === "view_submission") {- if (payload.view?.callback_id === MODAL_EDIT_SUBMIT) {- const meta: StoredMeta = JSON.parse(payload.view.private_metadata || "{}");- const ctx: StandupContext = {- memberEmail: meta.memberEmail,- threadTs: meta.threadTs,- channelId: meta.channelId,- };- const edited =- payload.view.state?.values?.[EDIT_INPUT_BLOCK]?.[EDIT_INPUT_ACTION]- ?.value ?? "";- const msg = buildDraftMessage(edited, ctx);- if (meta.dmChannel && meta.dmTs) {- await updateMessage(meta.dmChannel, meta.dmTs, msg.text, msg.blocks);- }- }- return res.status(200).send("");- }-- if (payload.type !== "block_actions") return res.status(200).send("");-- const action = payload.actions?.[0];- const ctx: StandupContext = JSON.parse(action?.value || "{}");- const dmChannel = payload.container?.channel_id ?? payload.channel?.id;- const dmTs = payload.message?.ts;- if (!dmChannel || !dmTs) return res.status(200).send("");-- // Edit opens a modal: must use trigger_id within ~3s, so handle inline.- if (action?.action_id === ACTION_EDIT) {- const draft = extractDraft(payload.message ?? {});- await openModal(- payload.trigger_id ?? "",- buildEditModal(draft, ctx, { channel: dmChannel, ts: dmTs })- );- return res.status(200).send("");- }-- // Slow work (AI draft, OAuth links, posting): ack within Slack's 3s window,- // then run via waitUntil, which keeps the function alive after the response is- // sent. A plain post-send await would be frozen by Vercel.- waitUntil(- processSlowAction(action, ctx, dmChannel, dmTs, payload).catch(async (err) => {- // Don't leave the member stuck on the loading message: log and tell them.- console.error("standup interaction failed:", err);- await postMessage(- dmChannel,- "⚠️ Something went wrong handling that. Please try again."- ).catch(() => {});- })- );- return res.status(200).send("");-}--async function processSlowAction(- action: SlackAction | undefined,- ctx: StandupContext,- dmChannel: string,- dmTs: string,- payload: SlackInteraction-) {- const member = team.find((m) => m.slackEmail === ctx.memberEmail);-- if (action?.action_id === ACTION_DRAFT) {- const loading = buildLoadingMessage();- await updateMessage(dmChannel, dmTs, loading.text, loading.blocks);-- const connected = await getConnectedIntegrations(ctx.memberEmail);- const draft =- member && connected.length- ? await generateDraftText(member, connected)- : "";- const msg = buildDraftMessage(draft, ctx);- await updateMessage(dmChannel, dmTs, msg.text, msg.blocks);- return;- }-- if (action?.action_id === ACTION_CONNECT) {- const connected = await getConnectedIntegrations(ctx.memberEmail);- const unconnected = TOOLKITS.filter((t) => !connected.includes(t.slug));- const links = (- await Promise.all(- unconnected.map(async (t) => {- const url = await getConnectLink(ctx.memberEmail, t.slug);- return url ? { label: t.label, url } : null;- })- )- ).filter(Boolean) as { label: string; url: string }[];-- if (unconnected.length === 0) {- await postMessage(dmChannel, "You're already connected to everything! 🎉");- } else if (links.length === 0) {- // Toolkits remain, but every connect link failed to generate.- await postMessage(- dmChannel,- "⚠️ Couldn't generate connect links right now. Please try again in a moment."- );- } else {- const menu = buildConnectMenu(links);- await postMessage(dmChannel, menu.text, { blocks: menu.blocks });- }- return;- }-- if (action?.action_id === ACTION_CONFIRM) {- const draft = extractDraft(payload.message ?? {});- // Swap the buttons out immediately so a double-click can't post twice.- const posting = buildLoadingMessage("Posting your standup…");- await updateMessage(dmChannel, dmTs, posting.text, posting.blocks);-- const name = member ? memberName(member) : ctx.memberEmail;- const connected = await getConnectedIntegrations(ctx.memberEmail);-- let posted = false;- if (connected.includes("slack")) {- posted = await postAsUser(- ctx.memberEmail,- ctx.channelId,- `*${name}'s standup*\n${draft}`,- ctx.threadTs- );- }-- if (posted) {- const m = buildPostedMessage(draft);- await updateMessage(dmChannel, dmTs, m.text, m.blocks);- } else {- // No personal Slack (or post failed): give them copyable text.- const url = (await getPermalink(ctx.channelId, ctx.threadTs)) ?? "";- const m = buildCopyMessage(draft, url);- await updateMessage(dmChannel, dmTs, m.text, m.blocks);- }- return;- }-}diff --git a/docs/examples/standup-slackbot/package.json b/docs/examples/standup-slackbot/package.jsondeleted file mode 100644index 1ea4ee927..000000000--- a/docs/examples/standup-slackbot/package.json+++ /dev/null@@ -1,24 +0,0 @@-{- "name": "standup-slackbot",- "version": "1.0.0",- "private": true,- "scripts": {- "dev": "vercel dev",- "build": "tsc",- "typecheck": "tsc --noEmit"- },- "dependencies": {- "@composio/core": "latest",- "@composio/vercel": "latest",- "@vercel/functions": "^3.7.2",- "ai": "latest",- "dayjs": "^1.11.21",- "dotenv": "^17.4.2"- },- "devDependencies": {- "@types/node": "^20",- "@vercel/node": "^5.8.18",- "typescript": "^5",- "vercel": "latest"- }-}diff --git a/docs/examples/standup-slackbot/scripts/setup.ts b/docs/examples/standup-slackbot/scripts/setup.tsdeleted file mode 100644index 5e508396c..000000000--- a/docs/examples/standup-slackbot/scripts/setup.ts+++ /dev/null@@ -1,139 +0,0 @@-import { Composio } from "@composio/core";-import { env } from "../api/_utils/env";--// One-time setup: connect the bot's Slack ("slackbot") account so it can post to-// the channel and DM members. Run with `npx tsx scripts/setup.ts`, or-// `--reconnect` to clear and re-do the OAuth (needed after changing Slack scopes).-const COMPOSIO_BASE_URL = "https://backend.composio.dev";-const TOOLKIT_SLUG = "slackbot";--// Scopes the bot's OAuth *user* token must carry. Composio freezes the scopes at-// connect time, so we check them before connecting and tell the user what to add.-const REQUIRED_USER_SCOPES = ["team:read"];--const log = {- ok: (msg: string) => console.log(` ✅ ${msg}`),- info: (msg: string) => console.log(` · ${msg}`),- warn: (msg: string) => console.log(` ⚠️ ${msg}`),-};--function errMessage(err: unknown): string {- if (err && typeof err === "object") {- const e = err as {- error?: { error?: { message?: string }; message?: string };- message?: string;- };- return e.error?.error?.message ?? e.error?.message ?? e.message ?? String(err);- }- return String(err);-}--async function main() {- const RECONNECT = process.argv.includes("--reconnect");-- console.log("\n╭─────────────────────────────────────────────────────────╮");- console.log("│ Daily Standup Bot: One-Time Setup │");- console.log("╰─────────────────────────────────────────────────────────╯");- if (RECONNECT) {- console.log(" (--reconnect: will clear and re-do the bot's Slack auth)");- }-- const composio = new Composio({ apiKey: env.COMPOSIO_API_KEY });- const authConfigId = env.COMPOSIO_SLACKBOT_AUTH_CONFIG_ID;-- // Check the auth config requests the scopes the bot needs.- // READ-ONLY on purpose. GET returns secrets MASKED, and a PATCH that echoes- // those masked values back overwrites the real client_secret with the mask.- // So we never write credentials here; we only check and warn.- const cfgRes = await fetch(`${COMPOSIO_BASE_URL}/api/v3/auth_configs/${authConfigId}`, {- headers: { "x-api-key": env.COMPOSIO_API_KEY },- });- if (cfgRes.ok) {- const cfg = (await cfgRes.json().catch(() => ({}))) as {- credentials?: { user_scopes?: string[] };- };- const userScopes = cfg.credentials?.user_scopes ?? [];- const missing = REQUIRED_USER_SCOPES.filter((s) => !userScopes.includes(s));- if (missing.length > 0) {- log.warn(`Auth config is missing required user scope(s): ${missing.join(", ")}`);- console.log(- " Add them under the auth config's User Token Scopes in the Composio\n" +- " dashboard (Auth Configs → slackbot), then re-run with --reconnect."- );- } else {- log.ok("Auth config has the required user scopes.");- }- }-- // Ensure the bot's Slack connection is active.- const session = await composio.create("default", {- authConfigs: { slackbot: authConfigId },- });-- async function listSlackbotAccounts() {- try {- const res = await composio.connectedAccounts.list({- userIds: ["default"],- toolkitSlugs: [TOOLKIT_SLUG],- });- return res.items;- } catch {- return [];- }- }-- if (RECONNECT) {- const accounts = await listSlackbotAccounts();- if (accounts.length === 0) {- log.info("No existing connections to clear.");- } else {- for (const acc of accounts) {- try {- await composio.connectedAccounts.delete(acc.id);- log.ok(`Removed old connection ${acc.id}.`);- } catch (err) {- log.warn(`Could not remove ${acc.id}: ${errMessage(err)}`);- }- }- }- }-- let connected = false;- if (!RECONNECT) {- const toolkits = await session.toolkits({ toolkits: [TOOLKIT_SLUG] });- connected = !!toolkits.items.find((t) => t.slug === TOOLKIT_SLUG)?.connection- ?.isActive;- }-- if (connected) {- log.ok("Bot is already connected to Slack.");- } else {- log.info("Bot is not connected yet. Generating an authorization link…");- // Manual authentication: authorize() returns a Connect Link, then- // waitForConnection() resolves once the bot finishes OAuth in the browser.- // https://docs.composio.dev/docs/manually-authenticating- const connectionRequest = await session.authorize(TOOLKIT_SLUG);- if (!connectionRequest.redirectUrl) {- throw new Error("Composio did not return an authorization link.");- }-- console.log("\n Open this URL in your browser to authorize the bot:\n");- console.log(` ${connectionRequest.redirectUrl}\n`);- console.log(" Waiting for you to complete the OAuth flow (Ctrl+C to abort)…");-- const TIMEOUT_MS = 5 * 60 * 1000;- const account = await connectionRequest.waitForConnection(TIMEOUT_MS);- log.ok(`Bot connected to Slack (${account.id}).`);- }-- console.log(`\n${"─".repeat(70)}`);- console.log(" 🎉 Setup complete. Invite the bot to your standup channel and");- console.log(" point your Slack app's Interactivity Request URL at");- console.log(" https://<your-deployment>/api/interactivity");- console.log(`${"─".repeat(70)}\n`);-}--main().catch((err) => {- console.error(`\n ❌ ${errMessage(err)}\n`);- process.exit(1);-});diff --git a/docs/examples/standup-slackbot/standup.config.ts b/docs/examples/standup-slackbot/standup.config.tsdeleted file mode 100644index 3cc682689..000000000--- a/docs/examples/standup-slackbot/standup.config.ts+++ /dev/null@@ -1,110 +0,0 @@-// ─────────────────────────────────────────────────────────────────────────────-// Standup bot setup. Edit this file to configure your team and tools.-// Secrets (API keys, IDs) live in .env.local, never here.-// ─────────────────────────────────────────────────────────────────────────────--export type Member = {- slackEmail: string; // used to look up their Slack user + Composio connections- githubUsername: string;- standupTime?: string; // "HH:MM" 24h in THEIR timezone; defaults below- standupTimezone?: string; // IANA tz, e.g. "Europe/Rome"; defaults below-};--export type Toolkit = {- slug: string; // Composio toolkit slug- label: string; // shown on Connect buttons- emoji: string; // leads the bullet in the draft- draftInstruction: string; // injected into the draft prompt when connected-};--// Model used to write the draft, via the Vercel AI Gateway.-export const MODEL = "anthropic/claude-sonnet-4-5" as const;--// ─── Schedule ────────────────────────────────────────────────────────────────-// The cron runs every 30 min on weekdays; each member is reminded in the slot-// containing their standupTime, evaluated in their own timezone.-export const DEFAULT_STANDUP_TIMEZONE = "America/Los_Angeles";-export const DEFAULT_STANDUP_TIME = "10:00";-export const CRON_SLOT_MINUTES = 30;-// When true, every member is "due" on every cron run, ignoring standupTime.-// Set false in production so per-person times are honored.-export const DEMO_MODE = false;--// ─── Team ────────────────────────────────────────────────────────────────────-export const standupChannel = "#standup";--export const team: Member[] = [- { slackEmail: "[email protected]", githubUsername: "your-handle" },- { slackEmail: "[email protected]", githubUsername: "teammate-handle" },- // A per-person time and timezone override the defaults below:- { slackEmail: "[email protected]", githubUsername: "alberto-handle", standupTimezone: "Europe/Rome" },-];--// GitHub org that standup drafts are scoped to. Activity in other orgs and-// personal repos is ignored. Change this to your org.-export const GITHUB_ORG = "your-github-org";--// ─── Toolkit catalogue ───────────────────────────────────────────────────────-// Every toolkit a member can connect. The draft agent gets a Composio tool-router-// session scoped to whichever of these each member has connected. Delete what you-// don't want; edit draftInstruction to change how each source is summarized.-export const TOOLKITS: Toolkit[] = [- {- slug: "github",- label: "GitHub",- emoji: "🔧",- draftInstruction:- `GitHub: find PRs they opened or merged in the time range, SCOPED TO THE ${GITHUB_ORG} ORG ONLY. Always include \`org:${GITHUB_ORG}\` in the search query. Ignore other orgs and personal repos. For each meaningful PR write a one-liner explaining its PURPOSE, prefixed with a status emoji: 🟣 merged, 🟢 open, ⚪️ draft, 🔴 closed. Include the *#number*.`,- },- {- slug: "linear",- label: "Linear",- emoji: "📋",- draftInstruction:- "Linear: find issues they created, updated, or completed in the time range. Summarize the meaningful ones (📋), focusing on what moved forward.",- },- {- slug: "notion",- label: "Notion",- emoji: "📝",- draftInstruction:- "Notion: find pages/docs they created or edited in the time range. Summarize the doc work as a one-liner (📝) describing what the doc is for.",- },- {- slug: "googlecalendar",- label: "Google Calendar",- emoji: "📅",- draftInstruction:- "Google Calendar: find their meetings/events in the time range. Only mention notable ones that reflect real work (📅), not routine blocks.",- },- {- slug: "googlemeet",- label: "Google Meet",- emoji: "🎥",- draftInstruction:- "Google Meet (context only): optionally read meeting details/transcripts for context. Do not list meetings just for existing.",- },- {- slug: "zoom",- label: "Zoom",- emoji: "🎥",- draftInstruction:- "Zoom (context only): optionally read meeting info/recordings in the time range for extra context.",- },- {- slug: "granola_mcp",- label: "Granola",- emoji: "🎙️",- draftInstruction:- "Granola (context only): optionally read meeting transcripts in the time range for additional context.",- },- {- slug: "slack",- label: "Slack",- emoji: "💬",- draftInstruction:- "Slack (context only): optionally look at messages they sent in public channels for context. Do not quote verbatim.",- },-];--export const TOOLKIT_SLUGS = TOOLKITS.map((t) => t.slug);diff --git a/docs/examples/standup-slackbot/tsconfig.json b/docs/examples/standup-slackbot/tsconfig.jsondeleted file mode 100644index c66929598..000000000--- a/docs/examples/standup-slackbot/tsconfig.json+++ /dev/null@@ -1,18 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "module": "CommonJS",- "moduleResolution": "node",- "strict": true,- "esModuleInterop": true,- "skipLibCheck": true,- "outDir": "dist",- "rootDir": ".",- "baseUrl": ".",- "paths": {- "@/*": ["./*"]- }- },- "include": ["api/**/*.ts", "standup.config.ts", "scripts/**/*.ts"],- "exclude": ["node_modules", "dist"]-}diff --git a/docs/examples/standup-slackbot/vercel.json b/docs/examples/standup-slackbot/vercel.jsondeleted file mode 100644index b626e62e2..000000000--- a/docs/examples/standup-slackbot/vercel.json+++ /dev/null@@ -1,10 +0,0 @@-{- "buildCommand": "",- "outputDirectory": "",- "crons": [- {- "path": "/api/cron/standup",- "schedule": "*/30 * * * 1-5"- }- ]-}diff --git a/docs/examples/supabase-sql-agent/main.py b/docs/examples/supabase-sql-agent/main.pydeleted file mode 100644index 7d05b86ce..000000000--- a/docs/examples/supabase-sql-agent/main.py+++ /dev/null@@ -1,84 +0,0 @@-import sys--# region setup-from agents import Agent, Runner-from composio import Composio-from composio_openai_agents import OpenAIAgentsProvider--composio = Composio(provider=OpenAIAgentsProvider())-# endregion setup---# region connect-def connect(user_id: str):- """Check if Supabase is connected. If not, start OAuth and wait."""- session = composio.create(user_id=user_id, toolkits=["supabase"])- toolkits = session.toolkits()-- for t in toolkits.items:- if t.slug == "supabase" and t.connection and t.connection.is_active:- print("Supabase is already connected.")- return-- connection_request = session.authorize("supabase")- print(f"Open this URL to connect Supabase:\n{connection_request.redirect_url}")- connection_request.wait_for_connection()- print("Connected.")-# endregion connect---# region query-def query(user_id: str):- """Interactive loop: ask questions in natural language, get SQL results."""- session = composio.create(user_id=user_id, toolkits=["supabase"])- tools = session.tools()-- agent = Agent(- name="Supabase SQL Agent",- instructions=(- "You are a Supabase SQL assistant. You help users query their Supabase "- "databases using natural language. First list the user's projects to find "- "the right database, then translate their questions into SQL queries and "- "run them. Always explain the results clearly."- ),- tools=tools,- )-- print("Supabase SQL Agent (type 'exit' to quit)")- print("-" * 45)-- last_response_id = None- while True:- user_input = input("you > ")- if user_input.strip().lower() == "exit":- break-- result = Runner.run_sync(- starting_agent=agent,- input=user_input,- previous_response_id=last_response_id,- )- last_response_id = result.last_response_id- print(f"agent > {result.final_output}\n")-# endregion query---if __name__ == "__main__":- if len(sys.argv) < 2:- print("Usage:")- print(" python main.py connect <user_id>")- print(" python main.py query <user_id>")- sys.exit(1)-- command = sys.argv[1]-- if command == "connect":- user_id = sys.argv[2] if len(sys.argv) > 2 else "default"- connect(user_id)- elif command == "query":- user_id = sys.argv[2] if len(sys.argv) > 2 else "default"- query(user_id)- else:- print(f"Unknown command: {command}")- print("Use 'connect' or 'query'.")- sys.exit(1)diff --git a/docs/examples/support-agent/main.py b/docs/examples/support-agent/main.pydeleted file mode 100644index 6bdd75f23..000000000--- a/docs/examples/support-agent/main.py+++ /dev/null@@ -1,60 +0,0 @@-# region setup-import asyncio--from agents import Agent, Runner-from agents.stream_events import RawResponsesStreamEvent-from composio import Composio-from composio_openai_agents import OpenAIAgentsProvider-from openai.types.responses import ResponseTextDeltaEvent--composio = Composio(provider=OpenAIAgentsProvider())-# endregion setup---# region agent-SYSTEM_PROMPT = """You are a Support Knowledge Agent. Use your tools to help the user triage issues, find documentation, and manage incidents. Call tools first, then respond with what you found. Be concise."""---def create_agent(tools) -> Agent:- return Agent(- name="Support Knowledge Agent",- model="gpt-5.4",- instructions=SYSTEM_PROMPT,- tools=tools,- )-# endregion agent---# region chat-async def main():- user_id = "default"- session = composio.create(- user_id=user_id,- toolkits=["datadog", "notion", "github"],- )- tools = session.tools()- agent = create_agent(tools)-- messages = []- print("Support Knowledge Agent (type 'quit' to exit)")- print("-" * 50)-- while True:- user_input = input("\nYou: ").strip()- if not user_input or user_input.lower() == "quit":- break-- messages.append({"role": "user", "content": user_input})-- print("\nAgent: ", end="", flush=True)- result = Runner.run_streamed(starting_agent=agent, input=messages, max_turns=30)- async for event in result.stream_events():- if isinstance(event, RawResponsesStreamEvent) and isinstance(event.data, ResponseTextDeltaEvent):- print(event.data.delta, end="", flush=True)- print()-- messages.append({"role": "assistant", "content": result.final_output})---asyncio.run(main())-# endregion chatdiff --git a/docs/examples/tool-generator/main.py b/docs/examples/tool-generator/main.pydeleted file mode 100644index 485f5ebeb..000000000--- a/docs/examples/tool-generator/main.py+++ /dev/null@@ -1,113 +0,0 @@-import json-import sys--# region setup-from composio import Composio--composio = Composio()-# endregion setup---# region list-tools-def list_tools(toolkit_slug: str):- """Fetch raw tool definitions for a toolkit and print them."""- tools = composio.tools.get_raw_composio_tools(toolkits=[toolkit_slug])-- for tool in tools:- print(f"\n--- {tool.slug} ---")- print(f"Name: {tool.name}")- print(f"Description: {tool.description}")-- params = tool.input_parameters or {}- required = params.get("required", [])- for name, schema in params.get("properties", {}).items():- tag = "required" if name in required else "optional"- print(f" [{tag}] {name}: {schema.get('type', 'any')} - {schema.get('description', '')}")-# endregion list-tools---# region toolkit-info-def toolkit_info(toolkit_slug: str):- """Fetch toolkit metadata including auth schemes."""- toolkit = composio.toolkits.get(toolkit_slug)-- print(f"Name: {toolkit.name}")- print(f"Slug: {toolkit.slug}")-- if not toolkit.auth_config_details:- print("Auth: none (no auth required)")- return-- for scheme in toolkit.auth_config_details:- print(f"\nAuth scheme: {scheme.mode}")-- if not scheme.fields:- continue-- creation = scheme.fields.auth_config_creation- if creation:- print(" Auth config creation:")- for field in creation.required or []:- print(f" [required] {field.name}: {field.description}")- for field in creation.optional or []:- print(f" [optional] {field.name}: {field.description}")-- connection = scheme.fields.connected_account_initiation- if connection:- print(" Account connection:")- for field in connection.required or []:- print(f" [required] {field.name}: {field.description}")- for field in connection.optional or []:- print(f" [optional] {field.name}: {field.description}")-# endregion toolkit-info---# region export-def export(toolkit_slug: str, output_file: str):- """Export raw tool definitions to a JSON file."""- tools = composio.tools.get_raw_composio_tools(toolkits=[toolkit_slug])-- data = []- for tool in tools:- data.append({- "slug": tool.slug,- "name": tool.name,- "description": tool.description,- "input_parameters": tool.input_parameters or {},- "output_parameters": tool.output_parameters or {},- "scopes": getattr(tool, "scopes", []),- "tags": getattr(tool, "tags", []),- "no_auth": getattr(tool, "no_auth", False),- })-- with open(output_file, "w", encoding="utf-8") as f:- json.dump(data, f, indent=2, default=str)-- print(f"Exported {len(data)} tools to {output_file}")-# endregion export---if __name__ == "__main__":- if len(sys.argv) < 2:- print("Usage:")- print(" python main.py list-tools <toolkit>")- print(" python main.py toolkit-info <toolkit>")- print(" python main.py export <toolkit> <output.json>")- sys.exit(1)-- command = sys.argv[1]-- if command == "list-tools":- slug = sys.argv[2] if len(sys.argv) > 2 else "gmail"- list_tools(slug)- elif command == "toolkit-info":- slug = sys.argv[2] if len(sys.argv) > 2 else "gmail"- toolkit_info(slug)- elif command == "export":- slug = sys.argv[2] if len(sys.argv) > 2 else "gmail"- out = sys.argv[3] if len(sys.argv) > 3 else "output.json"- export(slug, out)- else:- print(f"Unknown command: {command}")- print("Use 'list-tools', 'toolkit-info', or 'export'.")- sys.exit(1)diff --git a/docs/examples/workplace-search/agent.py b/docs/examples/workplace-search/agent.pydeleted file mode 100644index bc4e4148b..000000000--- a/docs/examples/workplace-search/agent.py+++ /dev/null@@ -1,59 +0,0 @@-# region setup-import asyncio-import os-import sys--from agents import Agent, Runner-from composio import Composio-from composio_openai_agents import OpenAIAgentsProvider--composio = Composio(provider=OpenAIAgentsProvider())-# endregion setup---# region agent-SYSTEM_PROMPT = """You are a workplace search agent. You have access to GitHub, Slack, Gmail, and Notion.--When the user asks a question:-1. Break it down: decide which apps to search and what to look for.-2. Search across multiple apps in parallel when possible.-3. Synthesize findings into a single answer with citations.--For every piece of information you include, cite the source:-- GitHub: link to the issue, PR, or file-- Slack: channel name and date-- Gmail: sender and subject line-- Notion: page title--If a toolkit is not connected, skip it and note which sources were unavailable.-Do not ask for clarification. Use broad search terms and filter from the results."""-# endregion agent---# region search-async def main():- # Set USER_ID in your .env file- user_id = os.environ["USER_ID"]-- session = composio.create(- user_id=user_id,- toolkits=["github", "slack", "gmail", "notion"],- )-- tools = session.tools()-- agent = Agent(- name="Workplace Search",- model="gpt-5.4",- instructions=SYSTEM_PROMPT,- tools=tools,- )-- query = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else input("\nSearch: ")- result = await Runner.run(starting_agent=agent, input=query)-- print(result.final_output)-# endregion search---asyncio.run(main())diff --git a/docs/examples/workplace-search/authorize.py b/docs/examples/workplace-search/authorize.pydeleted file mode 100644index eebaea7a3..000000000--- a/docs/examples/workplace-search/authorize.py+++ /dev/null@@ -1,36 +0,0 @@-"""-One-time setup: connect your GitHub, Slack, Gmail, and Notion accounts.-Run this once before using the search agent.-"""--import os--from composio import Composio--composio = Composio()--# Set USER_ID in your .env file-user_id = os.environ["USER_ID"]--session = composio.create(- user_id=user_id,- toolkits=["github", "slack", "gmail", "notion"],-)--# Authorize each toolkit one at a time-for toolkit in ["github", "slack", "gmail", "notion"]:- print(f"\n--- {toolkit.upper()} ---")-- # Check if already connected- status = session.toolkits(toolkits=[toolkit])- if status.items and status.items[0].connection and status.items[0].connection.is_active:- print(f"Already connected.")- continue-- connection = session.authorize(toolkit)- print(f"Open this URL to connect:\n{connection.redirect_url}")-- connected = connection.wait_for_connection()- print(f"Connected: {connected.id}")--print("\nAll done. Run agent.py to start searching.")diff --git a/docs/tsconfig.json b/docs/tsconfig.jsonindex ddc5ba0b6..187567787 100644--- a/docs/tsconfig.json+++ b/docs/tsconfig.json@@ -35,5 +35,5 @@".next/types/**/*.ts",".next/dev/types/**/*.ts"],- "exclude": ["node_modules", "scripts/preload.ts", "tests", "examples"]+ "exclude": ["node_modules", "scripts/preload.ts", "tests"]}