1
----
2
-title: Using with MCP clients
3
-description: Use Tool Router as an MCP server with any MCP client
4
-keywords: [mcp server, http transport]
5
----
6
-
7
-Every Tool Router session provides a unique MCP server URL. This URL exposes the exact session you created - with the specific user, toolkits, and auth configs you configured. Any MCP client that supports HTTP transport can connect using just the URL and your API key.
8
-
9
-## Examples for popular frameworks
10
-
11
-Jump to examples for:
12
-- [Claude Agent SDK](#claude-agent-sdk) - Python, TypeScript
13
-- [OpenAI Agents SDK](#openai-agents-sdk) - Python, TypeScript
14
-- [Vercel AI SDK](#vercel-ai-sdk) - TypeScript
15
-
16
-## Claude Agent SDK
17
-
18
-### Installation
19
-
20
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
21
-<Tab value="Python">
22
-```bash
23
-pip install python-dotenv composio claude-agent-sdk
24
-```
25
-</Tab>
26
-<Tab value="TypeScript">
27
-```bash
28
-npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk
29
-```
30
-</Tab>
31
-</Tabs>
32
-
33
-### Usage
34
-
35
-Create a Tool Router session and execute tasks with Claude:
36
-
37
-<Callout type="info">
38
-- Set your `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
39
-- Set your `ANTHROPIC_API_KEY` environment variable with your [Anthropic API key](https://platform.claude.com/settings/keys).
40
-</Callout>
41
-
42
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
43
-<Tab value="Python">
44
-```python
45
-import asyncio
46
-from dotenv import load_dotenv
47
-from claude_agent_sdk.client import ClaudeSDKClient
48
-from claude_agent_sdk.types import (
49
- ClaudeAgentOptions,
50
- AssistantMessage,
51
- TextBlock,
52
- ToolUseBlock,
53
-)
54
-from composio import Composio
55
-
56
-load_dotenv()
57
-
58
-# Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly)
59
-composio = Composio()
60
-
61
-# Unique identifier of the user
62
-user_id = "user_123"
63
-# Create a tool router session for the user
64
-session = composio.create(user_id=user_id)
65
-
66
-# Configure Claude with Composio MCP server
67
-options = ClaudeAgentOptions(
68
- system_prompt=(
69
- "You are a helpful assistant with access to external tools. "
70
- "Always use the available tools to complete user requests."
71
- ),
72
- mcp_servers={
73
- "composio": {
74
- "type": "http",
75
- "url": session.mcp.url,
76
- "headers": session.mcp.headers, # Authentication headers for the Composio MCP server
77
- }
78
- },
79
- permission_mode="bypassPermissions", # Auto-approve tools (demo only)
80
-)
81
-
82
-async def main():
83
- print("""
84
-What task would you like me to help you with?
85
-I can use tools like Gmail, GitHub, Linear, Notion, and more.
86
-(Type 'exit' to exit)
87
-Example tasks:
88
- • 'Summarize my emails from today'
89
- • 'List all open issues on the composio github repository and create a notion page with the issues'
90
-""")
91
-
92
- async with ClaudeSDKClient(options) as client:
93
- # Multi-turn conversation with agentic tool calling
94
- while True:
95
- user_input = input("\nYou: ").strip()
96
- if user_input.lower() == "exit":
97
- break
98
-
99
- print("\nClaude: ", end="", flush=True)
100
- try:
101
- await client.query(user_input)
102
- async for msg in client.receive_response():
103
- if isinstance(msg, AssistantMessage):
104
- for block in msg.content:
105
- if isinstance(block, ToolUseBlock):
106
- print(f"\n[Using tool: {block.name}]", end="")
107
- elif isinstance(block, TextBlock):
108
- print(block.text, end="", flush=True)
109
- except Exception as e:
110
- print(f"\n[Error]: {e}")
111
-
112
-if __name__ == "__main__":
113
- asyncio.run(main())
114
-```
115
-</Tab>
116
-<Tab value="TypeScript">
117
-```typescript
118
-import "dotenv/config";
119
-import { query, type Options } from "@anthropic-ai/claude-agent-sdk";
120
-import { Composio } from "@composio/core";
121
-import { createInterface } from "readline/promises";
122
-
123
-// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
124
-const composio = new Composio();
125
-
126
-// Unique identifier of the user
127
-const userId = "user_123";
128
-
129
-// Create a tool router session for the user
130
-const session = await composio.create(userId);
131
-
132
-const options: Options = {
133
- systemPrompt: `You are a helpful assistant with access to external tools. ` +
134
- `Always use the available tools to complete user requests.`,
135
- mcpServers: {
136
- composio: {
137
- type: "http",
138
- url: session.mcp.url,
139
- headers: session.mcp.headers // Authentication headers for the Composio MCP server
140
- },
141
- },
142
- permissionMode: "bypassPermissions", // Auto-approve tools (demo only - use "default" in production)
143
-};
144
-
145
-// Set up interactive terminal input/output for the conversation
146
-const readline = createInterface({ input: process.stdin, output: process.stdout });
147
-
148
-console.log(`
149
-What task would you like me to help you with?
150
-I can use tools like Gmail, GitHub, Linear, Notion, and more.
151
-(Type 'exit' to exit)
152
-Example tasks:
153
- • 'Summarize my emails from today'
154
- • 'List all open issues on the composio github repository and create a notion page with the issues'
155
-`);
156
-
157
-let isFirstQuery = true;
158
-
159
-// Multi-turn conversation with agentic tool calling
160
-while (true) {
161
- const answer = await readline.question('You: ');
162
- const input = answer.trim();
163
- if (input.toLowerCase() === "exit") break;
164
-
165
- process.stdout.write("Claude: ");
166
-
167
- const queryOptions = isFirstQuery ? options : { ...options, continue: true };
168
- isFirstQuery = false;
169
-
170
- try {
171
- for await (const stream of query({ prompt: input, options: queryOptions })) {
172
- // Only process assistant messages (the SDK also sends result/error messages)
173
- if (stream.type === "assistant") {
174
- const { content } = stream.message;
175
- for (const block of content) {
176
- if (block.type === "tool_use") {
177
- process.stdout.write(`\n[Using tool: ${block.name}]`);
178
- } else if (block.type === "text") {
179
- process.stdout.write(block.text);
180
- }
181
- }
182
- }
183
- }
184
- } catch (error) {
185
- console.error("\n[Error]:", error instanceof Error ? error.message : error);
186
- }
187
- process.stdout.write("\n");
188
-}
189
-
190
-readline.close();
191
-```
192
-</Tab>
193
-</Tabs>
194
-
195
-## OpenAI Agents SDK
196
-
197
-### Installation
198
-
199
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
200
-<Tab value="Python">
201
-```bash
202
-pip install python-dotenv composio openai-agents
203
-```
204
-</Tab>
205
-<Tab value="TypeScript">
206
-```bash
207
-npm install dotenv @composio/core @openai/agents zod@3
208
-```
209
-</Tab>
210
-</Tabs>
211
-
212
-### Usage
213
-
214
-Create a Tool Router session and execute tasks with OpenAI agents:
215
-
216
-<Callout type="info">
217
-- Set `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
218
-- Set `OPENAI_API_KEY` environment variable with your [OpenAI API key](https://platform.openai.com/api-keys).
219
-</Callout>
220
-
221
-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
222
-<Tab value="Python">
223
-```python
224
-from dotenv import load_dotenv
225
-from composio import Composio
226
-from agents import Agent, Runner, HostedMCPTool
227
-
228
-load_dotenv()
229
-
230
-# Initialize Composio (API key from env var COMPOSIO_API_KEY)
231
-composio = Composio()
232
-# Unique identifier of the user
233
-user_id = "user_123"
234
-
235
-# Create a Tool Router session for the user
236
-session = composio.create(user_id=user_id)
237
-
238
-# Configure OpenAI agent with Composio MCP server
239
-agent = Agent(
240
- name="Personal Assistant",
241
- instructions="You are a helpful personal assistant. Use Composio tools to take action.",
242
- model="gpt-5.2",
243
- tools=[
244
- HostedMCPTool(
245
- tool_config={
246
- "type": "mcp",
247
- "server_label": "composio",
248
- "server_url": session.mcp.url,
249
- "require_approval": "never",
250
- "headers": session.mcp.headers,
251
- }
252
- )
253
- ],
254
-)
255
-
256
-# Execute the task
257
-print("Fetching GitHub issues from the Composio repository @ComposioHQ/composio...\n")
258
-try:
259
- result = Runner.run_sync(
260
- starting_agent=agent,
261
- input="Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
262
- )
263
- print(result.final_output)
264
-except Exception as e:
265
- print(f"[Error]: {e}")
266
-
267
-print("\n\n---")
268
-print("Tip: If prompted to authenticate, complete the auth flow and run again.")
269
-```
270
-</Tab>
271
-<Tab value="TypeScript">
272
-```typescript
273
-import "dotenv/config";
274
-import { Composio } from "@composio/core";
275
-import { Agent, hostedMcpTool, run, MemorySession } from "@openai/agents";
276
-import { createInterface } from "readline/promises";
277
-
278
-// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
279
-const composio = new Composio();
280
-
281
-// Unique identifier of the user
282
-const userId = "user_123";
283
-
284
-// Create a tool router session for the user
285
-const session = await composio.create(userId);
286
-
287
-const agent = new Agent({
288
- name: "Personal Assistant",
289
- instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
290
- model: "gpt-5.2",
291
- tools: [
292
- hostedMcpTool({
293
- serverLabel: "composio",
294
- serverUrl: session.mcp.url,
295
- headers: session.mcp.headers, // Authentication headers for the Composio MCP server
296
- }),
297
- ],
298
-});
299
-
300
-// Create a memory session for persistent multi-turn conversation
301
-const memory = new MemorySession();
302
-
303
-// Execute an initial task
304
-console.log("Fetching GitHub issues from the Composio repository...\n");
305
-try {
306
- const initialResult = await run(
307
- agent,
308
- "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
309
- { session: memory }
310
- );
311
- console.log(`${initialResult.finalOutput}\n`);
312
-} catch (error) {
313
- console.error("[Error]:", error instanceof Error ? error.message : error);
314
-}
315
-
316
-// Continue with interactive conversation
317
-const readline = createInterface({ input: process.stdin, output: process.stdout });
318
-
319
-console.log(`
320
-What else would you like me to do?
321
-(Type 'exit' to exit)
322
-`);
323
-
324
-while (true) {
325
- const input = (await readline.question("You: ")).trim();
326
- if (input.toLowerCase() === "exit") break;
327
-
328
- console.log("Assistant: ");
329
-
330
- try {
331
- const result = await run(agent, input, { session: memory });
332
- console.log(`${result.finalOutput}\n`);
333
- } catch (error) {
334
- console.error("\n[Error]:", error instanceof Error ? error.message : error);
335
- }
336
-}
337
-readline.close();
338
-```
339
-</Tab>
340
-</Tabs>
341
-
342
-## Vercel AI SDK
343
-
344
-### Installation
345
-
346
-```bash
347
-npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
348
-```
349
-
350
-### Usage
351
-
352
-Use Tool Router with Vercel AI SDK's `generateText` for single completions:
353
-
354
-<Callout type="info">
355
-- Set `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
356
-- Set `ANTHROPIC_API_KEY` environment variable with your [Anthropic API key](https://platform.claude.com/settings/keys).
357
-</Callout>
358
-
359
-```typescript
360
-import "dotenv/config";
361
-import { anthropic } from "@ai-sdk/anthropic";
362
-import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp";
363
-import { Composio } from "@composio/core";
364
-import { stepCountIs, streamText } from "ai";
365
-
366
-// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
367
-const composio = new Composio();
368
-
369
-// Unique identifier of the user
370
-const userId = "user_123";
371
-
372
-// Create a tool router session for the user
373
-const { mcp } = await composio.create(userId);
374
-
375
-// Create an MCP client to connect to the Composio tool router
376
-const client = await createMCPClient({
377
- transport: {
378
- type: "http",
379
- url: mcp.url,
380
- headers: mcp.headers, // Authentication headers for the Composio MCP server
381
- },
382
-});
383
-const tools = await client.tools();
384
-
385
-console.log("Summarizing your emails from today");
386
-
387
-const stream = await streamText({
388
- system: "You are a helpful personal assistant. Use Composio tools to take action.",
389
- model: anthropic("claude-sonnet-4-5"),
390
- prompt: "Summarize my emails from today",
391
- stopWhen: stepCountIs(10),
392
- onStepFinish: (step) => {
393
- for (const toolCall of step.toolCalls) {
394
- console.log(`[Using tool: ${toolCall.toolName}]`);
395
- }
396
- },
397
- tools,
398
-});
399
-
400
-for await (const textPart of stream.textStream) {
401
- process.stdout.write(textPart);
402
-}
403
-
404
-console.log("\n\n---");
405
-console.log("Tip: If prompted to authenticate, complete the auth flow and run again.")
406
-```