@devries-cameron20 / composio Mirror · read-only / commits / b5fbec7ed
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 02:00 UTC

import skills

Rahul Tarak committed Mar 26, 2026 at 18:39 UTC b5fbec7ed0536fcf1ad7a6d14f4dbf82ba528b4c
23 files changed +3856
.agents/skills/bug-fixing-guide/SKILL.md new
+92
@@ -0,0 +1,92 @@
1 +# Bug Fixing Guide
2 +
3 +Standard practices for fixing bugs in Composio SDK. Always add regression tests for major bugs.
4 +
5 +## Bug Fix Process
6 +
7 +### 1. Understand the Bug
8 +
9 +- **Reproduce the issue** - Create a minimal reproduction case
10 +- **Identify root cause** - Debug and trace the issue to its source
11 +- **Check existing tests** - See if tests exist for the affected code
12 +- **Review related code** - Check for similar issues elsewhere
13 +
14 +### 2. Fix the Bug
15 +
16 +- **Implement the fix** - Make minimal changes to address the root cause
17 +- **Avoid scope creep** - Don't refactor unrelated code
18 +- **Follow coding standards** - Maintain consistency with existing code
19 +- **Test locally** - Verify the fix works as expected
20 +
21 +### 3. Verify the Fix (Quick Functional Testing)
22 +
23 +**Optional but Recommended:** Test actual functionality before adding unit tests.
24 +
25 +For bugs affecting framework integrations or real-world usage:
26 +
27 +- Use **ephemeral E2E tests** to quickly verify the fix works end-to-end
28 +- Read `ephemeral-e2e-sdk-tests` skill for quick verification setup
29 +- Test in `.agent_cache/test-<bug-description>` (never commit these)
30 +- Example: `.agent_cache/test-fix-openai-tool-execution`
31 +
32 +### 4. Add Regression Tests (Required for Major Bugs)
33 +
34 +**Critical:** For major bugs, always add tests to prevent regressions.
35 +
36 +See `.Codex/rules/bug-fix-testing.mdc` for detailed testing requirements:
37 +
38 +- Where to add tests (TypeScript: `ts/packages/<package>/test/`, Python: `python/tests/`)
39 +- How to structure tests (Vitest for TS, pytest for Python)
40 +- Test naming conventions and patterns
41 +- Mocking strategies
42 +
43 +**Key Points:**
44 +
45 +- Add tests to **existing test files** for the affected feature
46 +- Tests should **fail before the fix** and **pass after**
47 +- Cover edge cases related to the bug
48 +- Run tests before committing: `pnpm test` (TS) or `make tst` (Python)
49 +
50 +### 5. Document the Fix
51 +
52 +- **Clear commit message** - Describe what was fixed and why
53 +- **Reference issues** - Link to GitHub issues or tickets
54 +- **Update docs** - If the bug exposed unclear documentation
55 +- **Add comments** - Explain non-obvious fixes in the code
56 +
57 +## When to Add Tests
58 +
59 +**Always add tests for:**
60 +
61 +- Logic errors and incorrect behavior
62 +- Edge cases and boundary conditions
63 +- Race conditions and async issues
64 +- Security vulnerabilities
65 +- Data corruption or loss issues
66 +
67 +**Consider tests for:**
68 +
69 +- Type errors (if not caught by TypeScript/mypy)
70 +- Minor UI/UX issues
71 +- Performance optimizations
72 +
73 +**May skip tests for:**
74 +
75 +- Trivial typo fixes in comments/docs
76 +- Formatting or linting issues
77 +
78 +## Testing Resources
79 +
80 +- **Quick verification**: Read `ephemeral-e2e-sdk-tests` skill (test in `.agent_cache/`)
81 +- **Full testing guidelines**: `.Codex/rules/bug-fix-testing.mdc`
82 +- **TypeScript tests**: `ts/packages/<package>/test/`
83 +- **Python tests**: `python/tests/`
84 +- **E2E tests**: `ts/e2e-tests/` (for runtime compatibility issues)
85 +
86 +## Common Pitfalls
87 +
88 +- Fixing symptoms instead of root cause
89 +- Not adding regression tests for major bugs
90 +- Breaking existing tests without updating them
91 +- Adding tests in new files instead of existing ones
92 +- Not running the full test suite before committing
.agents/skills/building-agents-using-anthropic/SKILL.md new
+134
@@ -0,0 +1,134 @@
1 +# Building Agents using Anthropic with Composio
2 +
3 +Build AI agents using Anthropic's Codex API with Composio tools.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/anthropic @anthropic-ai/sdk
9 +npm install @composio/Codex-agent-sdk @anthropic-ai/Codex-agent-sdk # For Agent SDK
10 +```
11 +
12 +```bash
13 +pip install composio-anthropic
14 +```
15 +
16 +**Find Latest Versions:**
17 +```bash
18 +npm view @anthropic-ai/sdk version
19 +pip index versions anthropic | grep "Available versions" | head -1
20 +```
21 +
22 +## Integration Method
23 +
24 +**Anthropic Messages API is non-agentic** - uses direct tools. **Codex Agent SDK is agentic** - uses Tool Router.
25 +
26 +### Messages API (Non-Agentic)
27 +
28 +```typescript
29 +import { Composio } from '@composio/core';
30 +import { AnthropicProvider } from '@composio/anthropic';
31 +import Anthropic from '@anthropic-ai/sdk';
32 +
33 +const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
34 +const composio = new Composio({
35 + apiKey: process.env.COMPOSIO_API_KEY,
36 + provider: new AnthropicProvider({ cacheTools: true }),
37 +});
38 +
39 +// Get tools
40 +const tools = await composio.tools.get('default', { toolkits: ['github'] });
41 +
42 +// Use with Codex
43 +const message = await anthropic.messages.create({
44 + model: 'Codex-3-7-sonnet-latest',
45 + max_tokens: 1024,
46 + tools: tools,
47 + messages: [{ role: 'user', content: 'Create a GitHub issue' }],
48 +});
49 +
50 +// Handle tool calls
51 +const toolResults = await composio.provider.handleToolCalls('default', message);
52 +```
53 +
54 +```python
55 +from composio_anthropic import ComposioToolSet, Action
56 +from anthropic import Anthropic
57 +
58 +client = Anthropic(api_key="YOUR_KEY")
59 +composio_toolset = ComposioToolSet(api_key="YOUR_KEY")
60 +
61 +# Get tools
62 +tools = composio_toolset.get_tools(actions=[Action.GITHUB_CREATE_ISSUE])
63 +
64 +# Use with Codex
65 +message = client.messages.create(
66 + model="Codex-3-7-sonnet-latest",
67 + max_tokens=1024,
68 + tools=tools,
69 + messages=[{"role": "user", "content": "Create a GitHub issue"}]
70 +)
71 +
72 +# Handle tool calls
73 +tool_results = composio_toolset.handle_tool_calls(message)
74 +```
75 +
76 +### Codex Agent SDK (Agentic - Requires Tool Router)
77 +
78 +```typescript
79 +import { Composio } from '@composio/core';
80 +import { ClaudeAgentSDKProvider } from '@composio/Codex-agent-sdk';
81 +import { query } from '@anthropic-ai/Codex-agent-sdk';
82 +
83 +const composio = new Composio({
84 + apiKey: process.env.COMPOSIO_API_KEY,
85 + provider: new ClaudeAgentSDKProvider()
86 +});
87 +
88 +async function runAgent(userId: string, prompt: string) {
89 + // Create session
90 + const session = await composio.create(userId, {
91 + toolkits: ['github'],
92 + manageConnections: true
93 + });
94 +
95 + const tools = await session.tools();
96 +
97 + // Use with Codex Agent SDK
98 + const stream = await query({
99 + prompt,
100 + options: {
101 + model: 'Codex-sonnet-4-5-20250929',
102 + permissionMode: 'bypassPermissions',
103 + tools
104 + }
105 + });
106 +
107 + for await (const event of stream) {
108 + if (event.type === 'result' && event.subtype === 'success') {
109 + console.log(event.result);
110 + }
111 + }
112 +}
113 +```
114 +
115 +## Key Resources
116 +
117 +- **Anthropic Docs**: https://docs.anthropic.com/
118 +- **Tool Use Guide**: https://docs.anthropic.com/en/docs/build-with-Codex/tool-use
119 +- **Codex Agent SDK**: https://docs.anthropic.com/en/docs/agents
120 +- **Messages API (Non-Agentic)**: Direct tools
121 +- **Codex Agent SDK (Agentic)**: Use Tool Router
122 +
123 +## Environment Variables
124 +
125 +```bash
126 +ANTHROPIC_API_KEY=sk-ant-...
127 +COMPOSIO_API_KEY=...
128 +```
129 +
130 +## Next Steps
131 +
132 +1. For Agent SDK (agentic), use `/building-agents`
133 +2. Check `ts/examples/anthropic/` for complete examples
134 +3. See [Anthropic docs](https://docs.anthropic.com/) for Codex features
.agents/skills/building-agents-using-autogen/SKILL.md new
+143
@@ -0,0 +1,143 @@
1 +# Building Agents using Microsoft AutoGen with Composio
2 +
3 +Build multi-agent conversational systems using AutoGen with Composio Tool Router.
4 +
5 +## Installation
6 +
7 +```bash
8 +# For AgentChat (conversational agents)
9 +pip install composio-autogen autogen-agentchat autogen-ext[openai]
10 +
11 +# For AutoGen Studio (UI-based)
12 +pip install autogenstudio
13 +```
14 +
15 +**Find Latest Versions:**
16 +```bash
17 +pip index versions autogen-agentchat | grep "Available versions" | head -1
18 +pip index versions composio-autogen | grep "Available versions" | head -1
19 +```
20 +
21 +## Integration Method
22 +
23 +**AutoGen is an agentic provider** - use Tool Router for user isolation.
24 +
25 +### Native Tools with Tool Router
26 +
27 +```python
28 +import asyncio
29 +from autogen_agentchat.agents import AssistantAgent
30 +from autogen_ext.models.openai import OpenAIChatCompletionClient
31 +from composio_autogen import ComposioToolSet, App
32 +
33 +toolset = ComposioToolSet()
34 +
35 +async def create_agent(user_id: str):
36 + # Create session
37 + session = toolset.create(
38 + user_id=user_id,
39 + toolkits=["github"],
40 + manage_connections=True
41 + )
42 +
43 + tools = session.tools()
44 +
45 + # Create agent with tools
46 + agent = AssistantAgent(
47 + name="github_agent",
48 + model_client=OpenAIChatCompletionClient(model="gpt-4o"),
49 + tools=tools,
50 + system_message="You manage GitHub repositories"
51 + )
52 +
53 + return agent
54 +
55 +async def main():
56 + agent = await create_agent("user_123")
57 + result = await agent.run(task="Create a GitHub issue titled 'Bug Report'")
58 + print(result)
59 +
60 +asyncio.run(main())
61 +```
62 +
63 +### Multi-Agent Conversation
64 +
65 +```python
66 +import asyncio
67 +from autogen_agentchat.agents import AssistantAgent
68 +from autogen_agentchat.teams import RoundRobinGroupChat
69 +from autogen_ext.models.openai import OpenAIChatCompletionClient
70 +from composio_autogen import ComposioToolSet, App
71 +
72 +toolset = ComposioToolSet()
73 +
74 +async def create_team(user_id: str):
75 + # Create session
76 + session = toolset.create(
77 + user_id=user_id,
78 + toolkits=["github", "slack"],
79 + manage_connections=True
80 + )
81 +
82 + tools = session.tools()
83 +
84 + # Create specialized agents
85 + github_agent = AssistantAgent(
86 + name="github_agent",
87 + model_client=OpenAIChatCompletionClient(model="gpt-4o"),
88 + tools=tools,
89 + system_message="You manage GitHub"
90 + )
91 +
92 + slack_agent = AssistantAgent(
93 + name="slack_agent",
94 + model_client=OpenAIChatCompletionClient(model="gpt-4o"),
95 + tools=tools,
96 + system_message="You manage Slack"
97 + )
98 +
99 + # Create team
100 + team = RoundRobinGroupChat(
101 + [github_agent, slack_agent],
102 + max_turns=10
103 + )
104 +
105 + return team
106 +
107 +async def main():
108 + team = await create_team("user_123")
109 + result = await team.run(
110 + task="Create a GitHub issue and notify team on Slack"
111 + )
112 + print(result)
113 +
114 +asyncio.run(main())
115 +```
116 +
117 +## Key Features
118 +
119 +- **Multi-Agent Conversations**: Agents collaborate and communicate
120 +- **AutoGen Studio**: No-code UI for prototyping
121 +- **Multiple Layers**: Studio, AgentChat, Core for different needs
122 +- **Team Patterns**: RoundRobin, Swarm, custom orchestration
123 +
124 +## Key Resources
125 +
126 +- **AutoGen Docs**: https://microsoft.github.io/autogen/stable/
127 +- **Tool Router Guide**: `/building-agents`
128 +- **GitHub**: https://github.com/microsoft/autogen
129 +- **Microsoft Agent Framework**: Successor to AutoGen
130 +
131 +## Environment Variables
132 +
133 +```bash
134 +OPENAI_API_KEY=sk-... # Or other LLM provider
135 +COMPOSIO_API_KEY=...
136 +```
137 +
138 +## Next Steps
139 +
140 +1. Use `/building-agents` for comprehensive guide
141 +2. Check `python/providers/autogen/` for complete examples
142 +3. See [AutoGen docs](https://microsoft.github.io/autogen/stable/) for conversation patterns
143 +4. Consider [Microsoft Agent Framework](https://learn.microsoft.com/en-us/agent-framework/) for new projects
.agents/skills/building-agents-using-cloudflare/SKILL.md new
+124
@@ -0,0 +1,124 @@
1 +# Building Agents using Cloudflare with Composio
2 +
3 +Build edge-deployed AI agents using Cloudflare Workers AI with Composio Tool Router.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/cloudflare agents @cloudflare/ai-utils
9 +npm install wrangler -D # For development
10 +```
11 +
12 +**Find Latest Versions:**
13 +```bash
14 +npm view agents version
15 +npm view @composio/cloudflare version
16 +```
17 +
18 +## Integration Method
19 +
20 +**Cloudflare is an agentic provider** - use Tool Router for user isolation.
21 +
22 +### Native Tools with Tool Router
23 +
24 +```typescript
25 +import { Agent } from 'agents';
26 +import { Composio } from '@composio/core';
27 +import { CloudflareProvider } from '@composio/cloudflare';
28 +
29 +export class MyAgent extends Agent {
30 + private composio: Composio;
31 +
32 + constructor(state: DurableObjectState, env: Env) {
33 + super(state, env);
34 +
35 + this.composio = new Composio({
36 + apiKey: env.COMPOSIO_API_KEY,
37 + provider: new CloudflareProvider(),
38 + });
39 + }
40 +
41 + async onStart() {
42 + // Initialize with user-specific session
43 + const session = await this.composio.create(this.userId, {
44 + toolkits: ['github'],
45 + manageConnections: true
46 + });
47 +
48 + this.tools = await session.tools();
49 + }
50 +
51 + async handleMessage(message: string) {
52 + // Use tools with Cloudflare AI
53 + const response = await this.ai.run('@cf/meta/llama-3.1-70b-instruct', {
54 + messages: [
55 + { role: 'system', content: 'You are a helpful assistant' },
56 + { role: 'user', content: message },
57 + ],
58 + tools: this.tools,
59 + });
60 +
61 + return response;
62 + }
63 +}
64 +```
65 +
66 +### wrangler.toml Configuration
67 +
68 +```toml
69 +name = "my-agent"
70 +main = "src/index.ts"
71 +compatibility_date = "2024-01-01"
72 +
73 +[[durable_objects.bindings]]
74 +name = "MY_AGENT"
75 +class_name = "MyAgent"
76 +
77 +[ai]
78 +binding = "AI"
79 +
80 +[vars]
81 +COMPOSIO_API_KEY = "your-key-here"
82 +
83 +[[migrations]]
84 +tag = "v1"
85 +new_sqlite_classes = ["MyAgent"]
86 +```
87 +
88 +## Key Features
89 +
90 +- **Edge Deployment**: Low-latency worldwide
91 +- **Durable Objects**: Persistent agent state
92 +- **Workers AI**: Run models at the edge
93 +- **Embedded Function Calling**: AI executes functions automatically
94 +
95 +## Key Resources
96 +
97 +- **Cloudflare Agents SDK**: https://developers.cloudflare.com/agents/
98 +- **Tool Router Guide**: `/building-agents`
99 +- **Workers AI**: https://developers.cloudflare.com/workers-ai/
100 +- **Function Calling**: https://developers.cloudflare.com/workers-ai/features/function-calling/
101 +
102 +## Environment Variables
103 +
104 +```bash
105 +COMPOSIO_API_KEY=...
106 +CLOUDFLARE_ACCOUNT_ID=...
107 +CLOUDFLARE_API_TOKEN=...
108 +```
109 +
110 +## Deployment
111 +
112 +```bash
113 +# Deploy with Wrangler
114 +npx wrangler deploy
115 +
116 +# Tail logs
117 +npx wrangler tail
118 +```
119 +
120 +## Next Steps
121 +
122 +1. Use `/building-agents` for comprehensive guide
123 +2. Check `ts/examples/cloudflare-wrangler/` for complete examples
124 +3. See [Cloudflare docs](https://developers.cloudflare.com/agents/) for edge features
.agents/skills/building-agents-using-crewai/SKILL.md new
+147
@@ -0,0 +1,147 @@
1 +# Building Agents using CrewAI with Composio
2 +
3 +Build multi-agent teams using CrewAI with Composio Tool Router.
4 +
5 +## Installation
6 +
7 +```bash
8 +pip install composio-crewai crewai crewai-tools
9 +```
10 +
11 +**Find Latest Versions:**
12 +```bash
13 +pip index versions crewai | grep "Available versions" | head -1
14 +pip index versions composio-crewai | grep "Available versions" | head -1
15 +```
16 +
17 +## Integration Method
18 +
19 +**CrewAI is an agentic provider** - use MCP for multi-agent teams.
20 +
21 +### MCP Integration
22 +
23 +```python
24 +from crewai import Agent, Task, Crew
25 +from crewai.mcp import MCPServerHTTP
26 +from composio import Composio
27 +
28 +composio = Composio()
29 +
30 +def create_crew(user_id: str):
31 + # Create session
32 + session = composio.create(user_id=user_id, toolkits=["github"])
33 +
34 + # Create agent with MCP server
35 + agent = Agent(
36 + role="GitHub Manager",
37 + goal="Manage GitHub repositories",
38 + backstory="You are an expert at GitHub operations",
39 + mcps=[
40 + MCPServerHTTP(
41 + url=session.mcp.url,
42 + headers=session.mcp.headers
43 + )
44 + ]
45 + )
46 +
47 + # Define task
48 + task = Task(
49 + description="Create a GitHub issue titled 'Bug Report'",
50 + expected_output="Confirmation of issue creation",
51 + agent=agent
52 + )
53 +
54 + # Execute crew
55 + crew = Crew(agents=[agent], tasks=[task])
56 + return crew
57 +
58 +crew = create_crew("user_123")
59 +result = crew.kickoff()
60 +print(result)
61 +```
62 +
63 +### Multi-Agent Team Example
64 +
65 +```python
66 +from crewai import Agent, Task, Crew, Process
67 +from crewai.mcp import MCPServerHTTP
68 +from composio import Composio
69 +
70 +composio = Composio()
71 +
72 +def create_team(user_id: str):
73 + session = composio.create(user_id=user_id, toolkits=["github", "slack"])
74 +
75 + # Create MCP server connection
76 + mcp_server = MCPServerHTTP(
77 + url=session.mcp.url,
78 + headers=session.mcp.headers
79 + )
80 +
81 + # Create specialized agents
82 + researcher = Agent(
83 + role="GitHub Researcher",
84 + goal="Analyze repositories",
85 + backstory="Expert at code analysis",
86 + mcps=[mcp_server]
87 + )
88 +
89 + reporter = Agent(
90 + role="Report Writer",
91 + goal="Create reports",
92 + backstory="Expert at documentation",
93 + mcps=[mcp_server]
94 + )
95 +
96 + # Define tasks
97 + research_task = Task(
98 + description="Analyze the repository",
99 + expected_output="Analysis report",
100 + agent=researcher
101 + )
102 +
103 + report_task = Task(
104 + description="Create a summary report",
105 + expected_output="Markdown report",
106 + agent=reporter,
107 + context=[research_task]
108 + )
109 +
110 + crew = Crew(
111 + agents=[researcher, reporter],
112 + tasks=[research_task, report_task],
113 + process=Process.sequential
114 + )
115 +
116 + return crew
117 +
118 +team = create_team("user_123")
119 +result = team.kickoff()
120 +```
121 +
122 +## Key Features
123 +
124 +- **Multi-Agent Teams**: Agents collaborate on tasks
125 +- **Task Dependencies**: Sequential or hierarchical execution
126 +- **YAML Configs**: Clean agent/task definitions
127 +- **Production Ready**: Mature framework
128 +
129 +## Key Resources
130 +
131 +- **CrewAI Docs**: https://docs.crewai.com/
132 +- **Tool Router Guide**: `/building-agents`
133 +- **Quickstart**: https://docs.crewai.com/en/quickstart
134 +- **GitHub**: https://github.com/crewAIInc/crewAI
135 +
136 +## Environment Variables
137 +
138 +```bash
139 +OPENAI_API_KEY=sk-... # Or other LLM provider
140 +COMPOSIO_API_KEY=...
141 +```
142 +
143 +## Next Steps
144 +
145 +1. Use `/building-agents` for comprehensive guide
146 +2. Check `python/providers/crewai/` for complete examples
147 +3. See [CrewAI docs](https://docs.crewai.com/) for multi-agent patterns
.agents/skills/building-agents-using-google/SKILL.md new
+107
@@ -0,0 +1,107 @@
1 +# Building Agents using Google Gemini with Composio
2 +
3 +Build AI agents using Google's Gemini API with Composio tools.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/google @google/genai
9 +```
10 +
11 +```bash
12 +pip install composio-google google-genai
13 +```
14 +
15 +**Find Latest Versions:**
16 +```bash
17 +npm view @google/genai version
18 +pip index versions google-genai | grep "Available versions" | head -1
19 +```
20 +
21 +## Integration Method
22 +
23 +**Google Gemini is a non-agentic provider** - uses direct tools (no Tool Router support).
24 +
25 +### TypeScript Example
26 +
27 +```typescript
28 +import { Composio } from '@composio/core';
29 +import { GoogleProvider } from '@composio/google';
30 +import { GoogleGenAI } from '@google/genai';
31 +
32 +const genai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY });
33 +const composio = new Composio({
34 + apiKey: process.env.COMPOSIO_API_KEY,
35 + provider: new GoogleProvider(),
36 +});
37 +
38 +// Get tools
39 +const tools = await composio.tools.get('default', { toolkits: ['github'] });
40 +
41 +// Use with Gemini
42 +const response = await genai.models.generateContent({
43 + model: 'gemini-3-flash-preview',
44 + contents: 'Create a GitHub issue',
45 + config: {
46 + tools: tools,
47 + temperature: 1.0 // Required for Gemini 3
48 + },
49 +});
50 +
51 +// Handle function calls
52 +if (response.functionCalls) {
53 + const results = await composio.provider.handleToolCalls('default', response);
54 +}
55 +```
56 +
57 +### Python Example
58 +
59 +```python
60 +from composio_google import ComposioToolSet, Action
61 +from google import genai
62 +from google.genai import types
63 +
64 +client = genai.Client(api_key="YOUR_KEY")
65 +composio_toolset = ComposioToolSet(api_key="YOUR_KEY")
66 +
67 +# Get tools
68 +tools = composio_toolset.get_tools(actions=[Action.GITHUB_CREATE_ISSUE])
69 +
70 +# Use with Gemini
71 +response = client.models.generate_content(
72 + model="gemini-3-flash-preview",
73 + contents="Create a GitHub issue",
74 + config=types.GenerateContentConfig(
75 + tools=tools,
76 + temperature=1.0
77 + )
78 +)
79 +
80 +# Handle function calls
81 +tool_results = composio_toolset.handle_tool_calls(response)
82 +```
83 +
84 +## Key Features
85 +
86 +- **Compositional Function Calling**: Chain multiple functions automatically
87 +- **Parallel Execution**: Execute independent functions simultaneously
88 +- **Internal Thinking**: Gemini 3 models reason through complex requests
89 +
90 +## Key Resources
91 +
92 +- **Gemini API Docs**: https://ai.google.dev/gemini-api/docs
93 +- **Function Calling**: https://ai.google.dev/gemini-api/docs/function-calling
94 +- **Available Models**: Gemini 3 Pro/Flash, Gemini 2.5 Pro/Flash
95 +
96 +## Environment Variables
97 +
98 +```bash
99 +GOOGLE_API_KEY=...
100 +COMPOSIO_API_KEY=...
101 +```
102 +
103 +## Next Steps
104 +
105 +1. Check `ts/examples/google/` for complete examples
106 +2. See [Gemini docs](https://ai.google.dev) for API features
107 +3. Note: Temperature must be 1.0 for Gemini 3 models
.agents/skills/building-agents-using-langchain/SKILL.md new
+123
@@ -0,0 +1,123 @@
1 +# Building Agents using LangChain with Composio
2 +
3 +Build AI agents using LangChain/LangGraph with Composio Tool Router.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/langchain langchain @langchain/core @langchain/openai
9 +```
10 +
11 +```bash
12 +pip install composio-langchain langchain langchain-openai
13 +```
14 +
15 +**Find Latest Versions:**
16 +```bash
17 +npm view langchain version
18 +pip index versions langchain | grep "Available versions" | head -1
19 +```
20 +
21 +## Integration Method
22 +
23 +**LangChain is an agentic provider** - use Tool Router (or MCP for flexibility).
24 +
25 +### Native Tools with Tool Router
26 +
27 +```typescript
28 +import { ChatOpenAI } from '@langchain/openai';
29 +import { Composio } from '@composio/core';
30 +import { LangchainProvider } from '@composio/langchain';
31 +
32 +const composio = new Composio({
33 + apiKey: process.env.COMPOSIO_API_KEY,
34 + provider: new LangchainProvider(),
35 +});
36 +
37 +async function runAgent(userId: string, prompt: string) {
38 + // Create session
39 + const session = await composio.create(userId, {
40 + toolkits: ['github'],
41 + manageConnections: true
42 + });
43 +
44 + const tools = await session.tools();
45 +
46 + // Use with LangChain
47 + const llm = new ChatOpenAI({ model: 'gpt-4o' });
48 + const agent = llm.bindTools(tools);
49 +
50 + const result = await agent.invoke(prompt);
51 + return result;
52 +}
53 +```
54 +
55 +```python
56 +from langchain_openai import ChatOpenAI
57 +from composio_langchain import ComposioToolSet, App
58 +
59 +composio_toolset = ComposioToolSet()
60 +
61 +def run_agent(user_id: str, prompt: str):
62 + # Create session
63 + session = composio_toolset.create(
64 + user_id=user_id,
65 + toolkits=["github"],
66 + manage_connections=True
67 + )
68 +
69 + tools = session.tools()
70 +
71 + # Use with LangChain
72 + llm = ChatOpenAI(model="gpt-4o")
73 + agent = llm.bind_tools(tools)
74 +
75 + result = agent.invoke(prompt)
76 + return result
77 +```
78 +
79 +### MCP Integration
80 +
81 +```typescript
82 +import { MultiServerMCPClient } from '@langchain/mcp-adapters';
83 +import { Composio } from '@composio/core';
84 +
85 +const composio = new Composio();
86 +
87 +async function runAgentMCP(userId: string) {
88 + const session = await composio.create(userId, {
89 + toolkits: ['github']
90 + });
91 +
92 + const client = new MultiServerMCPClient({
93 + composio: {
94 + transport: 'http',
95 + url: session.mcp.url,
96 + headers: session.mcp.headers
97 + }
98 + });
99 +
100 + const tools = await client.getTools();
101 + // Use tools with LangChain
102 +}
103 +```
104 +
105 +## Key Resources
106 +
107 +- **LangChain Docs**: https://python.langchain.com/docs/introduction/
108 +- **Tool Router Guide**: `/building-agents`
109 +- **Agents Documentation**: https://docs.langchain.com/oss/python/langchain/agents
110 +- **Use LangGraph for production**: More flexible agent runtime
111 +
112 +## Environment Variables
113 +
114 +```bash
115 +OPENAI_API_KEY=sk-... # Or other LLM provider
116 +COMPOSIO_API_KEY=...
117 +```
118 +
119 +## Next Steps
120 +
121 +1. Use `/building-agents` for comprehensive guide
122 +2. Use `/building-agents-using-langgraph` for stateful agents
123 +3. Check `ts/examples/langchain/` for complete examples
.agents/skills/building-agents-using-langgraph/SKILL.md new
+140
@@ -0,0 +1,140 @@
1 +# Building Agents using LangGraph with Composio
2 +
3 +Build stateful, durable AI agents using LangGraph with Composio Tool Router.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/langchain @langchain/langgraph @langchain/core
9 +```
10 +
11 +```bash
12 +pip install composio-langchain langgraph langgraph-checkpoint-sqlite
13 +```
14 +
15 +**Find Latest Versions:**
16 +```bash
17 +npm view @langchain/langgraph version
18 +pip index versions langgraph | grep "Available versions" | head -1
19 +```
20 +
21 +## Integration Method
22 +
23 +**LangGraph is an agentic provider** - use Tool Router for user isolation.
24 +
25 +### Python Example with Tool Router
26 +
27 +```python
28 +from langgraph.graph import StateGraph, MessagesAnnotation, START, END
29 +from langgraph.prebuilt import ToolNode
30 +from langgraph.checkpoint.sqlite import SqliteSaver
31 +from langchain_openai import ChatOpenAI
32 +from composio_langchain import ComposioToolSet
33 +
34 +toolset = ComposioToolSet()
35 +
36 +def create_agent(user_id: str):
37 + # Create session
38 + session = toolset.create(
39 + user_id=user_id,
40 + toolkits=["github"],
41 + manage_connections=True
42 + )
43 +
44 + tools = session.tools()
45 +
46 + # Create graph
47 + tool_node = ToolNode(tools)
48 + model = ChatOpenAI(model="gpt-4o").bind_tools(tools)
49 +
50 + def should_continue(state):
51 + last_message = state["messages"][-1]
52 + return "tools" if hasattr(last_message, "tool_calls") and last_message.tool_calls else END
53 +
54 + def call_model(state):
55 + return {"messages": [model.invoke(state["messages"])]}
56 +
57 + workflow = StateGraph(MessagesAnnotation)
58 + workflow.add_node("agent", call_model)
59 + workflow.add_node("tools", tool_node)
60 + workflow.add_edge(START, "agent")
61 + workflow.add_edge("tools", "agent")
62 + workflow.add_conditional_edges("agent", should_continue)
63 +
64 + # Compile with checkpointer for durability
65 + memory = SqliteSaver.from_conn_string(":memory:")
66 + app = workflow.compile(checkpointer=memory)
67 +
68 + return app
69 +
70 +# Use with thread_id for persistence
71 +app = create_agent("user_123")
72 +result = app.invoke(
73 + {"messages": [{"role": "user", "content": "Create a GitHub issue"}]},
74 + config={"configurable": {"thread_id": "user-123"}}
75 +)
76 +```
77 +
78 +### TypeScript Example with Tool Router
79 +
80 +```typescript
81 +import { StateGraph, MessagesAnnotation, START, END } from '@langchain/langgraph';
82 +import { ToolNode } from '@langchain/langgraph/prebuilt';
83 +import { ChatOpenAI } from '@langchain/openai';
84 +import { Composio } from '@composio/core';
85 +import { LangchainProvider } from '@composio/langchain';
86 +
87 +const composio = new Composio({
88 + apiKey: process.env.COMPOSIO_API_KEY,
89 + provider: new LangchainProvider(),
90 +});
91 +
92 +async function createAgent(userId: string) {
93 + const session = await composio.create(userId, {
94 + toolkits: ['github'],
95 + manageConnections: true
96 + });
97 +
98 + const tools = await session.tools();
99 + const toolNode = new ToolNode(tools);
100 + const model = new ChatOpenAI({ model: 'gpt-4o' }).bindTools(tools);
101 +
102 + const workflow = new StateGraph(MessagesAnnotation)
103 + .addNode('agent', async (state) => ({ messages: [await model.invoke(state.messages)] }))
104 + .addNode('tools', toolNode)
105 + .addEdge(START, 'agent')
106 + .addEdge('tools', 'agent')
107 + .addConditionalEdges('agent', (state) => {
108 + const last = state.messages[state.messages.length - 1];
109 + return last.tool_calls?.length ? 'tools' : END;
110 + });
111 +
112 + return workflow.compile();
113 +}
114 +```
115 +
116 +## Key Features
117 +
118 +- **Durable Execution**: Agents persist through failures
119 +- **Human-in-the-Loop**: Pause for approvals
120 +- **Persistent Memory**: State saved across sessions
121 +- **Production Ready**: v1.0 released late 2025
122 +
123 +## Key Resources
124 +
125 +- **LangGraph Docs**: https://docs.langchain.com/oss/python/langgraph/
126 +- **Tool Router Guide**: `/building-agents`
127 +- **LangGraph v1.0**: https://www.blog.langchain.com/langchain-langgraph-1dot0/
128 +
129 +## Environment Variables
130 +
131 +```bash
132 +OPENAI_API_KEY=sk-...
133 +COMPOSIO_API_KEY=...
134 +```
135 +
136 +## Next Steps
137 +
138 +1. Use `/building-agents` for comprehensive guide
139 +2. Check `ts/examples/langchain/` for complete examples
140 +3. See [LangGraph docs](https://docs.langchain.com/oss/python/langgraph/) for advanced features
.agents/skills/building-agents-using-llamaindex/SKILL.md new
+128
@@ -0,0 +1,128 @@
1 +# Building Agents using LlamaIndex with Composio
2 +
3 +Build RAG-enhanced AI agents using LlamaIndex with Composio Tool Router.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/llamaindex llamaindex
9 +```
10 +
11 +```bash
12 +pip install composio-llamaindex llama-index llama-index-llms-openai
13 +```
14 +
15 +**Find Latest Versions:**
16 +```bash
17 +npm view llamaindex version
18 +pip index versions llama-index | grep "Available versions" | head -1
19 +```
20 +
21 +## Integration Method
22 +
23 +**LlamaIndex is an agentic provider** - use Tool Router for user isolation.
24 +
25 +### Python Example with Tool Router
26 +
27 +```python
28 +from llama_index.core.agent import ReActAgent
29 +from llama_index.llms.openai import OpenAI
30 +from composio_llamaindex import ComposioToolSet, App
31 +
32 +toolset = ComposioToolSet()
33 +
34 +def create_agent(user_id: str):
35 + # Create session
36 + session = toolset.create(
37 + user_id=user_id,
38 + toolkits=["github"],
39 + manage_connections=True
40 + )
41 +
42 + tools = session.tools()
43 +
44 + # Create agent
45 + llm = OpenAI(model="gpt-4o")
46 + agent = ReActAgent.from_tools(tools, llm=llm, verbose=True)
47 +
48 + return agent
49 +
50 +agent = create_agent("user_123")
51 +response = agent.chat("Create a GitHub issue titled 'Bug Report'")
52 +print(response)
53 +```
54 +
55 +### TypeScript Example with Tool Router
56 +
57 +```typescript
58 +import { Composio } from '@composio/core';
59 +import { LlamaIndexProvider } from '@composio/llamaindex';
60 +import { OpenAI, FunctionCallingAgent } from 'llamaindex';
61 +
62 +const composio = new Composio({
63 + apiKey: process.env.COMPOSIO_API_KEY,
64 + provider: new LlamaIndexProvider(),
65 +});
66 +
67 +async function createAgent(userId: string) {
68 + // Create session
69 + const session = await composio.create(userId, {
70 + toolkits: ['github'],
71 + manageConnections: true
72 + });
73 +
74 + const tools = await session.tools();
75 +
76 + // Create agent
77 + const llm = new OpenAI({ model: 'gpt-4o' });
78 + const agent = new FunctionCallingAgent({
79 + llm,
80 + tools,
81 + verbose: true,
82 + });
83 +
84 + return agent;
85 +}
86 +
87 +const agent = await createAgent('user_123');
88 +const response = await agent.chat({ message: 'Create a GitHub issue' });
89 +```
90 +
91 +### MCP Integration
92 +
93 +```python
94 +# LlamaIndex also supports MCP for framework flexibility
95 +from composio import Composio
96 +
97 +composio = Composio()
98 +session = composio.create(user_id="user_123", toolkits=["github"])
99 +
100 +# Use session.mcp.url with LlamaIndex MCP adapters
101 +```
102 +
103 +## Key Features
104 +
105 +- **ReAct Agents**: Reasoning + Acting pattern
106 +- **RAG + Tools**: Combine retrieval with actions
107 +- **Workflows 1.0**: Event-driven orchestration
108 +- **Query Engines**: Tools for advanced RAG
109 +
110 +## Key Resources
111 +
112 +- **LlamaIndex Docs**: https://developers.llamaindex.ai/python/framework/
113 +- **Tool Router Guide**: `/building-agents`
114 +- **Agents Guide**: https://developers.llamaindex.ai/python/framework/use_cases/agents/
115 +- **Workflows**: https://www.llamaindex.ai/blog/announcing-workflows-1-0-a-lightweight-framework-for-agentic-systems
116 +
117 +## Environment Variables
118 +
119 +```bash
120 +OPENAI_API_KEY=sk-...
121 +COMPOSIO_API_KEY=...
122 +```
123 +
124 +## Next Steps
125 +
126 +1. Use `/building-agents` for comprehensive guide
127 +2. Check `ts/examples/llamaindex/` for complete examples
128 +3. See [LlamaIndex docs](https://developers.llamaindex.ai/) for RAG patterns
.agents/skills/building-agents-using-mastra/SKILL.md new
+121
@@ -0,0 +1,121 @@
1 +# Building Agents using Mastra with Composio
2 +
3 +Build AI agents using Mastra with Composio Tool Router.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/mastra @mastra/core
9 +```
10 +
11 +**Find Latest Versions:**
12 +```bash
13 +npm view @mastra/core version
14 +npm view @composio/mastra version
15 +```
16 +
17 +## Integration Method
18 +
19 +**Mastra is an agentic provider** - use Tool Router for user isolation.
20 +
21 +### Native Tools with Tool Router
22 +
23 +```typescript
24 +import { Composio } from '@composio/core';
25 +import { MastraProvider } from '@composio/mastra';
26 +import { Agent } from '@mastra/core/agent';
27 +
28 +const composio = new Composio({
29 + apiKey: process.env.COMPOSIO_API_KEY,
30 + provider: new MastraProvider(),
31 +});
32 +
33 +async function createAgent(userId: string) {
34 + // Create session
35 + const session = await composio.create(userId, {
36 + toolkits: ['github'],
37 + manageConnections: true
38 + });
39 +
40 + const tools = await session.tools();
41 +
42 + // Create agent
43 + const agent = new Agent({
44 + id: 'github-agent',
45 + name: 'GitHub Agent',
46 + instructions: 'You manage GitHub repositories',
47 + model: 'openai/gpt-4o',
48 + tools: {
49 + ...tools, // Spread Composio tools
50 + },
51 + });
52 +
53 + return agent;
54 +}
55 +
56 +const agent = await createAgent('user_123');
57 +const result = await agent.generate({
58 + prompt: 'Create a GitHub issue titled "Bug Report"',
59 +});
60 +
61 +console.log(result.text);
62 +```
63 +
64 +### Streaming with Tool Router
65 +
66 +```typescript
67 +async function streamAgent(userId: string, prompt: string) {
68 + const session = await composio.create(userId, {
69 + toolkits: ['github'],
70 + manageConnections: true
71 + });
72 +
73 + const tools = await session.tools();
74 +
75 + const agent = new Agent({
76 + id: 'agent',
77 + model: 'openai/gpt-4o',
78 + tools: { ...tools },
79 + maxSteps: 10,
80 + });
81 +
82 + // Stream response
83 + const stream = await agent.stream({
84 + prompt,
85 + onStepFinish: (step) => {
86 + console.log('Step completed:', step);
87 + },
88 + });
89 +
90 + for await (const chunk of stream) {
91 + process.stdout.write(chunk);
92 + }
93 +}
94 +```
95 +
96 +## Key Features
97 +
98 +- **40+ Model Providers**: OpenAI, Anthropic, Google, Mistral, Groq, etc.
99 +- **Autonomous Agents**: Solve open-ended tasks
100 +- **Streaming Support**: Real-time responses
101 +- **v1.0 Released**: January 2026 - production ready
102 +
103 +## Key Resources
104 +
105 +- **Mastra Docs**: https://mastra.ai/docs
106 +- **Tool Router Guide**: `/building-agents`
107 +- **Agents Guide**: https://mastra.ai/docs/agents/overview
108 +- **GitHub**: https://github.com/mastra-ai/mastra
109 +
110 +## Environment Variables
111 +
112 +```bash
113 +OPENAI_API_KEY=sk-... # Or other model provider
114 +COMPOSIO_API_KEY=...
115 +```
116 +
117 +## Next Steps
118 +
119 +1. Use `/building-agents` for comprehensive guide
120 +2. Check `ts/examples/mastra/` for complete examples
121 +3. See [Mastra docs](https://mastra.ai/docs) for multi-provider routing
.agents/skills/building-agents-using-openai/SKILL.md new
+125
@@ -0,0 +1,125 @@
1 +# Building Agents using OpenAI with Composio
2 +
3 +Build AI agents using OpenAI's APIs with Composio tools.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/openai openai
9 +npm install @composio/openai-agents @openai/agents # For Agents API
10 +```
11 +
12 +```bash
13 +pip install composio-openai
14 +```
15 +
16 +**Find Latest Versions:**
17 +```bash
18 +npm view openai version
19 +pip index versions openai | grep "Available versions" | head -1
20 +```
21 +
22 +## Integration Method
23 +
24 +**OpenAI is a non-agentic provider** - uses direct tools (no Tool Router support).
25 +
26 +### Chat Completions API
27 +
28 +```typescript
29 +import { Composio } from '@composio/core';
30 +import { OpenAI } from 'openai';
31 +
32 +const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
33 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
34 +
35 +// Get tools
36 +const tools = await composio.tools.get('default', { toolkits: ['github'] });
37 +
38 +// Use with OpenAI
39 +const response = await openai.chat.completions.create({
40 + model: 'gpt-4o',
41 + messages: [{ role: 'user', content: 'Create a GitHub issue' }],
42 + tools: tools,
43 +});
44 +
45 +// Handle tool calls
46 +if (response.choices[0].message.tool_calls) {
47 + const result = await composio.provider.handleToolCalls('default', response);
48 +}
49 +```
50 +
51 +```python
52 +from composio_openai import ComposioToolSet, Action
53 +from openai import OpenAI
54 +
55 +openai_client = OpenAI(api_key="YOUR_KEY")
56 +composio_toolset = ComposioToolSet(api_key="YOUR_KEY")
57 +
58 +# Get tools
59 +tools = composio_toolset.get_tools(actions=[Action.GITHUB_CREATE_ISSUE])
60 +
61 +# Use with OpenAI
62 +response = openai_client.chat.completions.create(
63 + model="gpt-4o",
64 + messages=[{"role": "user", "content": "Create a GitHub issue"}],
65 + tools=tools,
66 +)
67 +
68 +# Handle tool calls
69 +result = composio_toolset.handle_tool_calls(response)
70 +```
71 +
72 +### OpenAI Agents API (Agentic - Requires Tool Router)
73 +
74 +```typescript
75 +import { Composio } from '@composio/core';
76 +import { OpenAIAgentsProvider } from '@composio/openai-agents';
77 +import { Agent, run } from '@openai/agents';
78 +
79 +const composio = new Composio({
80 + apiKey: process.env.COMPOSIO_API_KEY,
81 + provider: new OpenAIAgentsProvider()
82 +});
83 +
84 +async function createAgent(userId: string) {
85 + // Create session for user
86 + const session = await composio.create(userId, {
87 + toolkits: ['github'],
88 + manageConnections: true
89 + });
90 +
91 + const tools = await session.tools();
92 +
93 + const agent = new Agent({
94 + name: 'GitHub Agent',
95 + model: 'gpt-4o',
96 + instructions: 'You help with GitHub operations',
97 + tools
98 + });
99 +
100 + return agent;
101 +}
102 +
103 +const agent = await createAgent('user_123');
104 +const result = await run(agent, 'Create a GitHub issue');
105 +```
106 +
107 +## Key Resources
108 +
109 +- **OpenAI Docs**: https://platform.openai.com/docs
110 +- **Function Calling**: https://platform.openai.com/docs/guides/function-calling
111 +- **Agents API**: https://platform.openai.com/docs/agents
112 +- **OpenAI Agents SDK (Agentic)**: Use Tool Router with `@composio/openai-agents`
113 +
114 +## Environment Variables
115 +
116 +```bash
117 +OPENAI_API_KEY=sk-...
118 +COMPOSIO_API_KEY=...
119 +```
120 +
121 +## Next Steps
122 +
123 +1. For Agents API (agentic), use `/building-agents`
124 +2. Check `ts/examples/openai/` for complete examples
125 +3. See [OpenAI docs](https://platform.openai.com/docs) for API features
.agents/skills/building-agents-using-vercel/SKILL.md new
+116
@@ -0,0 +1,116 @@
1 +# Building Agents using Vercel AI SDK with Composio
2 +
3 +Build AI agents using Vercel AI SDK with Composio Tool Router for user-isolated tool sessions.
4 +
5 +## Installation
6 +
7 +```bash
8 +npm install @composio/core @composio/vercel ai @ai-sdk/openai
9 +```
10 +
11 +**Find Latest Versions:**
12 +```bash
13 +npm view ai version
14 +npm view @composio/vercel version
15 +```
16 +
17 +## Integration Method
18 +
19 +**Vercel AI SDK is an agentic provider** - use Tool Router for user isolation.
20 +
21 +### Native Tools (Recommended)
22 +
23 +```typescript
24 +import { Composio } from '@composio/core';
25 +import { VercelProvider } from '@composio/vercel';
26 +import { openai } from '@ai-sdk/openai';
27 +import { generateText } from 'ai';
28 +
29 +const composio = new Composio({
30 + apiKey: process.env.COMPOSIO_API_KEY,
31 + provider: new VercelProvider(),
32 +});
33 +
34 +async function runAgent(userId: string, prompt: string) {
35 + // Create user session
36 + const session = await composio.create(userId, {
37 + toolkits: ['github'],
38 + manageConnections: true
39 + });
40 +
41 + // Get native Vercel-formatted tools
42 + const tools = await session.tools();
43 +
44 + // Use with Vercel AI SDK
45 + const result = await generateText({
46 + model: openai('gpt-4o'),
47 + prompt,
48 + tools,
49 + maxSteps: 10,
50 + });
51 +
52 + return result.text;
53 +}
54 +
55 +await runAgent('user_123', 'Create a GitHub issue');
56 +```
57 +
58 +### MCP Integration (Optional)
59 +
60 +```typescript
61 +import { Composio } from '@composio/core';
62 +import { experimental_createMCPClient as createMCPClient } from '@ai-sdk/mcp';
63 +import { streamText } from 'ai';
64 +
65 +const composio = new Composio();
66 +
67 +async function runAgentMCP(userId: string, prompt: string) {
68 + // Create session
69 + const session = await composio.create(userId, {
70 + toolkits: ['github'],
71 + manageConnections: true
72 + });
73 +
74 + // Connect via MCP
75 + const client = await createMCPClient({
76 + transport: {
77 + type: 'http',
78 + url: session.mcp.url,
79 + headers: session.mcp.headers
80 + }
81 + });
82 +
83 + const tools = await client.tools();
84 +
85 + // Use with any framework
86 + const stream = await streamText({
87 + model: openai('gpt-4o'),
88 + prompt,
89 + tools,
90 + });
91 +
92 + for await (const chunk of stream.textStream) {
93 + process.stdout.write(chunk);
94 + }
95 +}
96 +```
97 +
98 +## Key Resources
99 +
100 +- **Vercel AI SDK Docs**: https://ai-sdk.dev/docs/introduction
101 +- **Tool Router Guide**: `/building-agents`
102 +- **Building Agents Guide**: https://vercel.com/kb/guide/how-to-build-ai-agents-with-vercel-and-the-ai-sdk
103 +- **Native vs MCP**: Use native tools for better performance, MCP for framework flexibility
104 +
105 +## Environment Variables
106 +
107 +```bash
108 +COMPOSIO_API_KEY=...
109 +OPENAI_API_KEY=... # Or other model provider
110 +```
111 +
112 +## Next Steps
113 +
114 +1. Use `/building-agents` for comprehensive Tool Router documentation
115 +2. Check `ts/examples/vercel/` for complete examples
116 +3. See [Vercel AI SDK docs](https://ai-sdk.dev) for framework-specific features
.agents/skills/building-agents/SKILL.md new
+440
@@ -0,0 +1,440 @@
1 +# Building AI Agents with Composio SDK
2 +
3 +This skill provides comprehensive guidance for building AI agents using Composio SDK with various provider frameworks.
4 +
5 +## Overview
6 +
7 +Composio integrates with 10+ major AI agent frameworks, allowing you to add tools and external integrations to your agents. Each framework-specific skill provides:
8 +- Installing and setting up the provider SDK
9 +- Finding latest SDK versions (NPM/PyPI)
10 +- Official documentation links and latest examples
11 +- Code examples for building agents with Composio tools
12 +- Best practices and troubleshooting tips
13 +
14 +## Installing Composio Packages
15 +
16 +### Working in Composio SDK Repository (This Workspace)
17 +
18 +If you're working within the Composio SDK repository itself, install packages from the workspace:
19 +
20 +**TypeScript:**
21 +```bash
22 +pnpm i @composio/core @composio/<provider> --workspace
23 +```
24 +
25 +**Example:**
26 +```bash
27 +pnpm i @composio/core @composio/openai --workspace
28 +```
29 +
30 +### External Projects (Outside SDK Repository)
31 +
32 +For projects outside the Composio SDK repository, install from NPM/PyPI:
33 +
34 +**TypeScript:**
35 +```bash
36 +npm install @composio/core @composio/<provider>
37 +```
38 +
39 +**Python:**
40 +```bash
41 +pip install composio-<provider>
42 +# or
43 +uv pip install composio-<provider>
44 +```
45 +
46 +**Examples:**
47 +```bash
48 +# TypeScript
49 +npm install @composio/core @composio/openai
50 +
51 +# Python
52 +pip install composio-openai
53 +```
54 +
55 +## Available Framework Skills
56 +
57 +Use `/building-agents-using-<framework>` to access specific guides:
58 +
59 +### 1. **building-agents-using-openai**
60 +Build agents using OpenAI's Chat Completions API, Assistants API, and Agents API.
61 +- **Languages**: TypeScript, Python
62 +- **Key Features**: Function calling, streaming, parallel tool calls
63 +- **Models**: GPT-4o, GPT-4o-mini, GPT-4 Turbo
64 +- **Use Cases**: General-purpose agents, chatbots, automation
65 +
66 +**Invoke:** `/building-agents-using-openai`
67 +
68 +### 2. **building-agents-using-anthropic**
69 +Build agents using Anthropic's Codex API and Codex Agent SDK.
70 +- **Languages**: TypeScript, Python
71 +- **Key Features**: Prompt caching, long context, thinking blocks
72 +- **Models**: Codex 3.7 Sonnet, Codex 3.5 Sonnet, Codex 3 Opus
73 +- **Use Cases**: Complex reasoning, code analysis, long documents
74 +
75 +**Invoke:** `/building-agents-using-anthropic`
76 +
77 +### 3. **building-agents-using-langchain**
78 +Build agents using LangChain and LangGraph for production workflows.
79 +- **Languages**: TypeScript, Python
80 +- **Key Features**: Graph-based agents, middleware, state management
81 +- **Framework**: LangGraph recommended for production
82 +- **Use Cases**: Multi-step workflows, RAG with actions, complex agents
83 +
84 +**Invoke:** `/building-agents-using-langchain`
85 +
86 +### 4. **building-agents-using-langgraph**
87 +Build stateful, durable agents using LangGraph (v1.0).
88 +- **Languages**: TypeScript, Python
89 +- **Key Features**: Durable execution, human-in-the-loop, persistent memory
90 +- **Status**: Production-ready (v1.0 released late 2025)
91 +- **Use Cases**: Long-running workflows, supervised agents, multi-agent systems
92 +
93 +**Invoke:** `/building-agents-using-langgraph`
94 +
95 +### 5. **building-agents-using-google**
96 +Build agents using Google's Gemini API and GenAI SDK.
97 +- **Languages**: TypeScript, Python
98 +- **Key Features**: Compositional function calling, parallel execution, thinking
99 +- **Models**: Gemini 3 Flash/Pro, Gemini 2.5 Flash/Pro
100 +- **Use Cases**: Multi-step workflows, location-based services, data analysis
101 +
102 +**Invoke:** `/building-agents-using-google`
103 +
104 +### 6. **building-agents-using-vercel**
105 +Build agents using Vercel AI SDK for TypeScript/JavaScript applications.
106 +- **Languages**: TypeScript, JavaScript
107 +- **Key Features**: ToolLoopAgent, streaming, multi-provider support (40+)
108 +- **Frameworks**: Next.js, Node.js, React, Vue, Svelte
109 +- **Use Cases**: AI chatbots, web applications, full-stack AI
110 +
111 +**Invoke:** `/building-agents-using-vercel`
112 +
113 +### 7. **building-agents-using-llamaindex**
114 +Build RAG-enhanced agents using LlamaIndex.
115 +- **Languages**: TypeScript, Python
116 +- **Key Features**: ReAct agents, query engines as tools, workflows
117 +- **Framework**: Workflows 1.0 for complex agentic systems
118 +- **Use Cases**: RAG + actions, documentation bots, code assistants
119 +
120 +**Invoke:** `/building-agents-using-llamaindex`
121 +
122 +### 8. **building-agents-using-mastra**
123 +Build agents using Mastra, the modern TypeScript framework from the Gatsby team.
124 +- **Languages**: TypeScript
125 +- **Key Features**: Autonomous agents, 40+ model providers, streaming
126 +- **Status**: v1.0 released January 2026
127 +- **Use Cases**: GitHub automation, web search, multi-tool workflows
128 +
129 +**Invoke:** `/building-agents-using-mastra`
130 +
131 +### 9. **building-agents-using-cloudflare**
132 +Build edge-deployed agents using Cloudflare Workers AI and Agents SDK.
133 +- **Languages**: TypeScript, JavaScript
134 +- **Key Features**: Edge deployment, embedded function calling, Durable Objects
135 +- **Platform**: Cloudflare Workers, Workers AI
136 +- **Use Cases**: Low-latency agents, real-time chat, API orchestration
137 +
138 +**Invoke:** `/building-agents-using-cloudflare`
139 +
140 +### 10. **building-agents-using-crewai**
141 +Build multi-agent teams using CrewAI for collaborative AI.
142 +- **Languages**: Python
143 +- **Key Features**: Role-based agents, task dependencies, YAML configs
144 +- **Framework**: Lean, fast, independent of LangChain
145 +- **Use Cases**: Research & reporting, content creation, data analysis
146 +
147 +**Invoke:** `/building-agents-using-crewai`
148 +
149 +### 11. **building-agents-using-autogen**
150 +Build multi-agent conversational systems using Microsoft AutoGen.
151 +- **Languages**: Python
152 +- **Key Features**: Multi-agent chat, AutoGen Studio, event-driven core
153 +- **Status**: Microsoft Agent Framework is the successor
154 +- **Use Cases**: Multi-agent conversations, research, customer support
155 +
156 +**Invoke:** `/building-agents-using-autogen`
157 +
158 +## Finding Latest SDK Versions
159 +
160 +Each skill includes commands to find the latest versions of both Composio packages and provider SDKs.
161 +
162 +### Find Latest Composio Package Version
163 +
164 +**NPM (TypeScript):**
165 +```bash
166 +npm view @composio/<provider> version
167 +# Example
168 +npm view @composio/openai version
169 +```
170 +
171 +**PyPI (Python):**
172 +```bash
173 +pip index versions composio-<provider> | grep "Available versions" | head -1
174 +# Example
175 +pip index versions composio-openai | grep "Available versions" | head -1
176 +```
177 +
178 +### Find Latest Provider SDK Version
179 +
180 +**NPM (TypeScript):**
181 +```bash
182 +npm view <provider-package> version
183 +# Example
184 +npm view openai version
185 +```
186 +
187 +**PyPI (Python):**
188 +```bash
189 +pip index versions <provider-package> | grep "Available versions" | head -1
190 +# Example
191 +pip index versions openai | grep "Available versions" | head -1
192 +```
193 +
194 +## Tool Router vs Direct Tools
195 +
196 +Composio SDK supports two integration methods based on the provider type:
197 +
198 +### 🤖 Agentic Providers (Tool Router ONLY)
199 +
200 +These frameworks support full modifier capabilities and **MUST use Tool Router** for user-isolated sessions:
201 +
202 +| Framework | Package | Why Tool Router |
203 +|-----------|---------|----------------|
204 +| **Vercel AI SDK** | `@composio/vercel` | Multi-agent support, modifiers |
205 +| **LangChain** | `@composio/langchain` | Complex chains, state management |
206 +| **LangGraph** | `@composio/langchain` | Stateful workflows, durability |
207 +| **Mastra** | `@composio/mastra` | Multi-provider routing |
208 +| **LlamaIndex** | `@composio/llamaindex` | RAG + agents, workflows |
209 +| **Codex Agent SDK** | `@composio/Codex-agent-sdk` | Codex agents framework |
210 +| **OpenAI Agents** | `@composio/openai-agents` | OpenAI Agents API |
211 +| **Cloudflare** | `@composio/cloudflare` | Edge agents, Durable Objects |
212 +| **CrewAI** | Python | Multi-agent teams |
213 +| **AutoGen** | Python | Multi-agent conversations |
214 +
215 +**Tool Router Benefits:**
216 +- ✅ **User Isolation**: Each user gets their own tool session
217 +- ✅ **Auto-Authentication**: In-chat OAuth flows
218 +- ✅ **Scoped Access**: Control toolkits per user
219 +- ✅ **Connection Management**: Automatic OAuth handling
220 +- ✅ **Production Ready**: Built for multi-user applications
221 +
222 +### 📦 Non-Agentic Providers (Direct Tools)
223 +
224 +These providers only support schema modifiers and use **direct tools** approach:
225 +
226 +| Framework | Package | Why Direct Tools |
227 +|-----------|---------|-----------------|
228 +| **OpenAI** | `@composio/openai` | Chat Completions, Assistants API |
229 +| **Anthropic** | `@composio/anthropic` | Codex Messages API |
230 +| **Google Gemini** | `@composio/google` | GenAI SDK |
231 +
232 +**Direct Tools Characteristics:**
233 +- ✅ Simpler for single-user apps
234 +- ✅ No session management needed
235 +- ⚠️ Not suitable for multi-user production apps
236 +- ⚠️ Manual authentication required
237 +
238 +### Tool Router Quick Start
239 +
240 +```typescript
241 +import { Composio } from '@composio/core';
242 +import { OpenAI } from 'openai';
243 +
244 +const composio = new Composio();
245 +const openai = new OpenAI();
246 +
247 +async function runAgent(userId: string, prompt: string) {
248 + // Create isolated session for user
249 + const session = await composio.create(userId, {
250 + toolkits: ['github'],
251 + manageConnections: true // Enable auto-authentication
252 + });
253 +
254 + // Get tools from session
255 + const tools = await session.tools();
256 +
257 + // Use with OpenAI
258 + const response = await openai.chat.completions.create({
259 + model: 'gpt-4o',
260 + messages: [{ role: 'user', content: prompt }],
261 + tools: tools,
262 + });
263 +
264 + // Handle tool calls
265 + if (response.choices[0].message.tool_calls) {
266 + const result = await composio.provider.handleToolCalls(userId, response);
267 + return result;
268 + }
269 +}
270 +
271 +// Each user gets isolated tools
272 +await runAgent('user_123', 'Create a GitHub issue');
273 +await runAgent('user_456', 'Check my Gmail'); // Different user, different session
274 +```
275 +
276 +### Tool Router with Framework Integration
277 +
278 +Each framework skill includes Tool Router examples. See:
279 +- `/building-agents-using-openai` - Tool Router with OpenAI
280 +- `/building-agents-using-anthropic` - Tool Router with Codex
281 +- `/building-agents-using-vercel` - Tool Router with Vercel AI SDK
282 +- And all other framework skills
283 +
284 +### Learn More About Tool Router
285 +
286 +For comprehensive Tool Router documentation, use:
287 +```bash
288 +/composio-tool-router
289 +```
290 +
291 +## Quick Start Example
292 +
293 +Here's a quick example using OpenAI with direct tools (single-user):
294 +
295 +### TypeScript
296 +
297 +```typescript
298 +import { Composio } from '@composio/core';
299 +import { OpenAI } from 'openai';
300 +
301 +const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
302 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
303 +
304 +// Get tools
305 +const tools = await composio.tools.get('default', { toolkits: ['github'] });
306 +
307 +// Use with OpenAI
308 +const response = await openai.chat.completions.create({
309 + model: 'gpt-4o',
310 + messages: [{ role: 'user', content: 'Create a GitHub issue' }],
311 + tools: tools,
312 +});
313 +
314 +// Handle tool calls
315 +if (response.choices[0].message.tool_calls) {
316 + const result = await composio.provider.handleToolCalls('default', response);
317 + console.log(result);
318 +}
319 +```
320 +
321 +### Python
322 +
323 +```python
324 +from composio_openai import ComposioToolSet, Action
325 +from openai import OpenAI
326 +
327 +openai_client = OpenAI(api_key="YOUR_OPENAI_KEY")
328 +composio_toolset = ComposioToolSet(api_key="YOUR_COMPOSIO_KEY")
329 +
330 +# Get tools
331 +tools = composio_toolset.get_tools(actions=[Action.GITHUB_CREATE_ISSUE])
332 +
333 +# Use with OpenAI
334 +response = openai_client.chat.completions.create(
335 + model="gpt-4o",
336 + messages=[{"role": "user", "content": "Create a GitHub issue"}],
337 + tools=tools,
338 +)
339 +
340 +# Handle tool calls
341 +result = composio_toolset.handle_tool_calls(response)
342 +```
343 +
344 +## Provider Comparison
345 +
346 +| Provider | Languages | Best For | Complexity | Maturity |
347 +|----------|-----------|----------|------------|----------|
348 +| OpenAI | TS, Py | General purpose, function calling | Low | Mature |
349 +| Anthropic | TS, Py | Complex reasoning, long context | Low | Mature |
350 +| LangChain | TS, Py | Prototyping multi-agent workflows | Medium | Mature |
351 +| LangGraph | TS, Py | Production stateful agents | High | Mature (v1.0) |
352 +| Google Gemini | TS, Py | Compositional function calling | Low | Mature |
353 +| Vercel AI SDK | TS | Full-stack web applications | Low | Mature (v6.0) |
354 +| LlamaIndex | TS, Py | RAG + agents | Medium | Mature |
355 +| Mastra | TS | Modern TypeScript apps | Low | New (v1.0 2026) |
356 +| Cloudflare | TS | Edge-deployed agents | Medium | Growing |
357 +| CrewAI | Py | Multi-agent teams | Medium | Mature |
358 +| AutoGen | Py | Research multi-agent systems | High | Mature |
359 +
360 +## Common Composio Features
361 +
362 +All frameworks support these Composio features:
363 +
364 +### 1. Tool Management
365 +```typescript
366 +// Get tools by app
367 +const tools = await composio.tools.get('default', { apps: ['github', 'slack'] });
368 +
369 +// Get specific actions
370 +const tools = await composio.tools.get('default', { actions: ['GITHUB_CREATE_ISSUE'] });
371 +
372 +// Get by toolkit
373 +const tools = await composio.tools.get('default', { toolkits: ['github'] });
374 +```
375 +
376 +### 2. Connected Accounts
377 +```typescript
378 +// Manage user integrations
379 +const account = await composio.connectedAccounts.initiate({
380 + integrationId: 'github',
381 + entityId: 'user-123',
382 +});
383 +```
384 +
385 +### 3. Custom Tools
386 +```typescript
387 +// Create custom tools
388 +const customTool = await composio.tools.createCustomTool({
389 + name: 'My Tool',
390 + description: 'Tool description',
391 + execute: async (input) => {
392 + // Implementation
393 + return { data: 'result' };
394 + },
395 +});
396 +```
397 +
398 +## Environment Variables
399 +
400 +Most examples require:
401 +
402 +```bash
403 +# Composio
404 +COMPOSIO_API_KEY=...
405 +
406 +# LLM Provider (choose one or more)
407 +OPENAI_API_KEY=sk-...
408 +ANTHROPIC_API_KEY=sk-ant-...
409 +GOOGLE_API_KEY=...
410 +```
411 +
412 +## Documentation Resources
413 +
414 +- **Composio Docs**: https://docs.composio.dev/
415 +- **Composio GitHub**: https://github.com/composiohq/composio-sdk
416 +- **API Reference**: https://docs.composio.dev/api-reference
417 +- **Examples**: Check `ts/examples/` and `python/examples/` in this repository
418 +
419 +## Getting Help
420 +
421 +- **Discord**: https://discord.gg/composio
422 +- **GitHub Issues**: https://github.com/composiohq/composio-sdk/issues
423 +- **Documentation**: https://docs.composio.dev/
424 +
425 +## Next Steps
426 +
427 +1. Choose a framework from the list above
428 +2. Invoke the corresponding skill (e.g., `/building-agents-using-openai`)
429 +3. Follow the installation and setup instructions
430 +4. Try the code examples
431 +5. Build your agent!
432 +
433 +## Tips
434 +
435 +- **Start simple** - Begin with OpenAI or Anthropic for easiest setup
436 +- **Use LangGraph** for production stateful agents
437 +- **Try Vercel AI SDK** for full-stack web applications
438 +- **Use CrewAI** for multi-agent collaborative systems
439 +- **Check examples** in the repository for working code
440 +- **Read framework docs** linked in each skill for advanced features
.agents/skills/create-cli-e2e/SKILL.md new
+438
@@ -0,0 +1,438 @@
1 +---
2 +description: Write end-to-end tests for CLI commands using the Docker-based test framework in ts/e2e-tests/cli/.
3 +---
4 +
5 +# CLI E2E Test Development
6 +
7 +Write, expand, and maintain end-to-end tests for CLI commands in `ts/e2e-tests/cli/`.
8 +
9 +## When to Use
10 +
11 +- Adding a new e2e test suite for a CLI command
12 +- Modifying or extending an existing CLI e2e test
13 +- Debugging a failing CLI e2e test
14 +- Reviewing whether a CLI command's output contract is properly tested
15 +
16 +For CLI **design** (arguments, flags, help text, UX), see the `create-cli` skill.
17 +For CLI **implementation** (Effect patterns, services, command registration), see the `implement-cli-command` skill.
18 +
19 +## Architecture
20 +
21 +Each CLI e2e test runs the compiled `composio` binary inside a **scratch Debian Docker container**. The binary is self-contained (built via `bun build --compile`) — no Node, Bun, or pnpm exists in the runtime image.
22 +
23 +Key properties:
24 +
25 +- Each test suite = a directory under `ts/e2e-tests/cli/<suite-name>/`
26 +- Use `runCmd` only. Never use `runFixture` (throws an error for CLI tests). Never set `usesFixtures`.
27 +- **Each `runCmd` call creates a fresh container.** No state persists between calls.
28 +- Commands run inside `sh -c '...'` — POSIX shell only, no bash-isms.
29 +- Containers have network access — API-calling commands work.
30 +- `HOME=/tmp`, cache dir is `/tmp/.composio/` — auth passes via env vars only.
31 +- `process.stdout.isTTY` is always `false` inside Docker — the CLI always runs in piped mode.
32 +
33 +### What "piped mode" means for tests
34 +
35 +Inside Docker, the composio binary's stdout is never a TTY. This triggers the CLI's piped-mode behavior (see `ts/packages/cli/AGENTS.md` § "Output Conventions"):
36 +- `ui.output()` writes to stdout
37 +- All Clack decoration is suppressed
38 +- stderr is empty for successful commands
39 +
40 +## File Structure
41 +
42 +For a new test suite `<suite-name>`, create 2 files:
43 +
44 +```
45 +ts/e2e-tests/cli/<suite-name>/
46 +├── e2e.test.ts # Test file
47 +└── package.json # Package manifest
48 +```
49 +
50 +### Naming Conventions
51 +
52 +- **Directory**: hyphen-separated lowercase matching the command structure
53 + - `version`, `whoami`, `toolkits-list`, `tools-info`, `auth-configs-list`, `connected-accounts-link`
54 +- **Package name**: `@e2e-tests/cli-<suite-name>`
55 + - `@e2e-tests/cli-version`, `@e2e-tests/cli-toolkits-list`
56 +
57 +### package.json Template
58 +
59 +```json
60 +{
61 + "name": "@e2e-tests/cli-<suite-name>",
62 + "version": "0.0.0",
63 + "private": true,
64 + "type": "module",
65 + "scripts": {
66 + "typecheck": "tsc --noEmit",
67 + "test:e2e": "bun test e2e.test.ts",
68 + "test:e2e:cli": "bun test e2e.test.ts"
69 + },
70 + "devDependencies": {
71 + "@e2e-tests/utils": "workspace:*"
72 + }
73 +}
74 +```
75 +
76 +## Choosing a Test Pattern
77 +
78 +Use this decision tree to select the right pattern:
79 +
80 +```
81 +Does the command need env vars (e.g., COMPOSIO_API_KEY)?
82 +├─ No → Is the output deterministic (exact value known at test time)?
83 +│ ├─ Yes → Pattern A (simple command, exact assertions)
84 +│ └─ No → Pattern D (fuzzy assertions: toContain, toBeGreaterThan)
85 +└─ Yes → Is the output deterministic given the env?
86 + ├─ Yes → Pattern B (env vars + exact assertions)
87 + └─ No → Pattern D (env vars + fuzzy assertions)
88 +
89 +Are you testing an error case (missing args, invalid input)?
90 +└─ Yes → Pattern C (non-zero exit code, stderr non-empty)
91 +
92 +Does the command perform an action with no machine-readable output?
93 +└─ Yes → Pattern E (exitCode=0, stdout empty, no redirect test)
94 +```
95 +
96 +## Test Patterns
97 +
98 +### Pattern A: Simple Command, No Env Vars (Canonical)
99 +
100 +For commands that produce deterministic output without needing authentication. This is the base pattern — all other patterns are variations of this.
101 +
102 +**Reference**: `ts/e2e-tests/cli/version/e2e.test.ts`
103 +
104 +```typescript
105 +/**
106 + * CLI version command e2e test
107 + *
108 + * Verifies that the compiled composio CLI behaves correctly in a scratch container.
109 + */
110 +
111 +import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
112 +import { TIMEOUTS } from '@e2e-tests/utils/const';
113 +import { describe, it, expect, beforeAll } from 'bun:test';
114 +import cliPkg from '../../../packages/cli/package.json' with { type: 'json' };
115 +
116 +e2e(import.meta.url, {
117 + versions: {
118 + cli: ['current'],
119 + },
120 + defineTests: ({ runCmd }) => {
121 + const expectedVersion = String(cliPkg.version ?? '').trim();
122 + let versionResult: E2ETestResult;
123 + let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
124 +
125 + beforeAll(async () => {
126 + versionResult = await runCmd('composio version');
127 + redirectedResult = await runCmd({
128 + command: 'composio version > out.txt',
129 + files: ['out.txt'],
130 + });
131 + }, TIMEOUTS.FIXTURE);
132 +
133 + describe('composio version', () => {
134 + it('exits successfully', () => {
135 + expect(versionResult.exitCode).toBe(0);
136 + });
137 +
138 + it('stdout matches snapshot', () => {
139 + expect(sanitizeOutput(versionResult.stdout)).toBe(expectedVersion);
140 + });
141 +
142 + it('stderr matches snapshot', () => {
143 + expect(versionResult.stderr).toBe('');
144 + });
145 + });
146 +
147 + describe('stdout redirection to out.txt', () => {
148 + it('exits successfully', () => {
149 + expect(redirectedResult.exitCode).toBe(0);
150 + });
151 +
152 + it('stdout is empty', () => {
153 + expect(redirectedResult.stdout).toBe('');
154 + });
155 +
156 + it('stderr is empty', () => {
157 + expect(redirectedResult.stderr).toBe('');
158 + });
159 +
160 + it('out.txt matches snapshot', () => {
161 + expect(sanitizeOutput(redirectedResult.files['out.txt'])).toBe(expectedVersion);
162 + });
163 + });
164 + },
165 +});
166 +```
167 +
168 +**Structure summary:**
169 +- Two test groups: **command execution** (stdout has data, stderr empty) + **stdout redirection** (file has data, Docker stdout/stderr both empty)
170 +- Use `sanitizeOutput()` on stdout and file contents before assertions
171 +- Use `TIMEOUTS.FIXTURE` for the `beforeAll` that runs Docker commands
172 +
173 +### Pattern B: Command Requiring Env Vars
174 +
175 +**Same as Pattern A**, with three additions:
176 +
177 +**Reference**: `ts/e2e-tests/cli/whoami/e2e.test.ts`
178 +
179 +1. **Type augmentation** for compile-time safety on `Bun.env`:
180 + ```typescript
181 + declare module 'bun' {
182 + interface Env {
183 + COMPOSIO_API_KEY: string;
184 + }
185 + }
186 + ```
187 +
188 +2. **Pass env vars** in the config:
189 + ```typescript
190 + env: {
191 + COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
192 + },
193 + ```
194 +
195 +3. **Derive expected values** from the env:
196 + ```typescript
197 + const expectedApiKey = Bun.env.COMPOSIO_API_KEY.trim();
198 + ```
199 +
200 +The rest follows the same two-group structure (command execution + stdout redirection).
201 +
202 +### Pattern C: Error Case Testing
203 +
204 +**Differences from Pattern A:**
205 +- No stdout redirection test needed — error cases don't produce data output
206 +- Assert non-zero exit code with `not.toBe(0)` (don't hardcode a specific error code)
207 +- Assert stderr is non-empty; optionally use `toContain()` for specific error message fragments
208 +- Import only `E2ETestResult`, not `E2ETestResultWithFiles`
209 +
210 +```typescript
211 +import { e2e, sanitizeOutput, type E2ETestResult } from '@e2e-tests/utils';
212 +import { TIMEOUTS } from '@e2e-tests/utils/const';
213 +import { describe, it, expect, beforeAll } from 'bun:test';
214 +
215 +e2e(import.meta.url, {
216 + versions: { cli: ['current'] },
217 + defineTests: ({ runCmd }) => {
218 + let missingArgResult: E2ETestResult;
219 +
220 + beforeAll(async () => {
221 + missingArgResult = await runCmd('composio manage tools info');
222 + }, TIMEOUTS.FIXTURE);
223 +
224 + describe('composio manage tools info (missing argument)', () => {
225 + it('exits with non-zero code', () => {
226 + expect(missingArgResult.exitCode).not.toBe(0);
227 + });
228 + it('stderr contains an error message', () => {
229 + expect(missingArgResult.stderr).not.toBe('');
230 + });
231 + });
232 + },
233 +});
234 +```
235 +
236 +Pattern C can be combined with A or B in the same test file to test both success and error paths.
237 +
238 +### Pattern D: Multi-line / API-dependent Output
239 +
240 +**Same structure as Pattern A or B** (depending on whether env vars are needed), with different assertion strategies:
241 +
242 +- **Never use exact-match assertions** (`toBe`) on API data — the data changes over time.
243 +- Use `toContain()` for known, stable items (e.g., `github`, `gmail` are always present).
244 +- Use `toBeGreaterThan()` for structural checks (line count, length).
245 +- Use `toMatch()` with regex for format validation.
246 +
247 +```typescript
248 +// Instead of:
249 +expect(sanitizeOutput(listResult.stdout)).toBe(exactValue);
250 +
251 +// Use fuzzy assertions:
252 +expect(sanitizeOutput(listResult.stdout).length).toBeGreaterThan(0);
253 +expect(sanitizeOutput(listResult.stdout)).toContain('github');
254 +const lines = sanitizeOutput(listResult.stdout).split('\n').filter(Boolean);
255 +expect(lines.length).toBeGreaterThan(1);
256 +```
257 +
258 +The redirect test group is identical to Pattern A — assert the file contains data, Docker stdout/stderr are empty.
259 +
260 +### Pattern E: Action Command, No Stdout Data
261 +
262 +For commands that perform an action but produce no machine-readable output (e.g., `logout`, `upgrade`).
263 +
264 +**Differences from Pattern A:**
265 +- No redirection test — there's no data to redirect
266 +- stdout should be literally empty (no `sanitizeOutput()` needed)
267 +- Import only `E2ETestResult`, not `E2ETestResultWithFiles`
268 +
269 +```typescript
270 +e2e(import.meta.url, {
271 + versions: { cli: ['current'] },
272 + defineTests: ({ runCmd }) => {
273 + let logoutResult: E2ETestResult;
274 +
275 + beforeAll(async () => {
276 + logoutResult = await runCmd('composio logout');
277 + }, TIMEOUTS.FIXTURE);
278 +
279 + describe('composio logout', () => {
280 + it('exits successfully', () => {
281 + expect(logoutResult.exitCode).toBe(0);
282 + });
283 +
284 + it('stdout is empty', () => {
285 + expect(logoutResult.stdout).toBe('');
286 + });
287 +
288 + it('stderr is empty', () => {
289 + expect(logoutResult.stderr).toBe('');
290 + });
291 + });
292 + },
293 +});
294 +```
295 +
296 +## Commands NOT Testable with This Framework
297 +
298 +Do not attempt to write e2e tests for:
299 +
300 +| Category | Examples | Why |
301 +|---|---|---|
302 +| **Interactive commands** | `login`, `init` (with prompts) | No TTY in Docker — Clack prompts hang |
303 +| **Long-running commands** | `triggers listen` | No mechanism to stop the process |
304 +| **Browser-dependent commands** | `login` (without `--no-browser`) | No browser in Docker |
305 +| **Host filesystem writers** | `generate` (writes to project dir) | Docker container is isolated |
306 +
307 +## Environment Variables
308 +
309 +### Auto-passed vars
310 +
311 +`COMPOSIO_API_KEY` and `OPENAI_API_KEY` are automatically forwarded to Docker containers if present on the host (defined in `WELL_KNOWN_ENV_VARS`).
312 +
313 +### Declaring required vars
314 +
315 +For tests that need env vars:
316 +
317 +1. Add the `declare module 'bun'` augmentation (compile-time safety).
318 +2. Pass via `E2EConfig.env` (runtime delivery to Docker).
319 +3. If any `E2EConfig.env` value is `undefined`, the test fails fast at startup — before any Docker container runs.
320 +
321 +### Multiple env vars
322 +
323 +```typescript
324 +declare module 'bun' {
325 + interface Env {
326 + COMPOSIO_API_KEY: string;
327 + COMPOSIO_BASE_URL: string;
328 + }
329 +}
330 +
331 +e2e(import.meta.url, {
332 + env: {
333 + COMPOSIO_API_KEY: Bun.env.COMPOSIO_API_KEY,
334 + COMPOSIO_BASE_URL: Bun.env.COMPOSIO_BASE_URL,
335 + },
336 + // ...
337 +});
338 +```
339 +
340 +## Shell Quoting
341 +
342 +Commands run inside `sh -c '...'` in a POSIX shell. Rules:
343 +
344 +- Use double quotes for flag values with spaces or special chars:
345 + ```typescript
346 + runCmd('composio manage tools info "GMAIL_SEND_EMAIL"')
347 + ```
348 +- Use single quotes inside double-quoted contexts for literal strings.
349 +- **No bash-isms**: no `[[`, no `$()`, no arrays.
350 +- `PATH` is `/usr/local/bin:/bin` — set in the Dockerfile.
351 +
352 +## Checklist for Adding a New Test Suite
353 +
354 +1. **Create directory**: `ts/e2e-tests/cli/<suite-name>/`
355 +2. **Create `package.json`**: Use the template above with name `@e2e-tests/cli-<suite-name>`
356 +3. **Create `e2e.test.ts`**: Follow the appropriate pattern (A through E)
357 +4. **Run `pnpm install`** from the monorepo root to resolve the workspace link
358 +5. **Run `pnpm test:e2e:cli`** to verify the test passes
359 +6. **Update `ts/e2e-tests/cli/README.md`**: Add a new row to the test suites table
360 +
361 +### README table format
362 +
363 +```markdown
364 +| [suite-name](./suite-name/) | `composio <command>` description | `ENV_VAR_1`, `ENV_VAR_2` (or None) |
365 +```
366 +
367 +## Troubleshooting
368 +
369 +### Reading DEBUG.log
370 +
371 +Each test suite generates a `DEBUG.log` in its directory with Docker execution details: container name, command, duration, exit code, stdout, stderr. Read this first when a test fails.
372 +
373 +### Stale Docker image
374 +
375 +If CLI code changed but tests show old behavior, the Docker image is cached. Rebuild:
376 +
377 +```bash
378 +docker rmi composio-e2e-cli:$(jq -r .version ts/packages/cli/package.json)
379 +```
380 +
381 +### Shell quoting issues
382 +
383 +Check the command string in `DEBUG.log`. Look for unescaped special characters that break `sh -c` parsing.
384 +
385 +### Missing env vars
386 +
387 +The error appears at test startup (before any Docker container runs), not during execution. Verify `Bun.env.*` values are set in your shell.
388 +
389 +### Container statelessness
390 +
391 +Each `runCmd` call runs in a fresh container. If you need to test a multi-step workflow (e.g., "set config then run command"), you must chain commands in a single `runCmd` call:
392 +
393 +```typescript
394 +runCmd('composio logout && composio whoami')
395 +```
396 +
397 +## API Reference
398 +
399 +### `runCmd` (two overloads)
400 +
401 +```typescript
402 +// Simple: returns { exitCode, stdout, stderr }
403 +const result: E2ETestResult = await runCmd('composio version');
404 +
405 +// With file capture: returns { exitCode, stdout, stderr, files }
406 +const result: E2ETestResultWithFiles<'out.txt'> = await runCmd({
407 + command: 'composio version > out.txt',
408 + files: ['out.txt'],
409 +});
410 +// Access: result.files['out.txt']
411 +```
412 +
413 +### `TIMEOUTS`
414 +
415 +Defined in `ts/e2e-tests/_utils/src/const.ts`:
416 +
417 +```typescript
418 +TIMEOUTS.DEFAULT // 5_000ms — individual test timeout
419 +TIMEOUTS.FIXTURE // 120_000ms — beforeAll timeout (Docker startup + command execution)
420 +TIMEOUTS.LLM_SHORT // 30_000ms — commands involving LLM calls
421 +TIMEOUTS.LLM_LONG // 60_000ms — commands involving longer LLM calls
422 +```
423 +
424 +Use `TIMEOUTS.FIXTURE` for the `beforeAll` that runs Docker commands. Use `TIMEOUTS.DEFAULT` for individual `it()` blocks (the default).
425 +
426 +## Reference Files
427 +
428 +| File | Purpose |
429 +|---|---|
430 +| `ts/e2e-tests/cli/version/e2e.test.ts` | Pattern A reference |
431 +| `ts/e2e-tests/cli/whoami/e2e.test.ts` | Pattern B reference |
432 +| `ts/e2e-tests/_utils/src/types.ts` | `E2EConfig`, `E2ETestResult`, `DefineTestsContext` types |
433 +| `ts/e2e-tests/_utils/src/const.ts` | `TIMEOUTS`, `WELL_KNOWN_ENV_VARS` |
434 +| `ts/e2e-tests/_utils/src/sanitize.ts` | `sanitizeOutput()` |
435 +| `ts/e2e-tests/_utils/Dockerfile.cli` | Docker image definition |
436 +| `ts/e2e-tests/cli/README.md` | Test suites table |
437 +| `CLI.md` | Planned CLI commands |
438 +| `ts/packages/cli/AGENTS.md` | CLI architecture and output conventions |
.agents/skills/create-cli/SKILL.md new
+240
@@ -0,0 +1,240 @@
1 +---
2 +description: CLI design guidelines — arguments, flags, subcommands, help, output, errors, interactivity, config precedence. Apply when designing new commands or reviewing CLI UX.
3 +globs:
4 + - "ts/packages/cli/src/**/*.ts"
5 +alwaysApply: false
6 +---
7 +
8 +# CLI Design Guidelines
9 +
10 +Design CLI surface area (syntax + behavior), human-first, script-friendly.
11 +Adapted from [clig.dev](https://clig.dev/) for our TypeScript + Effect.ts + Clack stack.
12 +
13 +## When to Use
14 +
15 +- Designing a CLI spec (before implementation) or refactoring CLI surface area.
16 +- Adding new commands, flags, or interactive prompts.
17 +- Reviewing CLI UX decisions.
18 +
19 +After designing a command, use the `implement-cli-command` skill to build it.
20 +After implementation, use the `create-cli-e2e` skill to write end-to-end tests.
21 +
22 +## Stack & Architecture
23 +
24 +See `ts/packages/cli/AGENTS.md` for the full architecture reference, including dependencies, services, effects, and vendor submodule locations.
25 +
26 +## Output Conventions
27 +
28 +The CLI separates human-readable decoration from machine-readable data. See `ts/packages/cli/AGENTS.md` § "Output Conventions" for the full specification.
29 +
30 +Key rule: when adding a command, ask "Does this produce a value scripts should capture?"
31 +- **Yes** → `ui.output(value)` for data, `ui.log.*` / `ui.note()` for context.
32 +- **No** → Only `ui.log.*` / `ui.note()` / `ui.intro()` / `ui.outro()`.
33 +
34 +**Show state changes.** When a command modifies state, say what changed and the new state:
35 +
36 +```typescript
37 +// After logout:
38 +yield* ui.log.info('Removed API key from ~/.composio/user-config.json');
39 +
40 +// After generate:
41 +yield* ui.log.success('Generated 42 tools across 5 toolkits → src/generated/');
42 +```
43 +
44 +## Arguments & Flags
45 +
46 +Define options via `@effect/cli`:
47 +
48 +```typescript
49 +const toolkits = Options.text('toolkits').pipe(
50 + Options.optional,
51 + Options.withDescription('Comma-separated toolkit slugs'),
52 +);
53 +const force = Options.boolean('force').pipe(
54 + Options.withAlias('f'),
55 + Options.withDefault(false),
56 +);
57 +```
58 +
59 +Principles:
60 +- Prefer flags over positional args for clarity and extensibility.
61 +- Provide long versions of all flags; one-letter aliases only for the most common.
62 +- Default values should be right for most users.
63 +- Never accept secrets via flags — they leak to `ps` output and shell history. Use `--password-file`, stdin, or a secret manager instead.
64 +- Support `-` for stdin/stdout when input/output is a file path.
65 +
66 +Standard flag names:
67 +
68 +| Flag | Short | Purpose |
69 +| ---- | ----- | ------- |
70 +| `--help` | `-h` | Show help (built-in via @effect/cli) |
71 +| `--version` | | Print version to stdout |
72 +| `--quiet` | `-q` | Less output |
73 +| `--verbose` | `-v` | More output (never use `-v` for version) |
74 +| `--debug` | `-d` | Debug output |
75 +| `--force` | `-f` | Skip confirmations |
76 +| `--dry-run` | `-n` | Preview only |
77 +| `--json` | | Structured output |
78 +| `--output` | `-o` | Output file path |
79 +| `--no-input` | | Disable prompts; fail if required input missing |
80 +| `--no-browser` | | Skip browser-open steps |
81 +| `--no-color` | | Disable color output |
82 +
83 +## Subcommands
84 +
85 +```typescript
86 +const login = Command.make('login', { noBrowser }, handler);
87 +const generate = Command.make('generate', { toolkits, typeTools }, handler);
88 +const root = Command.make('composio').pipe(
89 + Command.withSubcommands([login, generate, /* ... */]),
90 +);
91 +```
92 +
93 +- Follow verb-noun pattern consistently: `composio login`, `composio generate`.
94 +- Share global flags via parent command composition.
95 +- Support `composio help <subcmd>` and `composio <subcmd> --help`.
96 +- Avoid ambiguous pairs (`update` vs `upgrade`) unless sharply differentiated.
97 +
98 +## Interactivity
99 +
100 +Use `@clack/prompts` for all interactive UI. All Clack output goes to stderr via `{ output: process.stderr }`.
101 +
102 +| Prompt | When to use |
103 +| ------ | ----------- |
104 +| `text()` | Free-form text input |
105 +| `password()` | Secret input (echo disabled) |
106 +| `confirm()` | Yes/no decisions |
107 +| `select()` | Choose one from a list |
108 +| `multiselect()` | Choose multiple from a list |
109 +| `spinner()` | Long-running operations |
110 +| `log.info/warn/error/step()` | Styled status messages |
111 +| `note()` | Boxed contextual info |
112 +| `intro()` / `outro()` | Session start/end markers |
113 +
114 +Rules:
115 +- Prompt only if stdin is a TTY.
116 +- `--no-input`: never prompt; fail with actionable message if required input missing.
117 +- Make escape hatches obvious (Ctrl-C).
118 +- Destructive operations: interactive confirmation + non-interactive requires `--force`.
119 +
120 +## Error Handling
121 +
122 +- Use the `effect-errors/` module for capture and formatting.
123 +- Catch and rewrite expected errors for humans; no stack traces by default.
124 +- Put the most important info last; use red intentionally.
125 +- For unexpected crashes: provide debug info path + bug report instructions.
126 +
127 +**Write actionable error messages.** Tell the user *what went wrong* and *how to fix it*:
128 +
129 +```
130 +// Bad:
131 +Error: EACCES
132 +
133 +// Good:
134 +Can't write to ~/.composio/user-config.json.
135 +You might need to fix permissions: chmod +w ~/.composio/user-config.json
136 +
137 +// Bad:
138 +Error: 401
139 +
140 +// Good:
141 +API key is invalid or expired.
142 +Run `composio login` to authenticate again.
143 +```
144 +
145 +**Suggest corrections** when the user mistypes a subcommand or flag. If they ran `composio genrate`, suggest `composio generate`.
146 +
147 +Exit codes:
148 +
149 +| Code | Meaning |
150 +| ---- | ------- |
151 +| `0` | Success |
152 +| `1` | Generic failure |
153 +| `2` | Invalid usage (parse/validation error) |
154 +
155 +## Help & Documentation
156 +
157 +- `@effect/cli` generates help text from Command/Options declarations.
158 +- If run with missing required args, show concise help + 1–2 examples + "use --help for more".
159 +- Lead with examples; show common flags first.
160 +- Link to docs URL per subcommand when applicable.
161 +- Provide both terminal help (offline, version-synced) and web docs (searchable, linkable).
162 +
163 +Good help text structure:
164 +
165 +```
166 +USAGE
167 + $ composio generate [--toolkits <slugs>] [--type-tools]
168 +
169 +OPTIONS
170 + --toolkits <slugs> Comma-separated toolkit slugs (default: all)
171 + --type-tools Generate full type definitions
172 + -o, --output <dir> Output directory (default: @composio/core/generated)
173 +
174 +EXAMPLES
175 + $ composio generate
176 + $ composio generate --toolkits github,slack --type-tools
177 +
178 +COMMANDS
179 + composio generate ts Generate TypeScript stubs
180 + composio generate py Generate Python stubs
181 +```
182 +
183 +**Suggest next commands** when it helps the user's flow:
184 +
185 +```
186 +✔ Logged in as user@example.com
187 + Next: run `composio generate` to generate type stubs for your toolkits.
188 +```
189 +
190 +## Configuration Precedence
191 +
192 +High to low: **flags > process env > project config > user config > system config**.
193 +
194 +- Composio prefixes: `COMPOSIO_*` for app config, `DEBUG_OVERRIDE_*` for debug.
195 +- User config stored in `~/.composio/`.
196 +- Respect common env vars: `NO_COLOR`, `DEBUG`, `EDITOR`, `PAGER`, `TERM`, `TMPDIR`, `HOME`.
197 +
198 +## Naming
199 +
200 +- Subcommand names: simple, lowercase, single word when possible.
201 +- Avoid too-generic names that collide with system tools.
202 +- Keep names short but not cryptic — easy to type matters.
203 +- Never create implicit catch-all subcommands that prevent future expansion.
204 +- Don't allow arbitrary abbreviations (reserving `g` for `generate` blocks future `g`-commands).
205 +- Use explicit aliases only when there's a clear, stable mapping.
206 +
207 +## Robustness & Performance
208 +
209 +- Validate early; fail fast with good error messages.
210 +- Print something within ~100ms (especially before network I/O). Start a Clack spinner immediately before any network call.
211 +- Show progress for long tasks (interactive only) via Clack spinners.
212 +- Use timeouts for network calls; allow configuration.
213 +- Make reruns safe: idempotent where possible; recoverable on failure.
214 +- **Crash-only design**: assume cleanup might not run. Defer cleanup to the next invocation rather than relying on shutdown hooks. If a cache file is half-written, the next run should detect and rebuild it.
215 +
216 +## Example Invocations
217 +
218 +```bash
219 +# Interactive — user sees Clack decoration on stderr
220 +composio login
221 +composio generate --toolkits github,slack
222 +
223 +# Piped — only data on stdout, no decoration
224 +composio whoami | pbcopy
225 +API_KEY=$(composio whoami)
226 +composio version | cat
227 +
228 +# Non-interactive with force
229 +composio logout --force --no-input
230 +
231 +# Debug mode
232 +composio generate --debug --verbose
233 +```
234 +
235 +## References
236 +
237 +- Community CLI Guidelines: https://clig.dev/
238 +- CLI architecture: `ts/packages/cli/AGENTS.md`
239 +- @effect/cli source: `ts/vendor/effect/packages/cli/src/`
240 +- @clack/prompts source: `ts/vendor/clack/packages/prompts/src/`
.agents/skills/ephemeral-e2e-sdk-tests/SKILL.md new
+49
@@ -0,0 +1,49 @@
1 +# Ephemeral E2E SDK Tests
2 +
3 +Quick ephemeral verification tests for Composio SDK with AI frameworks. Never commit these tests.
4 +
5 +## Important Distinction
6 +
7 +- **Ephemeral tests** (this skill): Quick verification in `.agent_cache/test-<usecase>` - never committed
8 +- **Actual E2E tests that run in CI**: Use `ts/e2e-tests/` - committed to repository
9 +
10 +## Quick Setup
11 +
12 +```bash
13 +# Use descriptive usecase names (e.g., openai-direct-tools, vercel-tool-router, anthropic-mcp)
14 +TEST_DIR=".agent_cache/test-<usecase>"
15 +mkdir -p "$TEST_DIR" && cd "$TEST_DIR"
16 +npm init -y
17 +npm install @composio/core # Add framework-specific packages as needed
18 +```
19 +
20 +## What to Test
21 +
22 +- **Direct Tools (Non-Agentic)**: SDK integration with AI frameworks without Tool Router
23 +- **Tool Router (Agentic)**: User-isolated sessions with Tool Router
24 +- **MCP Integration**: MCP protocol compatibility
25 +- **Framework Compatibility**: Different AI frameworks (OpenAI, Vercel, Anthropic, etc.)
26 +
27 +## Implementation Examples
28 +
29 +For implementation examples, refer to existing skills:
30 +
31 +- **Tool Router basics**: Read `building-agents` skill
32 +- **OpenAI integration**: Read `building-agents-using-openai` skill
33 +- **Vercel AI SDK**: Read `building-agents-using-vercel` skill
34 +- **Anthropic**: Read `building-agents-using-anthropic` skill
35 +- **LangChain**: Read `building-agents-using-langchain` skill
36 +- **Other frameworks**: Check respective `building-agents-using-*` skills
37 +
38 +## Clean Up
39 +
40 +```bash
41 +cd .. && rm -rf "$TEST_DIR"
42 +```
43 +
44 +## Best Practices
45 +
46 +- **Always use .agent_cache** - These are ephemeral, never commit
47 +- **For CI E2E tests** - Use `ts/e2e-tests/` instead (see `ts/e2e-tests/README.md`)
48 +- **Use non-auth apps** - HackerNews, Public APIs for quick testing
49 +- **Report critical issues** - Add proper test cases to `ts/e2e-tests/` if needed
.agents/skills/implement-cli-command/SKILL.md new
+545
@@ -0,0 +1,545 @@
1 +---
2 +description: Implement new CLI commands in ts/packages/cli/ using Effect.ts patterns, service wiring, and @effect/cli declarations.
3 +---
4 +
5 +# Implement CLI Command
6 +
7 +Implement new commands and subcommands in `ts/packages/cli/`. Covers file creation, Effect patterns, service wiring, option declaration, output conventions, and registration.
8 +
9 +## When to Use
10 +
11 +- Implementing a new CLI command from a spec or design
12 +- Adding a subcommand to an existing command group
13 +- Wiring a new command into the command tree
14 +- Understanding how existing commands work to extend them
15 +
16 +For CLI **design** (arguments, flags, help text, UX), see the `create-cli` skill instead.
17 +For CLI **e2e tests**, see the `create-cli-e2e` skill instead.
18 +
19 +## Architecture
20 +
21 +The CLI uses `@effect/cli` for command declaration, `effect` for the runtime, and a service-oriented architecture with dependency injection via Effect layers.
22 +
23 +See `ts/packages/cli/AGENTS.md` for the full architecture reference (services, effects, models, dependencies, vendor submodule locations).
24 +
25 +```
26 +src/
27 +├── bin.ts # Entry point — layer composition, error handling, runtime
28 +├── commands/
29 +│ ├── index.ts # Command tree — registers all commands
30 +│ ├── $default.cmd.ts # Root command with global options (--log-level)
31 +│ ├── version.cmd.ts # Simple data command
32 +│ ├── whoami.cmd.ts # Data command with service dependency
33 +│ ├── login.cmd.ts # Complex command (options, spinner, polling)
34 +│ ├── logout.cmd.ts # Action command (no stdout data)
35 +│ ├── upgrade.cmd.ts # Action command (delegates to service)
36 +│ ├── generate/
37 +│ │ ├── generate.cmd.ts # Parent command group for `composio generate`
38 +│ │ ├── generate-py.cmd.ts # `composio generate py`
39 +│ │ └── generate-ts.cmd.ts # `composio generate ts`
40 +│ ├── manage/
41 +│ │ └── manage.cmd.ts # Parent command group for `composio manage`
42 +│ ├── ts/
43 +│ │ ├── ts.cmd.ts # Existing TS generation internals, referenced from generate/
44 +│ │ └── commands/
45 +│ │ └── ts.generate.cmd.ts # Reusable TS generation logic
46 +│ └── py/
47 +│ ├── py.cmd.ts # Existing Python generation internals, referenced from generate/
48 +│ └── commands/
49 +│ └── py.generate.cmd.ts
50 +├── services/ # Effect services (dependency injection)
51 +├── effects/ # Reusable Effect computations
52 +├── models/ # Effect Schema definitions
53 +├── generation/ # Code generation pipeline
54 +├── effect-errors/ # Error capture and formatting
55 +└── ui/ # Terminal output helpers
56 +```
57 +
58 +### File Naming Convention
59 +
60 +- Command files: `<name>.cmd.ts` (e.g., `version.cmd.ts`, `login.cmd.ts`)
61 +- Subcommand implementation files: `<parent>.<name>.cmd.ts` inside `commands/` (e.g., `ts.generate.cmd.ts`)
62 +- Parent command groups: `<name>.cmd.ts` at the group level (e.g., `generate/generate.cmd.ts`, `manage/manage.cmd.ts`)
63 +- Wrapper subcommand entrypoints can also live beside their parent group (e.g., `generate/generate-py.cmd.ts`, `generate/generate-ts.cmd.ts`)
64 +
65 +## Creating a New Command
66 +### Step 1: Create the Command File
67 +
68 +Create `src/commands/<name>.cmd.ts`.
69 +
70 +**Minimal template** (data command, no options):
71 +
72 +```typescript
73 +import { Command } from '@effect/cli';
74 +import { Effect } from 'effect';
75 +import { TerminalUI } from 'src/services/terminal-ui';
76 +
77 +export const myCmd = Command.make('my-command', {}).pipe(
78 + Command.withDescription('Brief description of what the command does.'),
79 + Command.withHandler(() =>
80 + Effect.gen(function* () {
81 + const ui = yield* TerminalUI;
82 +
83 + // Compute result...
84 + const result = 'some-value';
85 +
86 + yield* ui.log.info(result); // Decoration → stderr
87 + yield* ui.output(result); // Data → stdout (for scripts)
88 + })
89 + )
90 +);
91 +```
92 +
93 +**Template with options:**
94 +
95 +```typescript
96 +import { Command, Options } from '@effect/cli';
97 +import { Effect, Option } from 'effect';
98 +import { TerminalUI } from 'src/services/terminal-ui';
99 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
100 +
101 +// Define options at module level
102 +const toolkitSlug = Options.text('toolkit').pipe(
103 + Options.withDescription('Toolkit slug to look up.')
104 +);
105 +
106 +const searchOpt = Options.optional(
107 + Options.text('search')
108 +).pipe(
109 + Options.withDescription('Search query to filter results.')
110 +);
111 +
112 +export const myCmd = Command.make('my-command', { toolkitSlug, searchOpt }).pipe(
113 + Command.withDescription('Brief description.'),
114 + Command.withHandler(({ toolkitSlug, searchOpt }) =>
115 + Effect.gen(function* () {
116 + const ui = yield* TerminalUI;
117 + const client = yield* ComposioToolkitsRepository;
118 +
119 + yield* ui.intro('composio my-command');
120 +
121 + // Use options — searchOpt is Option<string>
122 + const search = Option.getOrUndefined(searchOpt);
123 +
124 + // Fetch data with spinner
125 + const result = yield* ui.withSpinner(
126 + 'Fetching data...',
127 + client.getToolkits(),
128 + { successMessage: 'Done', errorMessage: 'Failed to fetch' }
129 + );
130 +
131 + // Output
132 + yield* ui.note(formatResult(result), 'Result');
133 + yield* ui.output(formatResult(result));
134 + yield* ui.outro('Done');
135 + })
136 + )
137 +);
138 +```
139 +
140 +### Step 2: Register the Command
141 +
142 +Add the command to `src/commands/index.ts`:
143 +
144 +```typescript
145 +import { myCmd } from './my-command.cmd';
146 +
147 +const $cmd = $defaultCmd.pipe(
148 + Command.withSubcommands([
149 + versionCmd,
150 + upgradeCmd,
151 + whoamiCmd,
152 + loginCmd,
153 + logoutCmd,
154 + generateCmd,
155 + manageCmd,
156 + myCmd, // Add here
157 + ])
158 +);
159 +```
160 +
161 +### Step 3: Add Required Service Layers (if any)
162 +
163 +If your command uses a new service not already in `bin.ts`, add its layer:
164 +
165 +```typescript
166 +// In src/bin.ts
167 +const layers = Layer.mergeAll(
168 + // ... existing layers
169 + MyNewServiceLive, // Add if needed
170 +);
171 +```
172 +
173 +Most commands only use services already provided. The `ComposioToolkitsRepository` service is provided by `ComposioToolkitsRepositoryCachedLive` in `bin.ts` — you do not need to add a separate layer for the base repository.
174 +
175 +## Creating a Subcommand Group
176 +
177 +For commands like `composio manage toolkits list`, `composio manage toolkits info`:
178 +
179 +### Step 1: Create the Directory Structure
180 +
181 +```
182 +src/commands/manage/toolkits/
183 +├── toolkits.cmd.ts # Parent command group under `manage`
184 +└── commands/
185 + ├── toolkits.list.cmd.ts # composio manage toolkits list
186 + └── toolkits.info.cmd.ts # composio manage toolkits info
187 +```
188 +
189 +### Step 2: Create the Parent Command
190 +
191 +`src/commands/manage/toolkits/toolkits.cmd.ts`:
192 +```typescript
193 +import { Command } from '@effect/cli';
194 +import { toolkitsCmd$List } from './commands/toolkits.list.cmd';
195 +import { toolkitsCmd$Info } from './commands/toolkits.info.cmd';
196 +
197 +export const toolkitsCmd = Command.make('toolkits').pipe(
198 + Command.withDescription('Discover and inspect available toolkits.'),
199 + Command.withSubcommands([toolkitsCmd$List, toolkitsCmd$Info])
200 +);
201 +```
202 +
203 +### Step 3: Create Each Subcommand
204 +
205 +`src/commands/manage/toolkits/commands/toolkits.list.cmd.ts`:
206 +```typescript
207 +import { Command, Options } from '@effect/cli';
208 +import { Effect, Option } from 'effect';
209 +import { TerminalUI } from 'src/services/terminal-ui';
210 +import { ComposioToolkitsRepository } from 'src/services/composio-clients';
211 +
212 +const searchOpt = Options.optional(
213 + Options.text('search')
214 +).pipe(
215 + Options.withDescription('Search toolkits by name or description.')
216 +);
217 +
218 +export const toolkitsCmd$List = Command.make('list', { searchOpt }).pipe(
219 + Command.withDescription('List available toolkits.'),
220 + Command.withHandler(({ searchOpt }) =>
221 + Effect.gen(function* () {
222 + const ui = yield* TerminalUI;
223 + const client = yield* ComposioToolkitsRepository;
224 +
225 + const toolkits = yield* ui.withSpinner(
226 + 'Fetching toolkits...',
227 + client.getToolkits(),
228 + { successMessage: 'Toolkits loaded' }
229 + );
230 +
231 + // Format and output
232 + const output = toolkits
233 + .map(t => `${t.slug} - ${t.meta.description}`)
234 + .join('\n');
235 +
236 + yield* ui.log.info(output);
237 + yield* ui.output(output);
238 + })
239 + )
240 +);
241 +```
242 +
243 +### Step 4: Register the Parent in `manage/manage.cmd.ts`
244 +
245 +```typescript
246 +import { Command } from '@effect/cli';
247 +import { toolkitsCmd } from './toolkits/toolkits.cmd';
248 +
249 +export const manageCmd = Command.make('manage').pipe(
250 + Command.withDescription('Manage existing Composio resources.'),
251 + Command.withSubcommands([
252 + // ... existing manage subcommands
253 + toolkitsCmd,
254 + ])
255 +);
256 +```
257 +
258 +## Option Declaration Patterns
259 +Options are declared at module level using `@effect/cli`'s `Options` API. The template above demonstrates the most common types (required text, optional text). For other option types, see `ts/vendor/effect/packages/cli/src/Options.ts`.
260 +
261 +Both `Options.optional(Options.text(...))` (wrapping) and `Options.text(...).pipe(Options.optional)` (piped) are valid. Use whichever reads better.
262 +
263 +### Common patterns:
264 +
265 +```typescript
266 +import { Options } from '@effect/cli';
267 +
268 +// Boolean flag (with default)
269 +const verbose = Options.boolean('verbose').pipe(
270 + Options.withDefault(false),
271 + Options.withDescription('Enable verbose output.')
272 +);
273 +
274 +// Text with alias
275 +const output = Options.optional(
276 + Options.text('output')
277 +).pipe(
278 + Options.withAlias('o'),
279 + Options.withDescription('Output path.')
280 +);
281 +
282 +// Choice from fixed set
283 +const format = Options.choice('format', ['json', 'table', 'plain']).pipe(
284 + Options.withDefault('table'),
285 + Options.withDescription('Output format.')
286 +);
287 +```
288 +
289 +### Using Options in Handler
290 +
291 +```typescript
292 +Command.make('my-cmd', { search, verbose }).pipe(
293 + Command.withHandler(({ search, verbose }) =>
294 + Effect.gen(function* () {
295 + // search: Option<string> — use Option.getOrUndefined, Option.match, Option.isSome
296 + const searchValue = Option.getOrUndefined(search);
297 +
298 + // verbose: boolean — direct use
299 + if (verbose) { yield* Effect.logDebug('Verbose mode'); }
300 + })
301 + )
302 +);
303 +```
304 +
305 +## Output Conventions
306 +
307 +Follow the output conventions in `ts/packages/cli/AGENTS.md` § "Output Conventions" (stdout for data via `ui.output()`, stderr for decoration).
308 +
309 +**Data commands** — produce a value scripts should capture:
310 +
311 +```typescript
312 +yield* ui.note(apiKey, 'API Key'); // Decoration → stderr (pretty box)
313 +yield* ui.output(apiKey); // Data → stdout (scripts capture)
314 +```
315 +
316 +**Action commands** — perform a side effect, no data:
317 +
318 +```typescript
319 +yield* ui.log.success('Logged out successfully.');
320 +// NO ui.output() call — nothing for scripts to capture
321 +```
322 +
323 +## TerminalUI Spinners
324 +
325 +The `TerminalUI` service provides two spinner APIs. For output/decoration methods (`output`, `log.*`, `note`, `intro`, `outro`), see `ts/packages/cli/src/services/terminal-ui.ts`.
326 +
327 +```typescript
328 +// Automatic: wraps an Effect, auto-stops on success/error
329 +const result = yield* ui.withSpinner(
330 + 'Loading...',
331 + someEffect,
332 + { successMessage: 'Done!', errorMessage: 'Failed!' }
333 +);
334 +
335 +// Manual: full control over message updates
336 +const result = yield* ui.useMakeSpinner('Loading...', spinner =>
337 + Effect.gen(function* () {
338 + yield* spinner.message('Step 1...');
339 + const data = yield* fetchStep1;
340 + yield* spinner.message('Step 2...');
341 + const result = yield* fetchStep2(data);
342 + yield* spinner.stop('All done!');
343 + return result;
344 + })
345 +);
346 +```
347 +
348 +## Creating a New Service
349 +
350 +If your command requires functionality not covered by existing services (see `ts/packages/cli/AGENTS.md` for the full list):
351 +
352 +1. Define the service interface and tag in `src/services/<name>.ts`
353 +2. Create a `Live` layer implementation
354 +3. Register the layer in `src/bin.ts`
355 +
356 +Reference `src/services/upgrade-binary.ts` for a simple service pattern, or `src/services/composio-clients.ts` for a complex one with caching.
357 +
358 +## Error Handling Patterns
359 +
360 +### Optional Values
361 +
362 +```typescript
363 +yield* ctx.data.apiKey.pipe(
364 + Option.match({
365 + onNone: () => ui.log.warn('Not logged in. Run `composio login`.'),
366 + onSome: apiKey =>
367 + Effect.gen(function* () {
368 + yield* ui.output(apiKey);
369 + }),
370 + })
371 +);
372 +```
373 +
374 +### Typed Errors with catchTag
375 +
376 +```typescript
377 +yield* client.getToolkitsBySlugs(slugs).pipe(
378 + Effect.catchTag('services/InvalidToolkitsError', error =>
379 + Effect.gen(function* () {
380 + yield* ui.log.error(`Invalid toolkits: ${error.invalidToolkits.join(', ')}`);
381 + return yield* Effect.fail(error);
382 + })
383 + )
384 +);
385 +```
386 +
387 +### Logging Non-Fatal Errors
388 +
389 +```typescript
390 +yield* riskyOperation.pipe(
391 + Effect.catchAll(error =>
392 + Effect.logWarning(`Non-critical failure: ${error.message}`)
393 + )
394 +);
395 +```
396 +
397 +## Parallel Data Fetching
398 +
399 +Use `Effect.all` with `concurrency` for parallel API calls:
400 +
401 +```typescript
402 +const [toolkits, tools, triggerTypes] = yield* Effect.all(
403 + [
404 + client.getToolkits(),
405 + client.getTools(slugs),
406 + client.getTriggerTypes(slugs),
407 + ],
408 + { concurrency: 'unbounded' }
409 +);
410 +```
411 +
412 +## Extracting Reusable Logic
413 +
414 +For commands that share logic (e.g., `composio generate` delegates to `composio generate ts`):
415 +```typescript
416 +// In ts.generate.cmd.ts — export the logic separately
417 +export function generateTypescriptTypeStubs(params: { ... }) {
418 + return Effect.gen(function* () {
419 + const ui = yield* TerminalUI;
420 + // ... implementation
421 + });
422 +}
423 +
424 +// The command uses it
425 +export const tsCmd$Generate = Command.make('generate', { ... }).pipe(
426 + Command.withHandler(params => generateTypescriptTypeStubs(params))
427 +);
428 +
429 +// Other commands can reuse it
430 +// In generate/generate-ts.cmd.ts
431 +import { generateTypescriptTypeStubs } from '../ts/commands/ts.generate.cmd';
432 +yield* Match.value(envLang).pipe(
433 + Match.when('TypeScript', () => generateTypescriptTypeStubs({ ... })),
434 + Match.when('Python', () => generatePythonTypeStubs({ ... })),
435 + Match.exhaustive
436 +);
437 +```
438 +
439 +## Retry with Exponential Backoff
440 +
441 +For polling operations (e.g., waiting for OAuth):
442 +
443 +```typescript
444 +import { Schedule } from 'effect';
445 +
446 +const result = yield* ui.useMakeSpinner('Waiting...', spinner =>
447 + Effect.retry(
448 + Effect.gen(function* () {
449 + const status = yield* client.getSession(session);
450 + if (status.status === 'linked') return status;
451 + return yield* Effect.fail(new Error('Still pending'));
452 + }),
453 + Schedule.exponential('0.3 seconds').pipe(
454 + Schedule.intersect(Schedule.recurs(15)),
455 + Schedule.intersect(Schedule.spaced('5 seconds'))
456 + )
457 + ).pipe(
458 + Effect.tap(() => spinner.stop('Success!')),
459 + Effect.tapError(() => spinner.error('Timed out'))
460 + )
461 +);
462 +```
463 +
464 +## Checklist
465 +
466 +When implementing a new command:
467 +
468 +1. Create `src/commands/<name>.cmd.ts` (or `src/commands/<group>/commands/<group>.<name>.cmd.ts` for subcommands)
469 +2. Define options at module level using `Options.*`
470 +3. Create the command with `Command.make(name, options).pipe(Command.withDescription(...), Command.withHandler(...))`
471 +4. In the handler, resolve services with `yield* ServiceName`
472 +5. Follow the output convention: `ui.output()` for data, `ui.log.*` for decoration
473 +6. Register in `src/commands/index.ts` (or in the parent group's command file)
474 +7. If using a new service, add its layer to `src/bin.ts`
475 +8. Build to verify: `cd ts/packages/cli && pnpm build`
476 +9. Add recordings for the new command (see **Recording** below)
477 +
478 +If the build fails, check for: (1) missing service imports, (2) `Option<string>` being used where `string` is expected (use `Option.getOrUndefined` or `Option.match`), (3) the command not being exported from its file.
479 +
480 +## Recording
481 +
482 +New commands should have VHS recordings for documentation. Recordings produce SVGs and asciicasts that demonstrate the command in action.
483 +
484 +### Step 1: Add Entries to recordings.yaml
485 +
486 +Add recording entries to `ts/packages/cli/recordings/recordings.yaml` under the appropriate group:
487 +
488 +```yaml
489 +recordings:
490 + my-command:
491 + - name: help
492 + description: Show my-command help
493 + command: "composio my-command --help"
494 + height: dynamic # Use for commands whose output exceeds 750px
495 +
496 + - name: basic
497 + description: Run my-command with default options
498 + command: "composio my-command"
499 +```
500 +
501 +Each entry has:
502 +- `name` — filename for the recording (produces `<name>.svg`, `<name>.ascii`, `<name>.tape`)
503 +- `command` — the exact shell command to record
504 +- `description` — (optional) comment shown instantly above the command
505 +- `sleepAfterEnter` — (optional) override the default wait time after Enter (default: `6s`)
506 +- `height` — (optional) `'dynamic'` for auto-sizing via two-pass recording, or a fixed pixel number. Omit to use the default height (750px)
507 +
508 +Use `height: dynamic` for commands that produce long output (help text, full listings). Fixed height is fine for short-output commands (version, no-results, limited queries).
509 +
510 +### Step 2: Run the Recorder
511 +
512 +```bash
513 +cd ts/packages/cli
514 +bun scripts/record.ts
515 +```
516 +
517 +Requires `COMPOSIO_API_KEY` in the environment and `vhs` + `composio` on `PATH`.
518 +
519 +### Output Structure
520 +
521 +```
522 +recordings/
523 +├── recordings.yaml # Config
524 +├── tapes/<group>/<name>.tape # Generated VHS tape files (committed)
525 +├── svgs/<group>/<name>.svg # SVG recordings
526 +└── ascii/<group>/<name>.ascii # Asciicast recordings
527 +```
528 +
529 +## Reference Files
530 +
531 +| File | Purpose |
532 +|---|---|
533 +| `src/commands/version.cmd.ts` | Simplest command (no options, no services beyond TerminalUI) |
534 +| `src/commands/whoami.cmd.ts` | Data command with service dependency |
535 +| `src/commands/login.cmd.ts` | Complex command (options, spinner, polling, retry) |
536 +| `src/commands/logout.cmd.ts` | Action command (no stdout data) |
537 +| `src/commands/upgrade.cmd.ts` | Action command delegating to service |
538 +| `src/commands/generate/generate.cmd.ts` | Parent `generate` command and delegation entrypoint |
539 +| `src/commands/manage/manage.cmd.ts` | Parent `manage` command and subcommand registration |
540 +| `src/commands/ts/commands/ts.generate.cmd.ts` | Reusable TS generation logic used by `generate ts` |
541 +| `src/commands/index.ts` | Command tree registration |
542 +| `src/bin.ts` | Entry point, layer composition, error handling |
543 +| `src/services/terminal-ui.ts` | TerminalUI service interface |
544 +| `src/services/composio-clients.ts` | API client service (HTTP, pagination, metrics) |
545 +| `ts/packages/cli/AGENTS.md` | CLI architecture, services, effects, output conventions |
\ No newline at end of file
.agents/skills/test-sdk-in-realworld/SKILL.md new
+216
@@ -0,0 +1,216 @@
1 +# Testing Composio SDK in Real-World Scenarios
2 +
3 +Test the Composio SDK viability using ephemeral test projects. Never commit these tests.
4 +
5 +## Overview
6 +
7 +This skill helps validate SDK functionality by creating temporary test projects that:
8 +- Test both agentic (Tool Router) and non-agentic (Direct Tools) approaches
9 +- Use non-auth apps like HackerNews for quick validation
10 +- Identify bugs and quality issues in SDK or providers
11 +- Clean up automatically - never committed to repository
12 +
13 +## Testing Approach
14 +
15 +### 1. Create Ephemeral Test Project
16 +
17 +Always use the .agent_cache directory for tests:
18 +```bash
19 +# Create test directory in .agent_cache (gitignored)
20 +TEST_DIR=".agent_cache/sdk-test-$(date +%s)"
21 +mkdir -p "$TEST_DIR"
22 +cd "$TEST_DIR"
23 +
24 +# Initialize project
25 +npm init -y
26 +npm install @composio/core openai
27 +```
28 +
29 +### 2. Test Non-Agentic Providers (Direct Tools)
30 +
31 +Test simple tool execution without Tool Router:
32 +
33 +```typescript
34 +// test-direct-tools.ts
35 +import { Composio } from '@composio/core';
36 +import OpenAI from 'openai';
37 +
38 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
39 +const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
40 +
41 +async function testDirectTools() {
42 + // Get HackerNews tools (no auth required)
43 + const tools = await composio.tools.get('default', {
44 + toolkits: ['hackernews']
45 + });
46 +
47 + console.log(`✓ Got ${tools.length} HackerNews tools`);
48 +
49 + // Test with OpenAI
50 + const response = await openai.chat.completions.create({
51 + model: 'gpt-5.2',
52 + messages: [{ role: 'user', content: 'Get top 5 HackerNews stories' }],
53 + tools: tools,
54 + });
55 +
56 + // Handle tool calls
57 + if (response.choices[0].message.tool_calls) {
58 + const result = await composio.provider.handleToolCalls('default', response);
59 + console.log('✓ Tool execution successful');
60 + return result;
61 + }
62 +}
63 +
64 +testDirectTools().catch(console.error);
65 +```
66 +
67 +### 3. Test Agentic Providers (Tool Router)
68 +
69 +Test user-isolated sessions with Tool Router:
70 +
71 +```typescript
72 +// test-tool-router.ts
73 +import { Composio } from '@composio/core';
74 +import { VercelProvider } from '@composio/vercel';
75 +import { openai } from '@ai-sdk/openai';
76 +import { generateText } from 'ai';
77 +
78 +const composio = new Composio({
79 + apiKey: process.env.COMPOSIO_API_KEY,
80 + provider: new VercelProvider(),
81 +});
82 +
83 +async function testToolRouter() {
84 + // Create session for test user
85 + const session = await composio.create('test-user-001', {
86 + toolkits: ['hackernews'],
87 + manageConnections: false, // Non-auth app
88 + });
89 +
90 + console.log('✓ Created Tool Router session');
91 +
92 + const tools = await session.tools();
93 + console.log(`✓ Got ${Object.keys(tools).length} tools from session`);
94 +
95 + // Test with Vercel AI SDK
96 + const result = await generateText({
97 + model: openai('gpt-5.2'),
98 + prompt: 'Get the top 3 HackerNews stories',
99 + tools,
100 + maxSteps: 5,
101 + });
102 +
103 + console.log('✓ Tool Router execution successful');
104 + return result.text;
105 +}
106 +
107 +testToolRouter().catch(console.error);
108 +```
109 +
110 +### 4. Test MCP Integration
111 +
112 +Test MCP protocol compatibility:
113 +
114 +```typescript
115 +// test-mcp.ts
116 +import { Composio } from '@composio/core';
117 +
118 +const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
119 +
120 +async function testMCP() {
121 + const session = await composio.create('test-user-mcp', {
122 + toolkits: ['hackernews'],
123 + manageConnections: false,
124 + });
125 +
126 + console.log('✓ MCP Session created');
127 + console.log(' URL:', session.mcp.url);
128 + console.log(' Headers:', Object.keys(session.mcp.headers));
129 +
130 + // Test MCP endpoint accessibility
131 + const response = await fetch(session.mcp.url + '/tools', {
132 + headers: session.mcp.headers,
133 + });
134 +
135 + console.log('✓ MCP endpoint accessible:', response.ok);
136 + return response.ok;
137 +}
138 +
139 +testMCP().catch(console.error);
140 +```
141 +
142 +## Running Tests
143 +
144 +```bash
145 +# Run direct tools test
146 +npx tsx test-direct-tools.ts
147 +
148 +# Run Tool Router test
149 +npm install @composio/vercel ai @ai-sdk/openai
150 +npx tsx test-tool-router.ts
151 +
152 +# Run MCP test
153 +npx tsx test-mcp.ts
154 +
155 +# Clean up (always run after testing)
156 +cd .. && rm -rf "$TEST_DIR"
157 +```
158 +
159 +## What to Test
160 +
161 +1. **Installation**: Does `npm install @composio/core` work?
162 +2. **Type Safety**: Are TypeScript types correct?
163 +3. **Tool Discovery**: Can we fetch tools from toolkits?
164 +4. **Tool Execution**: Do tools execute successfully?
165 +5. **Error Handling**: Are errors informative?
166 +6. **Session Management**: Does Tool Router create sessions?
167 +7. **MCP Protocol**: Is MCP endpoint accessible?
168 +8. **Provider Integration**: Do provider packages work?
169 +
170 +## Reporting Issues
171 +
172 +When you find bugs or quality issues:
173 +
174 +1. **SDK Core Issues**: Report in GitHub Issues with:
175 + - Minimal reproduction code
176 + - Expected vs actual behavior
177 + - SDK version and environment
178 +
179 +2. **Provider Issues**: Note which provider package has issues
180 +
181 +3. **Documentation Issues**: Flag missing or incorrect docs
182 +
183 +## Best Practices
184 +
185 +- **Always use .agent_cache**: Never create tests in the main repository
186 +- **Use non-auth apps**: HackerNews, Public APIs for quick testing
187 +- **Test incrementally**: Start with simple tools, then complex workflows
188 +- **Clean up**: Always delete test directory after testing
189 +- **Check latest versions**: Use `npm view @composio/core version`
190 +
191 +## Available Environment Variables
192 +
193 +Assume these are available:
194 +```bash
195 +COMPOSIO_API_KEY # Composio API key
196 +OPENAI_API_KEY # OpenAI API key
197 +ANTHROPIC_API_KEY # Anthropic API key
198 +```
199 +
200 +## Quick Test Template
201 +
202 +```bash
203 +# One-liner to create and test
204 +TEST_DIR=".agent_cache/sdk-test-$(date +%s)" && \
205 +mkdir -p "$TEST_DIR" && cd "$TEST_DIR" && \
206 +npm init -y && npm install @composio/core openai && \
207 +echo "console.log('SDK Test Ready')" > test.ts && \
208 +npx tsx test.ts && \
209 +cd .. && rm -rf "$TEST_DIR"
210 +```
211 +
212 +## Next Steps
213 +
214 +1. Read `/building-agents` for comprehensive Tool Router documentation
215 +2. Check provider-specific skills for integration examples
216 +3. Report any bugs found during testing to the team
ts/packages/cli/skills/composio-cli/SKILL.md new
+118
@@ -0,0 +1,118 @@
1 +---
2 +name: composio-cli
3 +description: Help users operate the published Composio CLI to find the right tool, connect accounts, inspect schemas, execute tools, script workflows with `composio run`, and call authenticated app APIs with `composio proxy`. Use when the user asks how to do something with `composio`, wants to run a known tool slug, needs to discover a slug with `composio search`, fix a missing connection with `composio link`, inspect tool inputs with `--get-schema` or `--dry-run`, troubleshoot top-level CLI flows, or explicitly needs `composio dev` guidance.
4 +---
5 +
6 +# Composio CLI
7 +
8 +Use the shortest loop that gets the job done: `execute` first, `search` when the slug is unknown, `link` when a connection is missing, then retry `execute`.
9 +
10 +## Use The Default Workflow
11 +
12 +1. Start with `composio execute <slug>` whenever the slug is known.
13 +2. Let `execute` do the work. It already validates inputs and checks connection state.
14 +3. If `execute` says the toolkit is not connected, run `composio link <toolkit>` and retry.
15 +4. If the arguments are unclear, run `composio execute <slug> --get-schema` or `--dry-run` before guessing.
16 +5. Reach for `composio search "<task>"` only when the slug is unknown.
17 +
18 +## Treat Auth As A Footnote
19 +
20 +Use auth checks as quick preflight, not as the main workflow.
21 +
22 +```bash
23 +composio whoami
24 +```
25 +
26 +If `composio whoami` fails, run `composio login` and then move straight back to `execute`.
27 +
28 +## Use `execute` First
29 +
30 +Run a known slug:
31 +
32 +```bash
33 +composio execute GITHUB_GET_THE_AUTHENTICATED_USER -d '{}'
34 +```
35 +
36 +Inspect required inputs without executing:
37 +
38 +```bash
39 +composio execute GITHUB_CREATE_AN_ISSUE --get-schema
40 +```
41 +
42 +Preview safely:
43 +
44 +```bash
45 +composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'
46 +```
47 +
48 +Pass data from a file or stdin:
49 +
50 +```bash
51 +composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d @issue.json
52 +cat issue.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d -
53 +```
54 +
55 +Recover from missing connections:
56 +
57 +```bash
58 +composio execute GMAIL_FETCH_EMAILS -d '{ max_results: 1 }'
59 +composio link gmail --no-browser
60 +```
61 +
62 +After the auth flow completes, rerun the original `execute` command.
63 +
64 +Prefer `composio tools info` and `composio tools list` only when `search`, `--get-schema`, or the error message still leave the user stuck.
65 +
66 +## Use `search` To Find The Slug
67 +
68 +When the user knows the task but not the tool name, search first and then execute the best match.
69 +
70 +```bash
71 +composio search "create a github issue"
72 +composio search "send an email" --toolkits gmail
73 +```
74 +
75 +Read the returned slugs, choose the best match, and immediately move back to `execute`.
76 +
77 +## Use `link` Only To Unblock `execute`
78 +
79 +Use `link` when `execute` reports that the toolkit is not connected, or when the user explicitly wants to authorize an account.
80 +
81 +```bash
82 +composio link gmail
83 +composio link googlecalendar --no-browser
84 +```
85 +
86 +After linking, retry the original `execute` command instead of changing strategies.
87 +
88 +## Use Power Tools Deliberately
89 +
90 +Use `composio run` when one tool call is not enough and the user needs chaining, batching, lightweight automation, or sub-agent orchestration.
91 +
92 +```bash
93 +composio run '
94 + const [me, emails] = await Promise.all([
95 + execute("GITHUB_GET_THE_AUTHENTICATED_USER"),
96 + execute("GMAIL_FETCH_EMAILS", { max_results: 1 }),
97 + ]);
98 +
99 + console.log({
100 + login: me.data.login,
101 + fetchedEmails: !!emails.data,
102 + });
103 +'
104 +```
105 +
106 +Use `composio proxy` when the toolkit supports a raw API operation that is easier than finding a dedicated tool.
107 +
108 +```bash
109 +composio proxy https://api.github.com/user --toolkit github --method GET </dev/null
110 +```
111 +
112 +For richer `run`, `subAgent()`, `result.prompt()`, `Promise.all`, and mixed `execute()` plus `proxy()` patterns, load [references/power-user-examples.md](references/power-user-examples.md).
113 +
114 +## Escalate Only When Needed
115 +
116 +If the user is stuck on top-level commands or needs fallback inspection commands, load [references/troubleshooting.md](references/troubleshooting.md).
117 +
118 +If the user explicitly asks about developer projects, auth configs, connected accounts, triggers, logs, orgs, or projects, load [references/composio-dev.md](references/composio-dev.md). `composio dev` is not the default end-user path.
ts/packages/cli/skills/composio-cli/agents/openai.yaml new
+4
@@ -0,0 +1,4 @@
1 +interface:
2 + display_name: "Composio CLI"
3 + short_description: "Execute-first help for the Composio CLI"
4 + default_prompt: "Use $composio-cli to find the right Composio CLI command and run it safely."
ts/packages/cli/skills/composio-cli/references/composio-dev.md new
+71
@@ -0,0 +1,71 @@
1 +# Composio Dev
2 +
3 +Load this file only when the user explicitly needs developer-project workflows. Do not lead with `composio dev` for ordinary top-level CLI usage.
4 +
5 +## Use `dev init` To Bind A Directory
6 +
7 +Use `composio dev init` when the user wants to attach the current directory to a developer project.
8 +
9 +```bash
10 +composio dev init -y --no-browser
11 +```
12 +
13 +If later commands complain about missing developer project context, come back to `dev init`.
14 +
15 +## Inspect Toolkits And Versions
16 +
17 +Use toolkit commands to inspect developer-scoped capabilities:
18 +
19 +```bash
20 +composio dev toolkits list
21 +composio dev toolkits info github
22 +composio dev toolkits search "email"
23 +composio dev toolkits version github
24 +```
25 +
26 +## Manage Auth Configs
27 +
28 +Use auth-config commands when the user is configuring developer-project authentication behavior:
29 +
30 +```bash
31 +composio dev auth-configs list
32 +```
33 +
34 +## Manage Connected Accounts
35 +
36 +Use developer connected-account commands when the user is working with developer-project users or auth-config-specific flows.
37 +
38 +```bash
39 +composio dev connected-accounts list
40 +```
41 +
42 +Top-level `composio link` is consumer-only. Use `dev connected-accounts link` for developer-project flows.
43 +
44 +## Work With Triggers
45 +
46 +Use trigger commands when the user is creating, inspecting, or listening to developer-project triggers.
47 +
48 +```bash
49 +composio dev triggers list
50 +composio dev triggers info AGENT_MAIL_NEW_EMAIL_TRIGGER
51 +```
52 +
53 +## Inspect Logs
54 +
55 +Use logs when the user is debugging tool executions or trigger deliveries inside a developer project.
56 +
57 +```bash
58 +composio dev logs tools
59 +composio dev logs triggers
60 +```
61 +
62 +## Switch Or Inspect Org And Project Context
63 +
64 +Use these commands when the user needs to confirm or change the active developer scope:
65 +
66 +```bash
67 +composio dev orgs list
68 +composio dev projects list
69 +```
70 +
71 +If the user only wants to connect and execute tools as an end user, return to the top-level workflow instead of staying in `composio dev`.
ts/packages/cli/skills/composio-cli/references/power-user-examples.md new
+125
@@ -0,0 +1,125 @@
1 +# Power-User Examples
2 +
3 +Load this file when the user needs more than one top-level command, wants to script workflows, or wants to use `subAgent()` inside `composio run`.
4 +
5 +## Use `run` To Chain Tool Calls
6 +
7 +Fetch from multiple connected tools in one script:
8 +
9 +```bash
10 +composio run '
11 + const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
12 + const emails = await execute("GMAIL_FETCH_EMAILS", {
13 + max_results: 2,
14 + });
15 +
16 + console.log({
17 + login: me.data.login,
18 + emailCount: Array.isArray(emails.data?.messages) ? emails.data.messages.length : null,
19 + });
20 +'
21 +```
22 +
23 +## Use `Promise.all` To Fan Out
24 +
25 +Fetch from multiple services at once:
26 +
27 +```bash
28 +composio run '
29 + const [me, emails] = await Promise.all([
30 + execute("GITHUB_GET_THE_AUTHENTICATED_USER"),
31 + execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),
32 + ]);
33 +
34 + console.log({
35 + login: me.data.login,
36 + emailCount: emails.data.messages?.length ?? null,
37 + });
38 +'
39 +```
40 +
41 +## Use `search()` Before `execute()` Inside A Script
42 +
43 +Discover a candidate slug, then execute it:
44 +
45 +```bash
46 +composio run '
47 + const results = await search("get the authenticated github user", {
48 + toolkits: "github",
49 + limit: 1,
50 + });
51 +
52 + const slug = results.results?.[0]?.primary_tool_slugs?.[0];
53 + if (!slug) throw new Error("No candidate tool found.");
54 +
55 + const output = await execute(slug);
56 +
57 + console.log(output.data.login);
58 +'
59 +```
60 +
61 +## Use `subAgent()` With `z` And `result.prompt()`
62 +
63 +Turn a tool result into structured output:
64 +
65 +```bash
66 +composio run --logs-off '
67 + const emails = await execute("GMAIL_FETCH_EMAILS", { max_results: 2 });
68 +
69 + const brief = await subAgent(
70 + `Return only valid JSON matching the schema. Summarize these emails in one sentence and report how many items were returned.\n\n${emails.prompt()}`,
71 + {
72 + schema: z.object({
73 + summary: z.string(),
74 + count: z.number(),
75 + }),
76 + }
77 + );
78 +
79 + console.log(brief.structuredOutput);
80 +'
81 +```
82 +
83 +Use `result.prompt()` when the helper result is too noisy for a raw object dump but you still want to feed it into `subAgent()`.
84 +
85 +## Use `proxy()` For Raw API Access
86 +
87 +`proxy(toolkit)` returns a fetch-compatible function bound to the connected account. Name it like `fetch` if that keeps the script clearer. It returns a real `Response`, so call `.json()` or `.text()`.
88 +
89 +```bash
90 +composio run '
91 + const fetch = await proxy("github");
92 + const profile = await (await fetch("https://api.github.com/user")).json();
93 + console.log(profile);
94 +'
95 +```
96 +
97 +## Mix `execute()` And `proxy()`
98 +
99 +Use dedicated tools where they exist, then drop down to raw API calls for the missing step:
100 +
101 +```bash
102 +composio run '
103 + const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER");
104 +
105 + const fetch = await proxy("github");
106 + const repos = await (await fetch("https://api.github.com/user/repos?per_page=3")).json();
107 +
108 + console.log({
109 + login: me.data.login,
110 + repoCount: Array.isArray(repos) ? repos.length : null,
111 + });
112 +'
113 +```
114 +
115 +## Use `run` Flags Intentionally
116 +
117 +- Use `--dry-run` to preview every `execute()` call in the script.
118 +- Use `--debug` to see helper steps while the script runs.
119 +- Use `--logs-off` when `subAgent()` streaming logs are too noisy for the task.
120 +
121 +Example:
122 +
123 +```bash
124 +composio run --dry-run --debug 'await execute("GITHUB_CREATE_AN_ISSUE", { owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." })'
125 +```
ts/packages/cli/skills/composio-cli/references/troubleshooting.md new
+110
@@ -0,0 +1,110 @@
1 +# Troubleshooting
2 +
3 +Load this file when the user is stuck on top-level Composio CLI flows.
4 +
5 +## Not Logged In
6 +
7 +Symptoms:
8 +
9 +- `composio` commands fail because there is no user session
10 +- the user is unsure which account the CLI is using
11 +
12 +Fix:
13 +
14 +```bash
15 +composio whoami
16 +```
17 +
18 +If `composio whoami` fails, run `composio login` and then return to the original `execute` or `search` flow.
19 +
20 +## No Active Connection Found
21 +
22 +Symptoms:
23 +
24 +- `execute` reports that no active connection exists for a toolkit
25 +
26 +Fix:
27 +
28 +```bash
29 +composio link gmail --no-browser --no-wait
30 +composio link googlecalendar --no-browser --no-wait
31 +```
32 +
33 +After linking, retry the exact same `execute` command.
34 +
35 +## Invalid JSON Input
36 +
37 +Symptoms:
38 +
39 +- `execute` rejects `-d` input
40 +- the payload is not valid JSON or JS-style object syntax
41 +
42 +Fix:
43 +
44 +- Pass JSON or a JS-style object literal to `-d`
45 +- Use `@file` for large payloads
46 +- Use `-` to read from stdin
47 +
48 +Examples:
49 +
50 +```bash
51 +composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{"owner":"acme","repo":"app","title":"Bug report","body":"Steps to reproduce..."}'
52 +composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'
53 +composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d @payload.json
54 +cat payload.json | composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d -
55 +```
56 +
57 +## Unknown Or Wrong Slug
58 +
59 +Symptoms:
60 +
61 +- the user does not know the tool slug
62 +- the slug exists but is not the right tool for the job
63 +
64 +Fix:
65 +
66 +```bash
67 +composio search "create a github issue"
68 +composio search "send an email" --toolkits gmail
69 +```
70 +
71 +Use `composio tools list <toolkit>` only when the user already knows the toolkit and needs to browse the available slugs manually.
72 +
73 +## Confusion About Required Inputs
74 +
75 +Symptoms:
76 +
77 +- the user is unsure what fields a tool accepts
78 +- the first payload attempt failed validation
79 +
80 +Fix:
81 +
82 +```bash
83 +composio execute GITHUB_CREATE_AN_ISSUE --get-schema -d '{}'
84 +composio execute GITHUB_CREATE_AN_ISSUE --skip-connection-check --dry-run -d '{ owner: "acme", repo: "app", title: "Bug report", body: "Steps to reproduce..." }'
85 +```
86 +
87 +Use `composio tools info <slug>` only when the user wants a compact summary of a known slug and the `execute --get-schema` output is still not enough.
88 +
89 +## `tools info` And `tools list` Are Fallbacks
90 +
91 +Treat these commands as secondary inspection tools:
92 +
93 +```bash
94 +composio tools info GMAIL_SEND_EMAIL
95 +composio tools list gmail
96 +```
97 +
98 +Do not lead with them when `execute`, `search`, `--get-schema`, or `--dry-run` can get the user unstuck faster.
99 +
100 +## Consumer Vs `composio dev`
101 +
102 +Use the top-level commands for normal end-user flows:
103 +
104 +- `composio execute`
105 +- `composio search`
106 +- `composio link`
107 +- `composio run`
108 +- `composio proxy`
109 +
110 +Load [composio-dev.md](composio-dev.md) only when the user explicitly needs developer projects, auth configs, connected accounts, triggers, logs, orgs, or projects.