How to Use Composio with LangChain for Tool-Augmented Agents
Composio provides a LangChain provider that converts Composio tools into LangChain DynamicStructuredTool instances, enabling any LangChain agent to execute external API actions through a standardized interface.
The ComposioHQ/composio repository offers a dedicated TypeScript provider that bridges the Composio ecosystem with LangChain's agent framework. By using Composio with LangChain, developers can equip LLM agents with production-ready tools for Gmail, GitHub, Slack, and 100+ other services without writing custom API integrations.
Architecture of the Composio LangChain Integration
The integration follows a provider pattern that abstracts tool discovery and execution into LangChain-compatible interfaces.
| Component | Role | Source |
|---|---|---|
Composio core (@composio/core) |
Handles authentication, tool discovery, and execution requests against the Composio backend. | ts/packages/core/src/composio.ts |
LangChain provider (@composio/langchain) |
Extends BaseAgenticProvider and converts each Tool into a DynamicStructuredTool. Supplies wrapTool and wrapTools helpers. |
ts/packages/providers/langchain/src/index.ts |
| LangChain runtime | Executes agents, chains, or LCEL expressions. Accepts the provider's output directly into createOpenAIFunctionsAgent or AgentExecutor. |
External dependency |
MCP client (@langchain/mcp-adapters) |
Provides multi-server MCP client support that fetches tools from Composio MCP endpoints and wraps them via the provider. | ts/examples/tool-router/src/langchain.ts |
The execution flow follows five steps:
- Initialize a
Composioinstance with your API key andLangChainProvider. - Fetch desired tools for a specific user via
composio.tools.get(). - Wrap raw Composio
Toolobjects usingprovider.wrapTools()to generateDynamicStructuredToolinstances. - Pass wrapped tools to a LangChain agent, chain, or LCEL expression.
- When the LLM invokes a function, the provider's
funcforwards the request tocomposio.tools.execute()and returns the JSON-stringified result.
Setting Up Composio with LangChain
Before implementing tool-augmented agents, install the required packages and configure authentication.
npm install @composio/core @composio/langchain @langchain/openai langchain
export COMPOSIO_API_KEY="your_api_key_here"
export OPENAI_API_KEY="your_openai_key_here"
Initializing the LangChainProvider
The LangChainProvider class extends BaseAgenticProvider and implements the transformation logic required to bridge Composio tools with LangChain's tool interface.
import { Composio } from '@composio/core';
import { LangChainProvider } from '@composio/langchain';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
provider: new LangChainProvider(),
});
Implementing Tool-Augmented Agents
Once initialized, you can construct agents that leverage external APIs through Composio's tool ecosystem.
Basic Agent with Gmail Tools
This example demonstrates fetching Gmail tools and integrating them into an OpenAI functions-based agent.
import { Composio } from '@composio/core';
import { LangChainProvider } from '@composio/langchain';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
// Initialise Composio with the LangChain provider
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
provider: new LangChainProvider(),
});
// Discover tools for a user (e.g., Gmail toolkit)
const composioTools = await composio.tools.get('user_123', {
toolkits: ['gmail'],
limit: 10,
});
// Convert to LangChain tools
const langchainTools = composio.provider!.wrapTools(
composioTools,
composio.tools.execute,
);
// Build a LangChain model
const model = new ChatOpenAI({ modelName: 'gpt-4o', temperature: 0 });
// Create an OpenAI‑functions‑style agent
const agent = await createOpenAIFunctionsAgent({
llm: model,
tools: langchainTools,
});
// Execute the agent
const executor = new AgentExecutor({ agent, tools: langchainTools });
const result = await executor.invoke({
input: 'Fetch my most recent email from Gmail',
});
console.log(result);
Reference: ts/packages/providers/langchain/src/index.ts
Using the MCP Adapter for Multi-Server Setups
For applications requiring dynamic tool discovery across multiple Composio toolkits, the MCP (Model Context Protocol) adapter provides a flexible alternative.
import { MultiServerMCPClient } from '@langchain/mcp-adapters';
import { ChatOpenAI } from '@langchain/openai';
import { createAgent } from 'langchain';
import { Composio } from '@composio/core';
// Initialise Composio
const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
// Create a session that gives you an MCP endpoint for the user
const session = await composio.create('user_123', { toolkits: ['gmail'] });
// Build an MCP client that knows how to fetch tools from Composio
const client = new MultiServerMCPClient({
gmail: {
transport: 'http',
url: session.mcp.url,
headers: session.mcp.headers,
},
});
// Pull the tools and let LangChain handle wrapping automatically
const tools = await client.getTools();
const llm = new ChatOpenAI({ model: 'gpt-4o' });
const agent = createAgent({
name: 'Gmail Assistant',
systemPrompt: 'You are a helpful Gmail assistant.',
model: llm,
tools, // already LangChain‑compatible
});
const result = await agent.invoke({
messages: [{ role: 'user', content: 'Send an email to alice@example.com saying hi' }],
});
console.log(result);
Reference: ts/examples/tool-router/src/langchain.ts
Streaming Responses with Tool Execution
For real-time applications, you can stream agent responses while maintaining tool execution capabilities through LCEL (LangChain Expression Language).
import { Composio } from '@composio/core';
import { LangChainProvider } from '@composio/langchain';
import { ChatPromptTemplate } from '@langchain/core/prompts';
import { StringOutputParser } from '@langchain/core/output_parsers';
import { ChatOpenAI } from '@langchain/openai';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
provider: new LangChainProvider(),
});
const tools = await composio.tools.get('user_123', {
toolkits: ['gmail'],
});
const provider = composio.provider!;
const langchainTools = provider.wrapTools(tools, composio.tools.execute);
const model = new ChatOpenAI({ modelName: 'gpt-4', streaming: true });
const prompt = ChatPromptTemplate.fromTemplate(
'You are a helpful assistant. Use the provided tools if needed. Question: {question}'
);
const parser = new StringOutputParser();
const chain = prompt.pipe(model).pipe(parser);
for await (const chunk of chain.stream({ question: 'Give me a list of my latest Gmail threads' })) {
console.log('Model chunk:', chunk);
}
Reference: ts/packages/providers/langchain/README.md
Key Implementation Details
Understanding the internal mechanics of the LangChain provider helps debug integration issues and optimize performance.
Tool Wrapping Mechanism
The wrapTool method in ts/packages/providers/langchain/src/index.ts extracts the tool slug, description, and JSON Schema-based input parameters from each Composio tool. It converts the schema to a Zod instance using jsonSchemaToZodSchema, then constructs a DynamicStructuredTool whose func property calls executeTool and returns a JSON-stringified result.
Batch Tool Processing
The wrapTools method applies wrapTool across an array of tools, returning a ready-to-use array of DynamicStructuredTool instances. This batch processing ensures consistent schema conversion and execution binding across all tools in a toolkit.
MCP Compatibility Layer
The provider implements wrapMcpServerResponse to convert generic MCP URL lists into the format expected by LangChain's MultiServerMCPClient. This enables dynamic tool discovery from Composio's MCP endpoints without manual tool definition.
Key Files in the Composio Repository
| File | Purpose |
|---|---|
ts/packages/providers/langchain/src/index.ts |
Core provider implementation – wraps Composio tools into LangChain DynamicStructuredTools. |
ts/examples/tool-router/src/langchain.ts |
Demonstrates MCP‑based fetching and direct agent creation. |
ts/packages/providers/langchain/README.md |
Installation, environment variables, quick‑start, and advanced usage guide. |
ts/packages/providers/langchain/package.json |
Declares dependencies on @langchain/core and @langchain/openai. |
ts/packages/providers/langchain/test/langchain.test.ts |
Unit tests confirming provider name and tooling behavior. |
These files illustrate how the provider bridges the two ecosystems and provide concrete reference points for extending or debugging the integration.
Summary
- Composio with LangChain enables LLM agents to execute external API actions through a standardized
DynamicStructuredToolinterface. - The
LangChainProviderclass in@composio/langchainhandles the conversion of Composio tools into LangChain-compatible formats using Zod schema validation. - Tool execution flows from the LangChain agent to the Composio backend via
composio.tools.execute, with results returned as JSON strings. - MCP support allows dynamic tool discovery through
MultiServerMCPClient, enabling runtime tool selection without hardcoded definitions. - All integration points are fully typed and support streaming, batch processing, and custom execution modifiers.
Frequently Asked Questions
How do I authenticate Composio tools when using LangChain?
Authentication is handled at the Composio level rather than within LangChain. When you initialize the Composio instance with your API key, the SDK manages OAuth tokens and API credentials for each connected service (Gmail, GitHub, etc.). The LangChain provider receives pre-authenticated tool definitions, so your agent code only needs to handle the COMPOSIO_API_KEY environment variable.
Can I use Composio tools with LangChain's LCEL (LangChain Expression Language)?
Yes, the DynamicStructuredTool instances returned by LangChainProvider.wrapTools() are fully compatible with LCEL chains. You can bind tools to models using .bind({ tools: langchainTools }) or use them within RunnableSequence compositions. The streaming example in ts/packages/providers/langchain/README.md demonstrates how to pipe tool-enabled models through prompt templates and output parsers while maintaining real-time response streaming.
What is the difference between wrapTool and wrapTools in the LangChain provider?
wrapTool converts a single Composio tool into a LangChain DynamicStructuredTool by extracting the slug, description, and JSON schema, converting the schema to Zod, and binding the execution function. wrapTools is a batch convenience method that maps an array of Composio tools through wrapTool, returning an array ready for use with AgentExecutor or createOpenAIFunctionsAgent. Both methods ensure consistent schema validation and execution binding.
How does the MCP adapter enhance Composio's LangChain integration?
The MCP (Model Context Protocol) adapter allows LangChain's MultiServerMCPClient to dynamically fetch tool definitions from Composio's MCP endpoints rather than requiring static tool imports. This enables runtime tool discovery where your agent can access new toolkits simply by changing the MCP server configuration in composio.create(). The implementation in ts/examples/tool-router/src/langchain.ts shows how this decouples tool availability from application deployment, supporting multi-tenant scenarios where different users access different tool sets.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →