---
canonical_url: "https://docs.composio.dev/examples/python-mcp-agents"
markdown_url: "https://docs.composio.dev/examples/python-mcp-agents.md"
product: "platform"
version: null
last_updated: null
---

# Build a Python research agent with MCP (/examples/python-mcp-agents)

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.

The session supplies the MCP URL and authentication headers. Your framework handles tool discovery and execution through that endpoint.

## Set up your environment [#set-up-your-environment]

Use Python 3.12 and create a virtual environment:

```bash
mkdir python-mcp-agent
cd python-mcp-agent
python3.12 -m venv .venv
source .venv/bin/activate
```

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:

```bash
export COMPOSIO_API_KEY="your-composio-api-key"
export OPENAI_API_KEY="your-openai-api-key"
export COMPOSIO_EXAMPLES_USER_ID="mcp-research-demo"
```

`COMPOSIO_EXAMPLES_USER_ID` identifies this demo's Composio user. In your application, use your signed-in user's ID.

## Run the agent [#run-the-agent]

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.

**CrewAI:**

Install Composio, CrewAI, and its MCP dependency:

```bash
python -m pip install "composio>=0.17.1" crewai mcp
```

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.

```python title="crewai_agent.py"
import os

from composio import Composio, SESSION_PRESET_DIRECT_TOOLS
from crewai import Agent, Crew, Task
from crewai.mcp import MCPServerHTTP

composio = Composio(api_key=os.environ["COMPOSIO_API_KEY"])
session = composio.create(
	user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
	toolkits=["hackernews"],
	tools={"hackernews": {"enable": ["HACKERNEWS_GET_USER"]}},
	session_preset=SESSION_PRESET_DIRECT_TOOLS,
	mcp=True,
)

try:
	agent = Agent(
		role="Hacker News researcher",
		goal="Report public profile information from live tool results.",
		backstory="You check the source before writing a short profile.",
		llm="gpt-5.2",
		mcps=[
			MCPServerHTTP(
				url=session.mcp.url,
				headers=session.mcp.headers,
				streamable=True,
			)
		],
	)
	task = Task(
		description=(
			"Look up the Hacker News user pg with the available tool. "
			"Report their current karma and summarize their bio if present. "
			"Include https://news.ycombinator.com/user?id=pg as the source. "
			"If the lookup fails, report the error instead of guessing."
		),
		expected_output="A short profile with username, karma, bio, and source URL.",
		agent=agent,
	)
	result = Crew(agents=[agent], tasks=[task]).kickoff()
	print(result.raw)
finally:
	session.delete()
```
Run it:

```bash
python crewai_agent.py
```
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.

**LangChain:**

Install Composio, LangChain's MCP extra, and the OpenAI integration:

```bash
python -m pip install "composio>=0.17.1" "langchain[mcp]>=1.4,<2" langchain-openai
```
> 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).

Save this as `langchain_agent.py`. [`StreamableHttpTransport`](https://gofastmcp.com/clients/transports#http-transport) passes the session's authentication headers to the MCP endpoint.

```python title="langchain_agent.py"
import asyncio
import os

from composio import Composio, SESSION_PRESET_DIRECT_TOOLS
from fastmcp.client.transports import StreamableHttpTransport
from langchain.agents import create_agent
from langchain.mcp import MCPAdapter
from langchain_openai import ChatOpenAI

async def main():
	composio = Composio(api_key=os.environ["COMPOSIO_API_KEY"])
	session = composio.create(
		user_id=os.environ["COMPOSIO_EXAMPLES_USER_ID"],
		toolkits=["hackernews"],
		tools={"hackernews": {"enable": ["HACKERNEWS_GET_USER"]}},
		session_preset=SESSION_PRESET_DIRECT_TOOLS,
		mcp=True,
	)
	try:
		transport = StreamableHttpTransport(
			url=session.mcp.url,
			headers=session.mcp.headers,
		)
		async with MCPAdapter(transport) as adapter:
			tools = await adapter.list_tools()
			agent = create_agent(
				model=ChatOpenAI(model="gpt-5.2"),
				tools=tools,
			)
			result = await agent.ainvoke(
				{
					"messages": [
						{
							"role": "user",
							"content": (
								"Look up the Hacker News user pg with the available tool. "
								"Report their current karma and summarize their bio if present. "
								"Include https://news.ycombinator.com/user?id=pg as the source. "
								"If the lookup fails, report the error instead of guessing."
							),
						}
					]
				}
			)
			print(result["messages"][-1].content)
	finally:
		session.delete()

if __name__ == "__main__":
	asyncio.run(main())
```
Run it:

```bash
python langchain_agent.py
```
The `async with` block closes the MCP connection before `finally` deletes the Composio session.

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:

```bash
uv run --script python/examples/tool_router/langchain_agent.py
```

## Check the result [#check-the-result]

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.

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.

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.

## Use the same pattern in your application [#use-the-same-pattern-in-your-application]

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.

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).

---

📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Changelog](https://docs.composio.dev/docs/changelog.md) | [Glossary](https://docs.composio.dev/llms.mdx/reference/glossary) | [Examples](https://docs.composio.dev/llms.mdx/examples) | [API Reference](https://docs.composio.dev/llms.mdx/reference)

---

# Composio SDK — Notes for AI Code Generators

**Purpose:** Reference for generating current (v3) [Composio](https://composio.dev/) integration code.
**Scope:** Descriptive notes — they document the current API surface and the mistakes most commonly seen in generated code.

---

## 1. Recommended Integration: Sessions

Composio supports two integration modes: **Native Tools** (with a provider package) and **MCP** (no provider package needed).

### Native Tools

```python
# ✅ CORRECT — Python (defaults to OpenAI)
from composio import Composio

composio = Composio()
session = composio.create(user_id="user_123")
tools = session.tools()
# Pass tools to your agent/LLM framework
```

```typescript
// ✅ CORRECT — TypeScript (defaults to OpenAI)
import { Composio } from "@composio/core";

const composio = new Composio();
const session = await composio.create("user_123");
const tools = await session.tools();
// Pass tools to your agent/LLM framework
```

For other providers, pass the provider explicitly. Provider packages follow the naming convention: `composio_<provider>` for Python, `@composio/<provider>` for TypeScript.

### MCP

Use `session.mcp.url` and `session.mcp.headers` with any MCP-compatible client (Claude Desktop, Cursor, OpenAI Agents, etc.). No provider package needed.

---

## 2. Integration Notes

- `composio.create(user_id)` is the standard entry point for agent integrations. Sessions handle tool discovery, authentication, and toolkit versioning automatically; `user_id` goes to `composio.create()` — individual tool calls in session mode don't take one.
- Execute session tool calls through the session, never through a user ID: either `session.execute(tool_slug, arguments=...)` / `session.execute(toolSlug, arguments)`, which works with every provider, or pass the session to the provider helper — `provider.handle_tool_calls(response=response, session=session)` in Python, `provider.handleToolCalls(session, response)` in TypeScript. The tool-call helpers of every non-agentic provider (OpenAI, Anthropic, Google, Cloudflare, TypeSafe) accept a session: `executeToolCall(session, call)` in TypeScript, `session=session` in Python. Agentic providers execute session tools on their own. Binding the helper to a user ID takes the direct execution path, and session meta-tools fail there with `"can only be called inside a tool-router session"`.
- Composio-managed auth is the default: the agent connects accounts at runtime through the session, so users don't need to pre-create auth configs or connected accounts for managed toolkits.
- Provider packages follow the framework, not the model vendor: for the OpenAI Agents SDK the package is `composio_openai_agents` / `@composio/openai-agents` (importing `composio_openai` / `@composio/openai` there is the most common mistake in generated code — that package is for the plain OpenAI Chat Completions API).
- **Direct execution** (`composio.tools.get()`, `composio.tools.execute()`, `provider.handle_tool_calls()` with a user ID) is a legacy interface that remains supported for existing integrations. Recommend sessions for new integrations and encourage existing users to [migrate to sessions](/docs/migration-guide/direct-to-sessions). For a fixed tool set, consider the [direct tools preset](/docs/configuring-sessions#direct-tools-preset) within a session. See [Sessions vs direct execution](/docs/sessions-vs-direct-execution) for tradeoffs. Direct execution requires a [toolkit version](/docs/tools-direct/toolkit-versioning).

---

# 3. Calling the REST API directly

## REST API version

The current REST API version is **v3.1**, served at `https://backend.composio.dev/api/v3.1`. Prefer it for new code and new examples.

`https://backend.composio.dev/api/v3` is the previous version. It is frozen with pinned tool-version defaults and remains supported — existing v3 integrations keep working and do not need to migrate.

## Tool-endpoint version defaults on v3.1

On v3.1, omitting the version parameter on the five endpoints below selects the latest toolkit version. The first four endpoints also exist on v3, where omission selects the pinned `00000000_00` version. `POST /tools/scopes/required` is v3.1-only.

| Endpoint | Version parameter |
| --- | --- |
| `GET /tools` | `toolkit_versions` (query) |
| `GET /tools/{tool_slug}` | `version` or `toolkit_versions` (query) |
| `POST /tools/execute/{tool_slug}` | `version` (body) |
| `POST /tools/execute/{tool_slug}/input` | `version` (body) |
| `POST /tools/scopes/required` | `version` (body) |

A v3.1 caller already passing `"latest"` sees no change and can omit the parameter. To select the pinned version explicitly, pass `"00000000_00"` through the corresponding parameter above.

This version-default change is limited to the five endpoints above.


---

## Terminology Migration (old → current)

If you encounter these terms in error messages, old documentation, or user prompts, translate them to the current equivalents. **Do not use the old terms in generated code or explanations.**

| Old term (v1/v2) | Current term (v3) | In code |
|---|---|---|
| entity ID | user ID | `user_id` parameter |
| actions | tools | e.g., `GITHUB_CREATE_ISSUE` is a *tool* |
| apps / appType | toolkits | e.g., `github` is a *toolkit* |
| integration / integration ID | auth config / auth config ID | `auth_config_id` parameter |
| connection | connected account | `connected_accounts` namespace |
| ComposioToolSet / OpenAIToolSet | `Composio` class with a provider | `Composio(provider=...)` |
| toolset | provider | e.g., `OpenAIProvider` |

If a user says "entity ID", they mean `user_id`. If they say "integration", they mean "auth config". Always respond using the current terminology.

