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