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

next
py 78 lines 2.51 KB
Raw
1 """
2 Tool Router - MCP (Model Context Protocol) Example with OpenAI Agents
3
4 This example demonstrates how to use Tool Router with MCP servers and OpenAI Agents provider.
5 The MCP server provides a standardized way to access tools across different platforms,
6 and OpenAI Agents provider allows you to use these tools with OpenAI's agent framework.
7 """
8
9 import asyncio
10 import os
11
12 from agents import Agent, HostedMCPTool, Runner
13 from composio_openai_agents import OpenAIAgentsProvider
14
15 from composio import Composio
16
17
18 def require_env(name: str) -> str:
19 value = os.environ.get(name)
20 if not value:
21 raise RuntimeError(f"Set {name} before running this example.")
22 return value
23
24
25 async def main():
26 # Initialize Composio with OpenAI Agents provider
27 composio = Composio(
28 api_key=require_env("COMPOSIO_API_KEY"), provider=OpenAIAgentsProvider()
29 )
30
31 # Create a tool router session
32 session = composio.create(
33 # A user with connected GitHub and Gmail accounts (raises KeyError when unset)
34 user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
35 toolkits=["github", "gmail"],
36 # mcp=True surfaces session.mcp on the returned type
37 mcp=True,
38 )
39
40 mcpTool = HostedMCPTool(
41 tool_config={
42 "type": "mcp",
43 "server_label": "tool_router",
44 "server_url": session.mcp.url,
45 "require_approval": "never",
46 "headers": session.mcp.headers, # type: ignore[typeddict-item] # headers is typed Dict[str, Optional[str]]; the SDK always populates it with str values
47 }
48 )
49
50 print(f"Session created: {session.session_id}")
51 print(f"MCP Server URL: {session.mcp.url}")
52 print(f"MCP Server Type: {session.mcp.type}")
53
54 # Create an agent with the tools from tool router
55 agent = Agent(
56 name="MCP Tool Router Agent",
57 instructions=(
58 "You are a helpful assistant that can use GitHub and Gmail tools "
59 "through the MCP (Model Context Protocol) server. "
60 "Help users with their GitHub and email tasks."
61 ),
62 tools=[mcpTool],
63 )
64
65 # Run the agent with a sample task
66 print("\n--- Running Agent with Tool Router Tools ---")
67 result = await Runner.run(
68 starting_agent=agent,
69 input=(
70 "List my recent GitHub repositories and tell me about them. "
71 "If successful, respond with a summary of what you found."
72 ),
73 )
74 print(f"\nAgent Result: {result.final_output}")
75
76
77 if __name__ == "__main__":
78 asyncio.run(main())