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
mdx 208 lines 7.69 KB
Raw
1 ---
2 title: Build a Python research agent with MCP
3 description: Read a public Hacker News profile with CrewAI or LangChain through a Composio session's MCP endpoint.
4 keywords: [python, mcp, crewai, langchain, hackernews, research agent]
5 gallery:
6 categories: [General agents]
7 logos: [hackernews]
8 featured: true
9 order: 7
10 ---
11
12 {/* code-example: single-language-page reason="Python-only example project using CrewAI and LangChain Python MCP clients" */}
13
14 Build an agent that reads a Hacker News profile and reports its current karma and bio. Choose CrewAI or LangChain below. Both agents use a Composio session that exposes one public, read-only tool over MCP, so you don't need to connect a Hacker News account.
15
16 The session supplies the MCP URL and authentication headers. Your framework handles tool discovery and execution through that endpoint.
17
18 ## Set up your environment
19
20 Use Python 3.12 and create a virtual environment:
21
22 ```bash
23 mkdir python-mcp-agent
24 cd python-mcp-agent
25 python3.12 -m venv .venv
26 source .venv/bin/activate
27 ```
28
29 Set your [Composio project API key](https://dashboard.composio.dev/~/project/settings/api-keys?utm_source=docs&utm_medium=content&utm_campaign=examples-python-mcp-agents) and [OpenAI API key](https://platform.openai.com/api-keys) in this shell:
30
31 ```bash
32 export COMPOSIO_API_KEY="your-composio-api-key"
33 export OPENAI_API_KEY="your-openai-api-key"
34 export COMPOSIO_EXAMPLES_USER_ID="mcp-research-demo"
35 ```
36
37 `COMPOSIO_EXAMPLES_USER_ID` identifies this demo's Composio user. In your application, use your signed-in user's ID.
38
39 ## Run the agent
40
41 Choose one framework and install its dependencies. Each script creates the session, runs the lookup, and deletes the session when the run finishes or raises an error.
42
43 {/* code-example: single-language reason="CrewAI vs LangChain framework picker; both are Python-only MCP agent scripts" */}
44 <Tabs items={['CrewAI', 'LangChain']}>
45 <Tab value="CrewAI">
46
47 Install Composio, CrewAI, and its MCP dependency:
48
49 ```bash
50 python -m pip install "composio>=0.17.1" crewai mcp
51 ```
52
53 Save this as `crewai_agent.py`. CrewAI's [`MCPServerHTTP`](https://docs.crewai.com/en/mcp/overview) accepts the session's URL and headers through the agent's `mcps` list.
54
55 ```python title="crewai_agent.py"
56 import os
57
58 from composio import Composio, SESSION_PRESET_DIRECT_TOOLS
59 from crewai import Agent, Crew, Task
60 from crewai.mcp import MCPServerHTTP
61
62 composio = Composio(api_key=os.environ["COMPOSIO_API_KEY"])
63 session = composio.create(
64 user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
65 toolkits=["hackernews"],
66 tools={"hackernews": {"enable": ["HACKERNEWS_GET_USER"]}},
67 session_preset=SESSION_PRESET_DIRECT_TOOLS,
68 mcp=True,
69 )
70
71 try:
72 agent = Agent(
73 role="Hacker News researcher",
74 goal="Report public profile information from live tool results.",
75 backstory="You check the source before writing a short profile.",
76 llm="gpt-5.2",
77 mcps=[
78 MCPServerHTTP(
79 url=session.mcp.url,
80 headers=session.mcp.headers,
81 streamable=True,
82 )
83 ],
84 )
85 task = Task(
86 description=(
87 "Look up the Hacker News user pg with the available tool. "
88 "Report their current karma and summarize their bio if present. "
89 "Include https://news.ycombinator.com/user?id=pg as the source. "
90 "If the lookup fails, report the error instead of guessing."
91 ),
92 expected_output="A short profile with username, karma, bio, and source URL.",
93 agent=agent,
94 )
95 result = Crew(agents=[agent], tasks=[task]).kickoff()
96 print(result.raw)
97 finally:
98 session.delete()
99 ```
100
101 Run it:
102
103 ```bash
104 python crewai_agent.py
105 ```
106
107 The repository's [CrewAI MCP example](https://github.com/ComposioHQ/composio/blob/next/python/examples/tool_router/crewai_agent.py) uses the same connection pattern to summarize Gmail. That variant needs a connected Gmail account.
108
109 </Tab>
110 <Tab value="LangChain">
111
112 Install Composio, LangChain's MCP extra, and the OpenAI integration:
113
114 ```bash
115 python -m pip install "composio>=0.17.1" "langchain[mcp]>=1.4,<2" langchain-openai
116 ```
117
118 <Callout type="info">
119 LangChain's [`MCPAdapter`](https://docs.langchain.com/oss/python/langchain/mcp) requires `langchain[mcp]>=1.4.0` and is in beta. It replaces the archived `langchain-mcp-adapters` package. For an existing `MultiServerMCPClient` integration, follow LangChain's [migration guide](https://docs.langchain.com/oss/python/migrate/langchain-mcp-adapters).
120 </Callout>
121
122 Save this as `langchain_agent.py`. [`StreamableHttpTransport`](https://gofastmcp.com/clients/transports#http-transport) passes the session's authentication headers to the MCP endpoint.
123
124 ```python title="langchain_agent.py"
125 import asyncio
126 import os
127
128 from composio import Composio, SESSION_PRESET_DIRECT_TOOLS
129 from fastmcp.client.transports import StreamableHttpTransport
130 from langchain.agents import create_agent
131 from langchain.mcp import MCPAdapter
132 from langchain_openai import ChatOpenAI
133
134
135 async def main():
136 composio = Composio(api_key=os.environ["COMPOSIO_API_KEY"])
137 session = composio.create(
138 user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
139 toolkits=["hackernews"],
140 tools={"hackernews": {"enable": ["HACKERNEWS_GET_USER"]}},
141 session_preset=SESSION_PRESET_DIRECT_TOOLS,
142 mcp=True,
143 )
144 try:
145 transport = StreamableHttpTransport(
146 url=session.mcp.url,
147 headers=session.mcp.headers,
148 )
149 async with MCPAdapter(transport) as adapter:
150 tools = await adapter.list_tools()
151 agent = create_agent(
152 model=ChatOpenAI(model="gpt-5.2"),
153 tools=tools,
154 )
155 result = await agent.ainvoke(
156 {
157 "messages": [
158 {
159 "role": "user",
160 "content": (
161 "Look up the Hacker News user pg with the available tool. "
162 "Report their current karma and summarize their bio if present. "
163 "Include https://news.ycombinator.com/user?id=pg as the source. "
164 "If the lookup fails, report the error instead of guessing."
165 ),
166 }
167 ]
168 }
169 )
170 print(result["messages"][-1].content)
171 finally:
172 session.delete()
173
174
175 if __name__ == "__main__":
176 asyncio.run(main())
177 ```
178
179 Run it:
180
181 ```bash
182 python langchain_agent.py
183 ```
184
185 The `async with` block closes the MCP connection before `finally` deletes the Composio session.
186
187 The same script is in [`python/examples/tool_router/langchain_agent.py`](https://github.com/ComposioHQ/composio/blob/next/python/examples/tool_router/langchain_agent.py). From a repository checkout, run it with [uv](https://docs.astral.sh/uv/guides/scripts/) to install its declared dependencies in an isolated environment:
188
189 ```bash
190 uv run --script python/examples/tool_router/langchain_agent.py
191 ```
192
193 </Tab>
194 </Tabs>
195
196 ## Check the result
197
198 The agent prints `pg`'s current karma, a short bio when the profile contains one, and the Hacker News profile URL. Values and wording vary between runs. Check that the response cites `https://news.ycombinator.com/user?id=pg` and uses the tool's result.
199
200 The [direct tools preset](/docs/configuring-sessions#direct-tools-preset) exposes `HACKERNEWS_GET_USER` directly. The agent doesn't need to search for tools or start an authentication flow. To research another Hacker News user, change `pg` in the prompt and source URL.
201
202 If the MCP connection returns an authentication error, check `COMPOSIO_API_KEY` and pass both `session.mcp.url` and `session.mcp.headers`. Re-run the script to create a fresh session; the previous run's session was deleted.
203
204 ## Use the same pattern in your application
205
206 Keep the [session](/docs/how-composio-works) for as long as the conversation needs it, then delete it. To use a toolkit that needs an account, [authorize that toolkit](/docs/authentication/manually-authenticating) before running the agent.
207
208 For SDK modifiers or custom tools that run in your process, use the [CrewAI provider](/docs/providers/crewai) or [LangChain provider](/docs/providers/langchain). Those features don't run through a hosted [MCP session](/docs/sessions-via-mcp#trade-offs).