Skip to content

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

docs(openai-agents): Complete page restructure with MCP code

Sushmithamallesh993a7c385780
diff --git a/docs/content/docs/providers/openai-agents.mdx b/docs/content/docs/providers/openai-agents.mdx
index ccfbde195..175a38a5a 100644
--- a/docs/content/docs/providers/openai-agents.mdx
+++ b/docs/content/docs/providers/openai-agents.mdx
@@ -9,7 +9,7 @@ keywords: [agents sdk]
<ToolTypeOption id="native" name="Native Tools" icon="native">
<Steps>
<Step>
-### Install
+**Install**
<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
<Tab value="Python">
@@ -26,7 +26,7 @@ npm install dotenv @composio/core @composio/openai-agents @openai/agents
</Step>
<Step>
-### Configure API Keys
+**Configure API Keys**
<Callout type="info">
Set `COMPOSIO_API_KEY` with your API key from [Settings](https://platform.composio.dev/?next_page=/settings) and `OPENAI_API_KEY` with your [OpenAI API key](https://platform.openai.com/api-keys).
@@ -39,7 +39,7 @@ OPENAI_API_KEY=xxxxxxxxx
</Step>
<Step>
-### Create session and run agent
+**Create session and run agent**
<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
<Tab value="Python">
@@ -131,7 +131,7 @@ if (result.finalOutput) {
<ToolTypeOption id="mcp" name="MCP" icon="mcp">
<Steps>
<Step>
-### Install
+**Install**
<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
<Tab value="Python">
@@ -141,14 +141,14 @@ pip install composio openai-agents
</Tab>
<Tab value="TypeScript">
```bash
-npm install @composio/core @openai/agents
+npm install dotenv @composio/core @openai/agents
```
</Tab>
</Tabs>
</Step>
<Step>
-### Configure API Keys
+**Configure API Keys**
<Callout type="info">
Set `COMPOSIO_API_KEY` with your API key from [Settings](https://platform.composio.dev/?next_page=/settings) and `OPENAI_API_KEY` with your [OpenAI API key](https://platform.openai.com/api-keys).
@@ -161,392 +161,258 @@ OPENAI_API_KEY=xxxxxxxxx
</Step>
<Step>
-### Create session and run agent
-
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
-<Tab value="Python">
-```python
-# TODO: MCP Python code
-```
-</Tab>
-<Tab value="TypeScript">
-```typescript
-// TODO: MCP TypeScript code
-```
-</Tab>
-</Tabs>
-</Step>
-</Steps>
-</ToolTypeOption>
-
-</ToolTypeFlow>
-
-<Accordions>
-<Accordion title="Direct tool usage">
-TODO: Direct tool usage content
-</Accordion>
-
-<Accordion title="Direct MCP usage">
-TODO: Direct MCP usage content
-</Accordion>
-</Accordions>
-
----
-
-## Old Content (to be removed)
-
-The OpenAI Agents Provider is a provider that formats the Composio tools into an object compatible with OpenAI's Agents API.
-
-OpenAI Agents SDK is different from the OpenAI SDK. It helps build agentic AI apps in a lightweight, easy-to-use package with very few abstractions.
-
-## Usage with Tools
-
-Use Composio Tool Router as a native tool with the OpenAI Agents SDK.
-
-### Installation
-
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
-<Tab value="Python">
-```bash
-pip install python-dotenv composio composio-openai-agents openai-agents
-```
-</Tab>
-<Tab value="TypeScript">
-```bash
-npm install @composio/core @composio/openai-agents @openai/agents
-```
-</Tab>
-</Tabs>
-
-### Usage
-
-Create a Tool Router session and use it as a native tool with OpenAI Agents SDK:
-
-<Callout type="info">
-- Set `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
-- Set `OPENAI_API_KEY` environment variable with your [OpenAI API key](https://platform.openai.com/api-keys).
-</Callout>
+**Create session and run agent**
<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
<Tab value="Python">
```python
+import asyncio
from dotenv import load_dotenv
+load_dotenv()
+
from composio import Composio
-from agents import Agent, Runner, SQLiteSession
-from composio_openai_agents import OpenAIAgentsProvider
+from agents import Agent, Runner, HostedMCPTool
-load_dotenv()
+# Initialize Composio
+composio = Composio()
-# Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
-composio = Composio(provider=OpenAIAgentsProvider())
+external_user_id = "user_2nFh83Hde"
+recipient_email = "[email protected]"
-# Unique identifier of the user
-user_id = "user_123"
+# Create a session
+session = composio.create(user_id=external_user_id)
-# Create a session and get native tools for the user
-session = composio.create(user_id=user_id)
-tools = session.tools()
+# Create MCP tool
+composio_mcp = HostedMCPTool(
+ tool_config={
+ "type": "mcp",
+ "server_label": "composio",
+ "server_url": session.mcp.url,
+ "require_approval": "never",
+ "headers": session.mcp.headers,
+ }
+)
-# Configure OpenAI agent with Composio tools
+# Create agent with MCP tool
agent = Agent(
- name="Personal Assistant",
- instructions="You are a helpful personal assistant. Use Composio tools to take action.",
- model="gpt-5.2",
- tools=tools,
+ name="Email Manager",
+ instructions="You are a helpful assistant.",
+ tools=[composio_mcp],
)
-# Memory for multi-turn conversation
-memory = SQLiteSession("conversation")
-
-# Execute an initial task
-print("Fetching GitHub issues from the Composio repository...\n")
-try:
- result = Runner.run_sync(
+# Run the agent
+async def main():
+ result = await Runner.run(
starting_agent=agent,
- input="Fetch all the open GitHub issues on the @ComposioHQ/composio repository and group them by bugs/features/docs.",
- session=memory,
+ input=f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'",
)
- print(f"{result.final_output}\n")
-except Exception as e:
- print(f"[Error]: {e}")
-
-# Continue with interactive conversation
-print("\nWhat else would you like me to do? (Type 'exit' to exit)")
-
-while True:
- user_input = input("You: ").strip()
- if user_input.lower() == "exit":
- break
-
- print("Assistant: ", end="", flush=True)
- try:
- result = Runner.run_sync(starting_agent=agent, input=user_input, session=memory)
- print(f"{result.final_output}\n")
- except Exception as e:
- print(f"\n[Error]: {e}")
+ print(result.final_output)
+
+asyncio.run(main())
```
</Tab>
<Tab value="TypeScript">
```typescript
import "dotenv/config";
import { Composio } from "@composio/core";
-import { Agent, run, MemorySession } from "@openai/agents";
-import { OpenAIAgentsProvider } from "@composio/openai-agents";
-import { createInterface } from "readline/promises";
+import { Agent, run, hostedMcpTool } from "@openai/agents";
-// Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
-const composio = new Composio({ provider: new OpenAIAgentsProvider() });
+// Initialize Composio
+const composio = new Composio();
-// Unique identifier of the user
-const userId = "user_123";
+const externalUserId = "user_2nFh83Hde";
+const recipientEmail = "[email protected]";
-// Create a session and get native tools for the user
-const session = await composio.create(userId);
-const tools = await session.tools();
+// Create a session
+const session = await composio.create(externalUserId);
+// Create agent with MCP tool
const agent = new Agent({
- name: "Personal Assistant",
- instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
- model: "gpt-5.2",
- tools,
+ name: "Email Manager",
+ instructions: "You are a helpful assistant.",
+ tools: [
+ hostedMcpTool({
+ serverLabel: "composio",
+ serverUrl: session.mcp.url,
+ headers: session.mcp.headers,
+ }),
+ ],
});
-// Create a memory session for persistent multi-turn conversation
-const memory = new MemorySession();
-
-// Execute an initial task
-console.log("Fetching GitHub issues from the Composio repository...\n");
-try {
- const initialResult = await run(
- agent,
- "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
- { session: memory }
- );
- console.log(`${initialResult.finalOutput}\n`);
-} catch (error) {
- console.error("[Error]:", error instanceof Error ? error.message : error);
-}
-
-// Continue with interactive conversation
-const readline = createInterface({ input: process.stdin, output: process.stdout });
-
-console.log(`
-What else would you like me to do?
-(Type 'exit' to exit)
-`);
-
-
-while (true) {
- const input = (await readline.question("You: ")).trim();
- if (input.toLowerCase() === "exit") break;
-
- console.log("Assistant: ");
+// Run the agent
+console.log("Running agent...");
+const result = await run(
+ agent,
+ `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'`
+);
- try {
- const result = await run(agent, input, { session: memory });
- console.log(`${result.finalOutput}\n`);
- } catch (error) {
- console.error("\n[Error]:", error instanceof Error ? error.message : error);
- }
+console.log("Received response from agent");
+if (result.finalOutput) {
+ console.log(result.finalOutput);
}
-readline.close();
```
</Tab>
</Tabs>
+</Step>
+</Steps>
+</ToolTypeOption>
-## Usage with MCP
+</ToolTypeFlow>
-Use Composio Tool Router with the OpenAI Agents SDK for a fully managed MCP experience.
+<Accordions>
+<Accordion title="Direct tool usage">
+<Callout type="info">
+Only use this if you want to use a single, direct tool with your AI Agent.
+</Callout>
-### Installation
+**Install**
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
+<Tabs items={["Python", "TypeScript"]}>
<Tab value="Python">
```bash
-pip install python-dotenv composio openai-agents
+pip install composio openai-agents composio-openai-agents
```
</Tab>
<Tab value="TypeScript">
```bash
-npm install dotenv @composio/core @openai/agents zod@3
+npm install @composio/core @openai/agents @composio/openai-agents
```
</Tab>
</Tabs>
-### Usage
-
-Create a Tool Router session and execute tasks with OpenAI agents:
+**Usage**
-<Callout type="info">
-- Set `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
-- Set `OPENAI_API_KEY` environment variable with your [OpenAI API key](https://platform.openai.com/api-keys).
-</Callout>
-
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
+<Tabs items={["Python", "TypeScript"]}>
<Tab value="Python">
```python
-from dotenv import load_dotenv
+import asyncio
from composio import Composio
-from agents import Agent, Runner, HostedMCPTool
+from agents import Agent, Runner
+from composio_openai_agents import OpenAIAgentsProvider
-load_dotenv()
+composio = Composio(provider=OpenAIAgentsProvider())
-# Initialize Composio (API key from env var COMPOSIO_API_KEY)
-composio = Composio()
-# Unique identifier of the user
-user_id = "user_123"
+external_user_id = "user_2nFh83Hde"
+recipient_email = "[email protected]"
-# Create a Tool Router session for the user
-session = composio.create(user_id=user_id)
+# Get a specific tool
+tools = composio.tools.get(user_id=external_user_id, tools=["GMAIL_SEND_EMAIL"])
-# Configure OpenAI agent with Composio MCP server
agent = Agent(
- name="Personal Assistant",
- instructions="You are a helpful personal assistant. Use Composio tools to take action.",
- model="gpt-5.2",
- tools=[
- HostedMCPTool(
- tool_config={
- "type": "mcp",
- "server_label": "composio",
- "server_url": session.mcp.url,
- "require_approval": "never",
- "headers": session.mcp.headers,
- }
- )
- ],
+ name="Email Manager",
+ instructions="You are a helpful assistant.",
+ tools=tools,
)
-# Execute the task
-print("Fetching GitHub issues from the Composio repository @ComposioHQ/composio...\n")
-try:
- result = Runner.run_sync(
+async def main():
+ result = await Runner.run(
starting_agent=agent,
- input="Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
+ input=f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'",
)
print(result.final_output)
-except Exception as e:
- print(f"[Error]: {e}")
-print("\n\n---")
-print("Tip: If prompted to authenticate, complete the auth flow and run again.")
+asyncio.run(main())
```
</Tab>
<Tab value="TypeScript">
```typescript
-import "dotenv/config";
import { Composio } from "@composio/core";
-import { Agent, hostedMcpTool, run, MemorySession } from "@openai/agents";
-import { createInterface } from "readline/promises";
+import { Agent, run } from "@openai/agents";
+import { OpenAIAgentsProvider } from "@composio/openai-agents";
-// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
-const composio = new Composio();
+const composio = new Composio({
+ provider: new OpenAIAgentsProvider(),
+});
-// Unique identifier of the user
-const userId = "user_123";
+const externalUserId = "user_2nFh83Hde";
+const recipientEmail = "[email protected]";
-// Create a tool router session for the user
-const session = await composio.create(userId);
+// Get a specific tool
+const tools = await composio.tools.get(externalUserId, {
+ tools: ["GMAIL_SEND_EMAIL"],
+});
const agent = new Agent({
- name: "Personal Assistant",
- instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
- model: "gpt-5.2",
- tools: [
- hostedMcpTool({
- serverLabel: "composio",
- serverUrl: session.mcp.url,
- headers: session.mcp.headers, // Authentication headers for the Composio MCP server
- }),
- ],
+ name: "Email Manager",
+ instructions: "You are a helpful assistant.",
+ tools: tools,
});
-// Create a memory session for persistent multi-turn conversation
-const memory = new MemorySession();
-
-// Execute an initial task
-console.log("Fetching GitHub issues from the Composio repository...\n");
-try {
- const initialResult = await run(
- agent,
- "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
- { session: memory }
- );
- console.log(`${initialResult.finalOutput}\n`);
-} catch (error) {
- console.error("[Error]:", error instanceof Error ? error.message : error);
-}
-
-// Continue with interactive conversation
-const readline = createInterface({ input: process.stdin, output: process.stdout });
-
-console.log(`
-What else would you like me to do?
-(Type 'exit' to exit)
-`);
-
-while (true) {
- const input = (await readline.question("You: ")).trim();
- if (input.toLowerCase() === "exit") break;
-
- console.log("Assistant: ");
+console.log("Running agent...");
+const result = await run(
+ agent,
+ `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'`
+);
- try {
- const result = await run(agent, input, { session: memory });
- console.log(`${result.finalOutput}\n`);
- } catch (error) {
- console.error("\n[Error]:", error instanceof Error ? error.message : error);
- }
+console.log("Received response from agent");
+if (result.finalOutput) {
+ console.log(result.finalOutput);
}
-readline.close();
```
</Tab>
</Tabs>
+</Accordion>
-## Usage with direct tools
+<Accordion title="Direct MCP usage">
+<Callout type="info">
+Only use this if you want to use Composio's MCP server directly without the session abstraction.
+</Callout>
-### Setup
+**Install**
<Tabs items={["Python", "TypeScript"]}>
<Tab value="Python">
```bash
-pip install composio openai-agents composio-openai-agents
+pip install composio openai-agents
```
</Tab>
<Tab value="TypeScript">
```bash
-npm install @composio/core @openai/agents @composio/openai-agents
+npm install dotenv @composio/core @openai/agents
```
</Tab>
</Tabs>
-### Usage
+**Usage**
<Tabs items={["Python", "TypeScript"]}>
<Tab value="Python">
```python
import asyncio
+from dotenv import load_dotenv
+load_dotenv()
+
from composio import Composio
-from agents import Agent, Runner
-from composio_openai_agents import OpenAIAgentsProvider
+from agents import Agent, Runner, HostedMCPTool
-composio = Composio(api_key="your-api-key", provider=OpenAIAgentsProvider())
+composio = Composio()
-# Create a connected account for the user for the gmail toolkit and replace with your own user id
-externalUserId = "your-user-id"
+external_user_id = "user_2nFh83Hde"
+recipient_email = "[email protected]"
-# Get Gmail tools that are pre-configured
-tools = composio.tools.get(user_id=externalUserId, tools=["GMAIL_SEND_EMAIL"])
+# Get MCP URL directly
+mcp = composio.mcp.get(user_id=external_user_id)
agent = Agent(
- name="Email Manager", instructions="You are a helpful assistant", tools=tools
+ name="Email Manager",
+ instructions="You are a helpful assistant.",
+ tools=[
+ HostedMCPTool(
+ tool_config={
+ "type": "mcp",
+ "server_label": "composio",
+ "server_url": mcp.url,
+ "require_approval": "never",
+ "headers": mcp.headers,
+ }
+ )
+ ],
)
-# Run the agent
async def main():
result = await Runner.run(
starting_agent=agent,
- input="Send an email to [email protected] with the subject 'Hello from composio' and the body 'Congratulations on sending your first email using AI Agents and Composio!'",
+ input=f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'",
)
print(result.final_output)
@@ -555,39 +421,42 @@ asyncio.run(main())
</Tab>
<Tab value="TypeScript">
```typescript
+import "dotenv/config";
import { Composio } from "@composio/core";
-import { Agent, run } from "@openai/agents";
-import { OpenAIAgentsProvider } from "@composio/openai-agents";
+import { Agent, run, hostedMcpTool } from "@openai/agents";
-// add OPENAI_API_KEY in your .env file
-const composio = new Composio({
- apiKey: "your-api-key",
- provider: new OpenAIAgentsProvider(),
-});
+const composio = new Composio();
-// Create a connected account for the user for the gmail toolkit and replace with your own user id
-const externalUserId = "your-user-id";
+const externalUserId = "user_2nFh83Hde";
+const recipientEmail = "[email protected]";
-// Fetch tools for GMAIL toolkit on behalf of the user
-const tools = await composio.tools.get(externalUserId, {
- tools: ["GMAIL_SEND_EMAIL"],
- });
+// Get MCP URL directly
+const mcp = await composio.mcp.get(externalUserId);
const agent = new Agent({
- name: "Email Manager",
- tools: tools,
+ name: "Email Manager",
+ instructions: "You are a helpful assistant.",
+ tools: [
+ hostedMcpTool({
+ serverLabel: "composio",
+ serverUrl: mcp.url,
+ headers: mcp.headers,
+ }),
+ ],
});
-console.log(`Running agent...`);
+console.log("Running agent...");
const result = await run(
- agent,
- "Send an email to [email protected] with the subject 'Hello from composio' and the body 'Congratulations on sending your first email using AI Agents and Composio!'"
+ agent,
+ `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'`
);
-console.log(`Received response from agent`);
+console.log("Received response from agent");
if (result.finalOutput) {
- console.log(JSON.stringify(result.finalOutput, null, 2));
+ console.log(result.finalOutput);
}
```
</Tab>
</Tabs>
+</Accordion>
+</Accordions>