> ## Documentation Index
> Fetch the complete documentation index at: https://composio-preview.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Executing tools directly

> Maintain legacy integrations that call composio.tools.execute(); prefer sessions for new integrations

> [!NOTE]
>
> **Legacy API: prefer sessions**
>
> This guide covers legacy direct-execution methods, which remain supported for existing integrations. For new integrations, use [sessions](https://composio-preview.mintlify.site/docs/configuring-sessions.md) to manage tool fetching, authentication, and execution. If you use direct execution today, consider [migrating to sessions](https://composio-preview.mintlify.site/docs/migration-guide/direct-to-sessions.md). See [Sessions vs direct execution](https://composio-preview.mintlify.site/docs/sessions-vs-direct-execution.md) for the tradeoffs.

LLMs on their own can only do generation. Tool calling changes that by letting them interact with external services. Instead of just drafting an email, the model can call `GMAIL_SEND_EMAIL` to actually send it. The tool's results feed back to the LLM, closing the loop so it can decide, act, observe, and adapt.

In Composio, every **tool** is a single API action—fully described with schema, parameters, and return type. Tools live inside **toolkits** like Gmail, Slack, or GitHub, and Composio handles authentication and user scoping.

To run a specific tool version, pass `version` directly to `composio.tools.execute()`. See [Pin a version](#pin-a-version) for complete Python and TypeScript examples.

## Canceling TypeScript requests

TypeScript SDK methods accept an `AbortSignal` in their trailing request options. Aborted requests throw `ComposioRequestCancelledError`, so cancellation can be handled separately from execution failures:

```typescript theme={null}
import { Composio, ComposioRequestCancelledError } from '@composio/core';

const composio = new Composio({ apiKey: 'your_composio_api_key' });

try {
  await composio.toolkits.get({}, { signal: AbortSignal.timeout(5_000) });
} catch (error) {
  if (error instanceof ComposioRequestCancelledError) {
    console.log('Request canceled');
  }
}
```

Use an `AbortController` when application code decides when to cancel. Custom tools receive the same signal as `ctx.signal` and should pass it to cancellable work.

> [!NOTE]
>
> **User Scoping**: All tools are scoped to a specific user - that's why every example includes a `user_id`. Learn how to structure User IDs in [User scoping](https://composio-preview.mintlify.site/docs/how-composio-works.md). Each user must authenticate with their respective services (Gmail, Calendar, etc.) - see [Authentication](https://composio-preview.mintlify.site/docs/tools-direct/authenticating-tools.md).

## Using Chat Completions

Use the Composio SDK with providers like OpenAI, Anthropic, and Google AI. To learn how to set up these providers, see [Providers](https://composio-preview.mintlify.site/docs/providers/openai.md).

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
> from composio_openai import OpenAIProvider
> from openai import OpenAI
> from datetime import datetime
>
> # Use a unique identifier for each user in your application
> user_id = "user-k7334"
>
> # Create composio client
> provider = OpenAIProvider()
> composio = Composio(provider=provider, api_key="your_composio_api_key")
>
> # Create openai client
> openai = OpenAI()
>
> # Get calendar tools for this user
> tools = composio.tools.get(
>     user_id=user_id,
>     tools=["GOOGLECALENDAR_EVENTS_LIST"]
> )
>
> # Ask the LLM to check calendar
> result = openai.chat.completions.create(
>     model="gpt-5.4",
>     tools=tools,
>     messages=[
>         {"role": "system", "content": "You are a helpful assistant."},
>         {"role": "user", "content": f"What's on my calendar for the next 7 days?"}
>     ]
> )
>
> # Handle tool calls
> result = provider.handle_tool_calls(user_id=user_id, response=result)
> print(result)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio, OpenAIProvider } from '@composio/core';
> import OpenAI from 'openai';
>
> // Use a unique identifier for each user in your application
> const userId = 'user-k7334';
>
> // Create composio client
> const composio = new Composio({
>   apiKey: 'your_composio_api_key',
>   provider: new OpenAIProvider(),
> });
>
> // Create openai client
> const openai = new OpenAI();
>
> // Get calendar tools for this user
> const tools = await composio.tools.get(userId, {
>   tools: ['GOOGLECALENDAR_EVENTS_LIST'],
> });
>
> // Ask the LLM to check calendar
> const completion = await openai.chat.completions.create({
>   model: 'gpt-5.4',
>   tools,
>   messages: [
>     { role: 'system', content: 'You are a helpful assistant.' },
>     { role: 'user', content: "What's on my calendar for the next 7 days?" },
>   ],
> });
>
> // Handle tool calls
> const result = await composio.provider.handleToolCalls(userId, completion);
> console.log(result);
> ```

## Using Agentic Frameworks

Agentic frameworks automatically handle the tool execution loop. Composio provides support for frameworks like this by making sure the tools are formatted into the correct objects for the agentic framework to execute.

> [tab] Python
>
> ```python theme={null}
> import asyncio
> from agents import Agent, Runner
> from composio import Composio
> from composio_openai_agents import OpenAIAgentsProvider
>
> # Use a unique identifier for each user in your application
> user_id = "user-k7334"
>
> # Initialize Composio toolset
> composio = Composio(provider=OpenAIAgentsProvider(), api_key="your_composio_api_key")
>
> # Get all tools for the user
> tools = composio.tools.get(
>     user_id=user_id,
>     toolkits=["COMPOSIO_SEARCH"],
> )
>
> # Create an agent with the tools
> agent = Agent(
>     name="Deep Researcher",
>     instructions="You are an investigative journalist.",
>     tools=tools,
> )
>
> async def main():
>     result = await Runner.run(
>         starting_agent=agent,
>         input=("Do a thorough DEEP research on Golden Gate Bridge"),
>     )
>     print(result.final_output)
>
> # Run the agent
> asyncio.run(main())
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> import { Agent, run } from '@openai/agents';
> import { OpenAIAgentsProvider } from '@composio/openai-agents';
>
> // Use a unique identifier for each user in your application
> const userId = 'user-k7334';
>
> // Initialize Composio toolset
> const composio = new Composio({
>   apiKey: 'your_composio_api_key',
>   provider: new OpenAIAgentsProvider(),
> });
>
> // Get all tools for the user
> const tools = await composio.tools.get(userId, {
>   toolkits: ['COMPOSIO_SEARCH'],
> });
>
> // Create an agent with the tools
> const agent = new Agent({
>   name: 'Deep Researcher',
>   instructions: 'You are an investigative journalist.',
>   tools,
> });
>
> // Run the agent
> const result = await run(agent, 'Do a thorough DEEP research on Golden Gate Bridge');
> console.log(result.finalOutput);
> ```

## Direct Tool Execution

If you just want to call a tool without using any framework or LLM provider, you can use the `execute` method directly.

> [!WARNING]
>
> **A toolkit version is required for direct execution** — calling `tools.execute()` without one raises `ToolVersionRequiredError`, and `"latest"` alone is not accepted here. Two ways to satisfy it:
>
> * **An LLM or agent consumes the outputs:** keep `"latest"` and pass `dangerously_skip_version_check=True` (TypeScript: `dangerouslySkipVersionCheck: true`) on the execute call — you always run the newest tools, and the flag's name is the reminder that output schemas can change between releases.
> * **Your code parses the outputs:** pin a dated version: look it up in the [Toolkits catalog](https://composio-preview.mintlify.site/toolkits.md) or from the SDK (see [Pin a version](#pin-a-version)), and pass it at SDK initialization or per call via `version`.
>
> See [toolkit versioning](https://composio-preview.mintlify.site/docs/tools-direct/toolkit-versioning.md) for the full tradeoffs.

> [!NOTE]
>
> **Finding a toolkit and tool:** browse the [Toolkits catalog](https://composio-preview.mintlify.site/toolkits.md) — each toolkit page lists its tool slugs and current version — or search by task from the CLI: `composio search "send an email"`. You can also [search tools by action keywords](https://composio-preview.mintlify.site/docs/tools-direct/fetching-tools.md#by-search-experimental) from the SDK.
>
> **Finding tool parameters and types:**
>
> **Platform UI**: [Auth Configs](https://dashboard.composio.dev/~/project/auth-configs?utm_source=docs\&utm_medium=content\&utm_campaign=docs-tools-direct-executing-tools) → Select your toolkit → Tools & Triggers → Select the tool to see its required and optional parameters
>
> **CLI**: For Python and TypeScript projects, run `composio generate` to generate types. [Learn more →](https://composio-preview.mintlify.site/docs/cli.md#generate-type-definitions)

### Pin a version

Pass `version` on the `tools.execute()` call to select a specific tool version. This overrides SDK initialization and environment defaults for that call without changing other executions.

Choose an available version from the [GitHub toolkit page](https://composio-preview.mintlify.site/toolkits/github) or [look it up with the SDK](https://composio-preview.mintlify.site/docs/tools-direct/toolkit-versioning.md#managing-versions). The examples below use `20250909_00`. Replace it with the version you have tested, and keep that string in your code or configuration.

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio(api_key="your_composio_api_key")
>
> result = composio.tools.execute(
>     "GITHUB_LIST_STARGAZERS",
>     user_id="user-k7334",
>     version="20250909_00",
>     arguments={"owner": "ComposioHQ", "repo": "composio", "page": 1, "per_page": 5},
> )
> print(result)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from "@composio/core";
>
> const composio = new Composio({ apiKey: "your_composio_api_key" });
>
> const result = await composio.tools.execute("GITHUB_LIST_STARGAZERS", {
>   userId: "user-k7334",
>   version: "20250909_00",
>   arguments: { owner: "ComposioHQ", repo: "composio", page: 1, per_page: 5 },
> });
> console.log(result);
> ```

> [tab] API
>
> ```bash theme={null}
> curl -X POST https://backend.composio.dev/api/v3.1/tools/execute/GITHUB_LIST_STARGAZERS \
>   -H "x-api-key: $COMPOSIO_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{"user_id": "user-k7334", "version": "20250909_00", "arguments": {"owner": "ComposioHQ", "repo": "composio", "page": 1, "per_page": 5}}'
> ```

A dated `version` satisfies the direct-execution version check. To set a default for all calls to a toolkit, configure [SDK initialization or environment variables](https://composio-preview.mintlify.site/docs/tools-direct/toolkit-versioning.md#configuration-methods).

### Use the latest version

If an LLM consumes the output and can handle schema changes, you can use `latest`. Direct execution requires the explicit opt-in shown below.

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> user_id = "user-k7334"
> # Configure toolkit versions at SDK level for every toolkit you execute.
> # Use "latest", or pin a version (see "Pin a version" above)
> composio = Composio(
>     api_key="your_composio_api_key",
>     toolkit_versions={"github": "latest"}
> )
>
> # Find available arguments for any tool in the Composio dashboard
> result = composio.tools.execute(
>     "GITHUB_LIST_STARGAZERS",
>     user_id=user_id,
>     arguments={"owner": "ComposioHQ", "repo": "composio", "page": 1, "per_page": 5},
>     # "latest" requires this opt-in; to pin instead, pass version (see "Pin a version" above)
>     dangerously_skip_version_check=True,
> )
> print(result)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from "@composio/core";
>
> const userId = "user-k7334";
> // Configure toolkit versions at SDK level for every toolkit you execute.
> // Use "latest", or pin a version (see "Pin a version" above)
> const composio = new Composio({
>     apiKey: "your_composio_api_key",
>     toolkitVersions: { github: "latest" }
> });
>
> // Find available arguments for any tool in the Composio dashboard
> const result = await composio.tools.execute("GITHUB_LIST_STARGAZERS", {
>   userId,
>   arguments: {
>     "owner": "ComposioHQ",
>     "repo": "composio",
>     "page": 1,
>     "per_page": 5
>   },
>   // "latest" requires this opt-in; to pin instead, pass `version` (see "Pin a version" above)
>   dangerouslySkipVersionCheck: true,
> });
> console.log('GitHub stargazers:', JSON.stringify(result, null, 2));
> ```

> [tab] API
>
> ```bash theme={null}
> # The version check is SDK-side; over REST, send "latest" (also the v3.1 default)
> curl -X POST https://backend.composio.dev/api/v3.1/tools/execute/GITHUB_LIST_STARGAZERS \
>   -H "x-api-key: $COMPOSIO_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{"user_id": "user-k7334", "version": "latest", "arguments": {"owner": "ComposioHQ", "repo": "composio", "page": 1, "per_page": 5}}'
> ```

### Proxy Execute

You can proxy requests to any supported toolkit API and let Composio inject the authentication state. This is useful when you need an API endpoint that isn't available as a predefined tool.

Proxy execute requires auth context. Pass `connected_account_id` / `connectedAccountId`, or provide `custom_connection_data` if you're supplying auth manually.

On projects with 2FA enabled, also pass `user_id` / `userId`. Composio checks it against the connected account and may reject a call that omits it.

The `endpoint` can be a relative path or absolute URL. Relative paths are resolved against the connected account's base URL. Absolute URLs are only accepted when they use the same scheme and registrable domain as that base URL. Cross-subdomain requests on the same registrable domain still work.

> [!WARNING]
>
> Prefer relative endpoints when possible. They resolve against the connected account's base URL and avoid same-domain validation issues.
>
> A relative endpoint is appended to the base URL, and many base URLs already include a path. Google Calendar's base URL is `https://www.googleapis.com/calendar/v3`, so pass `/users/me/calendarList`. Passing `/calendar/v3/users/me/calendarList` requests `/calendar/v3/calendar/v3/users/me/calendarList` and returns a `404`.

> [tab] Python
>
> ```python theme={null}
> # Send a proxy request to the endpoint
> response = composio.tools.proxy(
>     endpoint="/repos/composiohq/composio/issues/1",
>     method="GET",
>     connected_account_id="ca_jI6********",  # use connected account for github
>     parameters=[
>         {
>             "name": "Accept",
>             "value": "application/vnd.github.v3+json",
>             "type": "header",
>         },
>     ],
> )
>
> print(response)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> const composio = new Composio({ apiKey: 'your_api_key' });
> // Send a proxy request to the endpoint
> const { data } = await composio.tools.proxyExecute({
>     endpoint:'/repos/composiohq/composio/issues/1',
>     method: 'GET',
>     connectedAccountId: 'ca_jI6********', // use connected account for github
>     parameters:[
>         {
>             "name": "Accept",
>             "value": "application/vnd.github.v3+json",
>             "in": "header",
>         },
>     ],
> });
>
> console.log(data);
> ```

> [tab] API
>
> ```bash theme={null}
> # Send a proxy request to the endpoint
> curl -X POST https://backend.composio.dev/api/v3.1/tools/execute/proxy \
>   -H "x-api-key: $COMPOSIO_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "endpoint": "/repos/composiohq/composio/issues/1",
>     "method": "GET",
>     "connected_account_id": "ca_jI6********",
>     "parameters": [{"name": "Accept", "value": "application/vnd.github.v3+json", "type": "header"}]
>   }'
> ```

> [!NOTE]
>
> Need an API that isn't supported by any Composio toolkit, or want to extend an existing one? Learn how to [create session custom tools](https://composio-preview.mintlify.site/docs/extending-sessions/custom-tools-and-toolkits.md).

## Automatic File Handling

Automatic file handling is **off by default**. Enable it with `dangerouslyAllowAutoUploadDownloadFiles: true` (TypeScript) or `dangerously_allow_auto_upload_download_files=True` (Python). Once enabled, pass file paths to tools that accept files and get local paths back from tools that return files.

### File Upload

Pass local file paths, URLs, or File objects to tools that accept files. The SDK uploads the file to Composio's storage and converts it to the format the tool expects — you don't need to construct the file metadata object (`s3key`, `name`, `mimetype`) yourself.

> [tab] Python
>
> ```python theme={null}
> import os
> from composio import Composio
>
> composio = Composio(
>     api_key="your_api_key",
>     toolkit_versions={"googledrive": "latest", "gmail": "latest"},
>     dangerously_allow_auto_upload_download_files=True,
> )
>
> # Upload a local file to Google Drive
> result = composio.tools.execute(
>     slug="GOOGLEDRIVE_UPLOAD_FILE",
>     user_id="user-1235***",
>     arguments={"file_to_upload": os.path.join(os.getcwd(), "document.pdf")},
>     dangerously_skip_version_check=True,  # required when running "latest"
> )
>
> print(result)  # Print Google Drive file details
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> import path from 'path';
> const composio = new Composio({
>   apiKey: 'your_api_key',
>   toolkitVersions: { googledrive: 'latest' },
>   dangerouslyAllowAutoUploadDownloadFiles: true,
> });
> // Upload a local file to Google Drive
> const result = await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
>   userId: 'user-1235***',
>   arguments: {
>     file_to_upload: path.join(__dirname, 'document.pdf')
>   },
>   dangerouslySkipVersionCheck: true, // required when running "latest"
> });
>
> console.log(result.data);  // Contains Google Drive file details
> ```

This also works with public URLs. For example, to send a Gmail email with an attachment from a URL:

> [tab] Python
>
> ```python theme={null}
> result = composio.tools.execute(
>     slug="GMAIL_SEND_EMAIL",
>     user_id="user-1235***",
>     arguments={
>         "recipient_email": "recipient@example.com",
>         "subject": "Report attached",
>         "body": "Please find the report attached.",
>         "attachment": "https://example.com/report.pdf",
>     },
>     dangerously_skip_version_check=True,  # required when running "latest"
> )
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> const composio = new Composio({
>   apiKey: 'your_api_key',
>   toolkitVersions: { googledrive: 'latest', gmail: 'latest' },
>   dangerouslyAllowAutoUploadDownloadFiles: true,
> });
> const result = await composio.tools.execute('GMAIL_SEND_EMAIL', {
>   userId: 'user-1235***',
>   arguments: {
>     recipient_email: 'recipient@example.com',
>     subject: 'Report attached',
>     body: 'Please find the report attached.',
>     attachment: 'https://example.com/report.pdf',
>   },
>   dangerouslySkipVersionCheck: true, // required when running "latest"
> });
> ```

### File Download

When tools return files, Composio downloads them to the local directory and provides the file path in the response:

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio(
>     api_key="your_api_key",
>     toolkit_versions={"googledrive": "latest"},
>     dangerously_allow_auto_upload_download_files=True,
>     file_download_dir="./downloads",  # Optional: Specify download directory
> )
>
> result = composio.tools.execute(
>     "GOOGLEDRIVE_DOWNLOAD_FILE",
>     user_id="user-1235***",
>     arguments={"file_id": "your_file_id"},
>     dangerously_skip_version_check=True,  # required when running "latest"
> )
>
> # Result includes local file path
> print(result)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> const composio = new Composio({
>   apiKey: 'your_api_key',
>   toolkitVersions: { googledrive: 'latest' },
>   dangerouslyAllowAutoUploadDownloadFiles: true,
> });
> // Download a file from Google Drive
> const result = await composio.tools.execute('GOOGLEDRIVE_DOWNLOAD_FILE', {
>     userId: 'user-1235***',
>     arguments: {
>       file_id: 'your_file_id'
>     },
>     dangerouslySkipVersionCheck: true, // required when running "latest"
>   });
>
> // Result includes local file path
> console.log(result);
> ```

Python names each downloaded file after the name in the tool response, made safe to write first: characters Windows reserves become `_`, an over-long name is truncated with its extension kept, and trailing dots and spaces are dropped. A name any of those rules changed also carries a short digest of the original, so two names that clean up the same way stay distinct. A name that can't be written at all, one containing a NUL byte or with nothing usable left, fails the download instead. An existing file in the download directory is never replaced — the new download gets a number before its extension, so a second `report.pdf` lands as `report-1.pdf`. TypeScript names automatic downloads after the tool slug and a timestamp instead, so its names are already unique.

Automatic S3 downloads stop at 100 MiB, even when the server omits or reports an incorrect `Content-Length`. Python removes partial files for transport and filesystem failures and raises `ErrorDownloadingFile`; oversized responses raise `ResponseTooLargeError`. In TypeScript, failed automatic S3 downloads return `file_downloaded: false`. `RemoteFile` connection failures and streamed-body failures raise `RemoteFileDownloadError`.

URL-based file fetches validate the resolved address at each redirect and reject internal, reserved, and transition-network address ranges. Both SDKs follow standard HTTP redirect method and body rules and strip credentials on cross-origin redirects.

## Security for local file paths

Automatic upload reads local paths (or uses them in `files.upload`) and sends file content to Composio storage. To reduce the chance of **accidentally uploading secrets** (SSH keys, cloud credentials, `.env` files, or assistant project folders), the SDK checks local paths against a **default denylist** of path segments and file-name patterns. **HTTP/HTTPS URLs and `File` objects are not matched like local path strings**; only local string paths go through this check.

> [!WARNING]
>
> Matching both path forms requires `@composio/core` 0.17.1 or later (TypeScript) or a `composio` release newer than 0.20.0 (Python). Earlier versions check only the symlink-resolved path. In those versions, a layout such as `~/.claude -> /state/claude` is not protected.

When `sensitiveFileUploadProtection` (TypeScript) or `sensitive_file_upload_protection` (Python) is enabled, each path is matched **twice**: once as written and once after resolving symlinks. A symlink can hide a denied name in either direction. For example, `~/link -> ~/nested/.aws/creds` hides `.aws` from the path you wrote, while `~/.claude -> /state/claude` hides `.claude` from the resolved target. Dotfile managers such as chezmoi, stow, and yadm can produce the second layout.

Matching both forms blocks these common single-symlink cases. Only the path as written and its fully resolved target are compared, so treat the denylist as a guardrail against accidental uploads, not a security boundary against a determined attacker.

> [!WARNING]
>
> Disabling protection or wiring a hook that always approves paths can allow **exfiltration of sensitive files** if an LLM or malicious input points at credential locations. Prefer keeping protection on, adding [`fileUploadPathDenySegments`](https://composio-preview.mintlify.site/reference/sdk-reference/typescript/composio) (TypeScript) / `file_upload_path_deny_segments` (Python) for your own secret directories, and using a [`beforeFileUpload`](https://composio-preview.mintlify.site/reference/sdk-reference/typescript/composio) / `before_file_upload` hook for auditing or strict allowlists. On Python, you can use the `@before_file_upload` decorator with `modifiers=[...]` the same way as `@before_execute` — see [Before file upload (Python)](https://composio-preview.mintlify.site/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.md#before-file-upload-python) on the before-execution modifiers page.

**Constructor options (defaults protect sensitive locations):**

> [tab] Python
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio(
>     api_key="your_composio_api_key",
>     sensitive_file_upload_protection=True,
>     file_upload_path_deny_segments=("internal-only-secrets",),
> )
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
>
> const composio = new Composio({
>   apiKey: 'your_composio_api_key',
>   // default true — block paths under built-in segments (e.g. .ssh, .aws) and risky basenames
>   sensitiveFileUploadProtection: true,
>   // optional: extra path *components* anywhere in the path (as written or symlink-resolved),
>   // merged with the built-in list
>   fileUploadPathDenySegments: ['internal-only-secrets'],
> });
> ```

**Per-execution upload hook** (run after the path is chosen but before read/upload; return a new path, `false` to abort, or throw). TypeScript passes `beforeFileUpload` on the **third** argument to `tools.execute`. In Python, add **`@before_file_upload`** functions to the `modifiers` list for `get` / `execute` (see [Before file upload (Python)](https://composio-preview.mintlify.site/docs/tools-direct/modify-tool-behavior/before-execution-modifiers.md#before-file-upload-python)).

> [tab] Python
>
> ```python theme={null}
> import os
> from composio import Composio, before_file_upload
>
> # New form: take a single ``context`` arg; ``context["source"]`` is "path"
> # or "url". The legacy ``(path, tool, toolkit)`` 3-arg form is still accepted.
> @before_file_upload(tools=["GOOGLEDRIVE_UPLOAD_FILE"])
> def audit_path(context) -> str | bool:
>     if context["source"] != "path":
>         return context["path"]
>     # ...audit context["path"]...
>     return context["path"]
>
> composio = Composio(api_key="your_api_key", toolkit_versions={"googledrive": "latest"})
>
> composio.tools.execute(
>     "GOOGLEDRIVE_UPLOAD_FILE",
>     {"file_to_upload": os.path.join(os.getcwd(), "document.pdf")},
>     user_id="user-4235***",
>     dangerously_skip_version_check=True,  # required when running "latest"
>     modifiers=[audit_path],
> )
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Composio, type beforeFileUploadModifier } from '@composio/core';
> import path from 'node:path';
> const composio = new Composio({
>   apiKey: 'your_api_key',
>   toolkitVersions: { googledrive: 'latest' },
> });
> // ctx.source is 'path' | 'url' | 'file' — useful if you only want to audit
> // local paths and let URLs / File objects pass through unchanged.
> const beforeFileUpload: beforeFileUploadModifier = async ctx => {
>   if (ctx.source !== 'path') return ctx.path;
>   // ...audit ctx.path...
>   return ctx.path;
> };
> await composio.tools.execute(
>   'GOOGLEDRIVE_UPLOAD_FILE',
>   {
>     userId: 'user-4235***',
>     arguments: { file_to_upload: path.join(__dirname, 'document.pdf') },
>     dangerouslySkipVersionCheck: true, // required when running "latest"
>   },
>   { beforeFileUpload }
> );
> ```

**Errors:** `ComposioSensitiveFilePathBlockedError` / `SensitiveFilePathBlockedError` when a path is blocked; `ComposioFileUploadAbortedError` / `FileUploadAbortedError` when the hook returns `false` (or equivalent abort).

### Automatic file handling (off by default)

Both SDKs ship with automatic file handling **off**. Opt in with `dangerouslyAllowAutoUploadDownloadFiles: true` (TypeScript) or `dangerously_allow_auto_upload_download_files=True` (Python). Even with the flag enabled, **local paths must resolve inside an allowlisted directory** — see the matrix in the [legacy auto-upload removal changelog](https://composio-preview.mintlify.site/docs/changelog/2026/04/24) for the full `fileUploadDirs` / `file_upload_dirs` semantics.

When auto-handling is off, handle the staging yourself.

> [tab] Python
>
> The Python SDK does not expose a top-level manual-staging API. Either:
>
> 1. Enable auto-handling and configure `file_upload_dirs` to cover the directories your code reads from:
>
> ```python theme={null}
> from composio import Composio
>
> composio = Composio(
>     api_key="your_composio_key",
>     toolkit_versions={"googledrive": "latest"},
>     dangerously_allow_auto_upload_download_files=True,
>     file_upload_dirs=["/srv/agent/uploads", "~/.composio/temp"],
> )
> ```
>
> 2. Or keep auto-handling off and pass an already-staged `{ "name", "mimetype", "s3key" }` dict directly into `tools.execute`. Pre-stage your files via your own pipeline (or an upstream tool) and inject the descriptor:
>
> ```python theme={null}
> result = composio.tools.execute(
>     "GOOGLEDRIVE_UPLOAD_FILE",
>     user_id="user-1",
>     arguments={"file_to_upload": prestaged_descriptor},
>     dangerously_skip_version_check=True,  # required when running "latest"
> )
> ```

> [tab] TypeScript
>
> With `dangerouslyAllowAutoUploadDownloadFiles: false` (the default), call `composio.files.upload(...)` to stage paths/URLs explicitly. That call bypasses `fileUploadDirs` by design — the caller controls the path:
>
> ```typescript theme={null}
> import { Composio } from '@composio/core';
> import path from 'path';
> const composio = new Composio({
>   apiKey: process.env.COMPOSIO_API_KEY,
>   toolkitVersions: { googledrive: 'latest' },
>   // Default: dangerouslyAllowAutoUploadDownloadFiles is false; set true only to opt in
> });
>
> // Stage manually using composio.files API
> const fileData = await composio.files.upload({
>   file: path.join(__dirname, 'document.pdf'),
>   toolSlug: 'GOOGLEDRIVE_UPLOAD_FILE',
>   toolkitSlug: 'googledrive'
> });
>
> // Then pass the { name, mimetype, s3key } descriptor into tools.execute
> await composio.tools.execute('GOOGLEDRIVE_UPLOAD_FILE', {
>   userId: 'user-1',
>   arguments: { file_to_upload: fileData },
>   dangerouslySkipVersionCheck: true, // required when running "latest"
> });
> ```

## Next

> [card] [Fetching tools](https://composio-preview.mintlify.site/docs/tools-direct/fetching-tools.md)
>
> Fetch and filter tools, inspect schemas, and search semantically
