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 195 lines 6.03 KB
Raw
1 """
2 Claude Agent SDK Provider for Composio
3
4 This provider enables integration with Claude Agent SDK,
5 allowing Composio tools to be used as MCP tools within Claude agents.
6 """
7
8 import asyncio
9 import json
10 import typing as t
11
12 from claude_agent_sdk import (
13 McpSdkServerConfig,
14 SdkMcpTool,
15 create_sdk_mcp_server,
16 )
17 from claude_agent_sdk import (
18 tool as sdk_tool,
19 )
20
21 from composio.core.provider import AgenticProvider
22 from composio.core.provider.agentic import AgenticProviderExecuteFn
23 from composio.types import Tool
24 from composio.utils.shared import alias_tool_input_schema, normalize_tool_arguments
25
26
27 class ClaudeAgentSDKProvider(
28 AgenticProvider[SdkMcpTool, list[SdkMcpTool]],
29 name="claude_agent_sdk",
30 ):
31 """
32 Composio provider for Claude Agent SDK.
33
34 This provider wraps Composio tools as MCP tools that can be used with
35 the Claude Agent SDK's `query()` function via the `mcp_servers` option.
36
37 Example:
38 ```python
39 import asyncio
40 from composio import Composio
41 from composio_claude_agent_sdk import ClaudeAgentSDKProvider
42 from claude_agent_sdk import query, ClaudeAgentOptions
43
44 composio = Composio(provider=ClaudeAgentSDKProvider())
45
46 async def main():
47 tools = composio.tools.get(user_id="default", toolkits=["gmail"])
48 mcp_server = composio.provider.create_mcp_server(tools)
49
50 async for message in query(
51 prompt="Fetch my latest email",
52 options=ClaudeAgentOptions(
53 mcp_servers={"composio": mcp_server},
54 permission_mode="bypassPermissions",
55 ),
56 ):
57 print(message)
58
59 asyncio.run(main())
60 ```
61 """
62
63 def __init__(
64 self,
65 server_name: str = "composio",
66 server_version: str = "1.0.0",
67 ) -> None:
68 """
69 Initialize the Claude Agent SDK provider.
70
71 Args:
72 server_name: Name for the MCP server (default: "composio")
73 server_version: Version for the MCP server (default: "1.0.0")
74 """
75 super().__init__()
76 self.server_name = server_name
77 self.server_version = server_version
78
79 def wrap_tool(
80 self,
81 tool: Tool,
82 execute_tool: AgenticProviderExecuteFn,
83 ) -> SdkMcpTool:
84 """
85 Wrap a Composio tool as a Claude Agent SDK MCP tool.
86
87 Args:
88 tool: The Composio tool to wrap
89 execute_tool: Function to execute the tool
90
91 Returns:
92 A Claude Agent SDK MCP tool definition
93 """
94 aliases = alias_tool_input_schema(tool.input_parameters or {})
95
96 @sdk_tool(
97 tool.slug,
98 tool.description or f"Execute {tool.slug}",
99 aliases.schema,
100 )
101 async def tool_handler(args: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
102 """Execute the Composio tool with the given arguments."""
103 try:
104 arguments = aliases.restore_arguments(normalize_tool_arguments(args))
105 # Run the synchronous execute_tool in a thread
106 result = await asyncio.to_thread(
107 execute_tool,
108 tool.slug,
109 arguments,
110 )
111 # Format the result for Claude Agent SDK
112 result_text = result if isinstance(result, str) else json.dumps(result)
113 return {
114 "content": [
115 {
116 "type": "text",
117 "text": result_text,
118 }
119 ]
120 }
121 except Exception as e:
122 return {
123 "content": [
124 {
125 "type": "text",
126 "text": json.dumps(
127 {
128 "successful": False,
129 "error": str(e),
130 "data": None,
131 }
132 ),
133 }
134 ]
135 }
136
137 return tool_handler
138
139 def _json_schema_to_simple_schema(self, schema: dict) -> dict:
140 """Return the provider-visible schema for a Composio JSON schema."""
141 return alias_tool_input_schema(schema or {}).schema
142
143 def wrap_tools(
144 self,
145 tools: t.Sequence[Tool],
146 execute_tool: AgenticProviderExecuteFn,
147 ) -> list[SdkMcpTool]:
148 """
149 Wrap multiple Composio tools as Claude Agent SDK MCP tools.
150
151 Args:
152 tools: Sequence of Composio tools to wrap
153 execute_tool: Function to execute the tools
154
155 Returns:
156 List of Claude Agent SDK MCP tool definitions
157 """
158 return [self.wrap_tool(tool, execute_tool) for tool in tools]
159
160 def create_mcp_server(
161 self,
162 wrapped_tools: list[SdkMcpTool],
163 ) -> McpSdkServerConfig:
164 """
165 Create an MCP server configuration for use with Claude Agent SDK.
166
167 This is the primary method for integrating Composio tools with Claude agents.
168 The returned configuration can be passed directly to the `mcp_servers` option.
169
170 Args:
171 wrapped_tools: List of wrapped Claude Agent SDK MCP tools
172 (from composio.tools.get())
173
174 Returns:
175 MCP server configuration for Claude Agent SDK
176
177 Example:
178 ```python
179 tools = composio.tools.get(user_id="default", toolkits=["gmail"])
180 mcp_server = composio.provider.create_mcp_server(tools)
181
182 async for message in query(
183 prompt="Send an email",
184 options=ClaudeAgentOptions(
185 mcp_servers={"composio": mcp_server},
186 ),
187 ):
188 print(message)
189 ```
190 """
191 return create_sdk_mcp_server(
192 name=self.server_name,
193 version=self.server_version,
194 tools=wrapped_tools,
195 )