# Connecting Snowflake Cortex Code to Treasure AI

[Snowflake Cortex Code](https://docs.snowflake.com/en/user-guide/cortex-code/cortex-code-cli) is Snowflake's CLI coding agent. Connect it to Treasure AI through the Model Context Protocol (MCP) to query databases, manage parent segments and journeys, or run [Treasure AI Studio](/products/ai-studio/overview) Actions and chats from your terminal.

You can connect Snowflake Cortex Code to Treasure AI using either or both of two MCP integration patterns:

- **[MCP Server (Platform)](/getting-started/ai/mcp-server-platform) (`tdx mcp`)**: Runs the [Treasure Code (`tdx`) CLI](/treasure-code/) locally over `stdio`. Cortex Code calls `tdx_search` and `tdx_run` to query databases, inspect schemas, and manage segments, journeys, and workflows directly against Treasure AI APIs.
- **[Treasure AI Studio MCP Endpoint](/products/ai-studio/agent-channels/mcp-endpoints)**: Connects over Streamable HTTP to the Treasure AI Studio Agent Gateway. Cortex Code delegates tasks to a shared work folder in Treasure AI Studio, runs saved Actions, and reads back the agent's answers.


## Which MCP Connection Should You Use?

| Aspect  | MCP Server (Platform) (`tdx mcp`)  | Treasure AI Studio MCP Endpoint  |
|  --- | --- | --- |
| **Best for** | Engineers querying tables, validating segment or journey YAML, and running CLI workflows from the terminal | Teams running saved Studio Actions, shared reports, and multi-turn Studio chats from Cortex Code |
| **Transport** | Local `stdio` process (`tdx mcp`) started by Cortex Code | Remote Streamable HTTP (`https://<Agent Gateway>/v1/mcp/<endpoint ID>`) |
| **Authentication** | Dedicated `tdx` profile stored in your system keychain (`TDX_PROFILE=cortex`) | Static Gateway Token (`Authorization: Bearer tasgwt_<secret>`) |
| **Runs as** | The Treasure AI user authenticated in your `cortex` profile | The MCP endpoint's designated executor in one shared work folder |
| **AI credit usage** | Snowflake AI Credits only (Treasure AI serves standard API requests) | Snowflake AI Credits (for Cortex Code) + Treasure AI Credits (for Studio chats and Actions) |
| **Tools exposed** | `tdx_run`, `tdx_search` | `list_work_folders`, `list_actions`, `run_action`, `start_chat`, `continue_chat`, `get_chat_result` |


You can register both MCP servers in Snowflake Cortex Code at the same time.

```mermaid
flowchart LR
    subgraph local["Option 1: MCP Server (Platform) — Local stdio"]
        C1["Snowflake Cortex Code"] -->|"stdio (TDX_PROFILE=cortex)"| TDX["tdx mcp"]
        TDX -->|"HTTPS (Keychain credentials)"| API["Treasure AI APIs<br/>Databases, Segments, Journeys, Workflows"]
    end
    subgraph remote["Option 2: Treasure AI Studio MCP — Remote HTTP"]
        C2["Snowflake Cortex Code"] -->|"Streamable HTTP<br/>Bearer tasgwt_..."| GW["AI Studio Agent Gateway"]
        GW -->|"Runs as executor"| WF["Shared Work Folder<br/>Saved Actions & Studio Chats"]
    end
```

## Prerequisites

| Requirement  | Details  |
|  --- | --- |
| **Snowflake account** | Your Snowflake user requires the `SNOWFLAKE.CORTEX_USER` or `SNOWFLAKE.CORTEX_AGENT_USER` database role |
| **Snowflake Cortex Code CLI** | [Snowflake Cortex Code CLI](https://docs.snowflake.com/en/user-guide/cortex-code/cortex-code-cli) installed and connected to your Snowflake account |
| **Node.js** *(for `tdx mcp`)* | Version 22.12 or later (see the [tdx Installation Guide](/treasure-code/guide/installation) for OS-specific setup) |
| **Treasure AI access** | For `tdx mcp`: API key or SSO access to the databases, segments, journeys, and workflows you plan to use. For a Studio MCP Endpoint: **Manage** access to a non-archived [shared work folder](/products/ai-studio/shared-folders) and permission under your account's endpoint creation policy |


## Option 1: Connect MCP Server (Platform) (`tdx mcp`)

Use this setup to run `tdx` commands from Cortex Code using your local credentials.

### Step 1: Install and Authenticate `tdx`

Install `@treasuredata/tdx` globally (requires Node.js 22.12 or later) and create a dedicated `cortex` profile so Cortex Code stays tied to a single Treasure AI account without affecting your default `tdx` profile:

```bash
npm install -g @treasuredata/tdx
tdx profile create cortex
tdx status --profile cortex
```

- If the prompt does not sign you in automatically, run `tdx auth setup --profile cortex`.
- For non-US regions, pass `--site eu01`, `--site ap01`, or `--site ap02` (for example, `tdx auth setup --profile cortex --site eu01`).
- For SSO authentication, include `--account-name <YOUR_ACCOUNT>`.
- Credentials are stored in your system credential store (macOS Keychain, Windows Credential Manager, or Linux Secret Service) rather than in plain-text configuration files.


### Step 2: Register `tdx` in Cortex Code

Register `tdx mcp` using either the `cortex` CLI or by editing `~/.snowflake/cortex/mcp.json`.

Option A: CLI Command
```bash
cortex mcp add tdx tdx mcp -e TDX_PROFILE=cortex
```

Option B: Edit mcp.json
Add the `tdx` server block to `~/.snowflake/cortex/mcp.json`:

```json
{
  "mcpServers": {
    "tdx": {
      "type": "stdio",
      "command": "tdx",
      "args": ["mcp"],
      "env": {
        "TDX_PROFILE": "cortex"
      }
    }
  }
}
```

### Step 3: Verify and Run Prompts

Check the registered server configuration, then launch Cortex Code:

```bash
cortex mcp get tdx
cortex
```

Do not pass --mode code
Start Cortex Code with plain `cortex`. Launching with `cortex --mode code` disables all MCP servers.

Inside the Cortex Code session, run `/mcp` to confirm `tdx` shows as `Connected` with 2 tools (`tdx_run` and `tdx_search`):

Ask Cortex Code to inspect or query your Treasure AI data:

- *"Use tdx to list my Treasure AI databases."*
- *"Show the tables in sample_datasets and describe one of them."*
- *"Count rows in sample_datasets.www_access grouped by HTTP method."*
- *"List my parent segments and the child segments under one of them."*


## Option 2: Connect a Treasure AI Studio MCP Endpoint

Use this setup to let Cortex Code list your shared work folder, trigger saved [Actions](/products/ai-studio/skills/actions), and run [Treasure AI Studio](/products/ai-studio/overview) chats over Streamable HTTP.

### Step 1: Create a Static-Token MCP Endpoint in Treasure AI Studio

Create an endpoint for the shared work folder you want Cortex Code to use. For full details on permissions and token management, see [Static-Token MCP Endpoints](/products/ai-studio/agent-channels/mcp-endpoints).

1. In Treasure AI Studio (Web or Desktop), open **Settings → Agent Channels** and select **New MCP Endpoint**.
2. Keep **Static token · shared executor** selected, enter a name (for example, `Snowflake Cortex Code`), and select **Next**.
3. Select the **Shared work folder** to publish and choose a token **Expiration** (7, 30, or 90 days, custom date, or no expiration).
4. Select **Create endpoint & issue first token**.
5. Copy both the **Connection URL** (`https://agent-gateway.<region>.treasure.ai/v1/mcp/<endpoint_id>`) and the **Authentication header** (`Authorization: Bearer tasgwt_<secret>`), check **I have stored the values**, and select **Done**.


Store the token immediately
The `tasgwt_` token is displayed only once. Store it in a password manager or your system credential store before closing the dialog. If you lose it, revoke the token and issue a new one on the endpoint's detail page.

### Step 2: Set the Token Environment Variable

Set the `TAS_TOKEN` environment variable in your shell so the token stays out of plain-text MCP configuration files.

macOS / Linux / WSL
```bash
export TAS_TOKEN="tasgwt_<YOUR_TOKEN>"
```

Persist the variable in your shell profile (`~/.bashrc` or `~/.zshrc`), or load it dynamically from your system credential manager.

Windows (PowerShell)
```powershell
$env:TAS_TOKEN = "tasgwt_<YOUR_TOKEN>"
```

### Step 3: Register the Studio Endpoint in Cortex Code

Paste the exact **Connection URL** copied from Treasure AI Studio (`https://agent-gateway.<REGION>.treasure.ai/v1/mcp/<YOUR_ENDPOINT_ID>`). Replace `<REGION>` with your Treasure AI Studio region (`us01` for US, `ap01` for Japan, `eu01` for Europe, or `ap02` for Korea) and `<YOUR_ENDPOINT_ID>` with your endpoint ID, without `< >` angle brackets.

Option A: Edit mcp.json (Recommended)
Editing `~/.snowflake/cortex/mcp.json` lets Cortex Code expand `${TAS_TOKEN}` from your shell environment at runtime without writing the secret to disk, and sets a 210-second timeout (`210000` ms) to accommodate Treasure AI Studio's 200-second wait per tool call:

```json
{
  "mcpServers": {
    "treasure-studio": {
      "type": "http",
      "url": "https://agent-gateway.<REGION>.treasure.ai/v1/mcp/<YOUR_ENDPOINT_ID>",
      "headers": {
        "Authorization": "Bearer ${TAS_TOKEN}"
      },
      "timeout": 210000
    }
  }
}
```

Option B: CLI Command
```bash
cortex mcp add treasure-studio "https://agent-gateway.<REGION>.treasure.ai/v1/mcp/<YOUR_ENDPOINT_ID>" \
  --transport http \
  -H "Authorization: Bearer $TAS_TOKEN"
```

When you pass `"$TAS_TOKEN"` in double quotes on the command line, your shell expands the token before Cortex Code writes `~/.snowflake/cortex/mcp.json`, storing the token in plain text in that file. Prefer Option A to keep the secret in environment variables or Keychain.

### Step 4: Verify and Run Studio Actions

Confirm the server is registered, then start Cortex Code from a terminal where `TAS_TOKEN` is exported:

```bash
cortex mcp list
cortex mcp get treasure-studio
cortex
```

Run `/mcp` inside the session to confirm `treasure-studio` is connected with 6 tools (`list_work_folders`, `list_actions`, `run_action`, `start_chat`, `continue_chat`, and `get_chat_result`), then test it with a prompt:

- *"Use treasure-studio to list my work folders and their Actions."*
- *"Run the Weekly Summary Action in treasure-studio."*
- *"Start a Studio chat that summarizes last week's campaign performance as a table."*


Each tool call waits up to 200 seconds. If a Studio task takes longer than 200 seconds, the tool returns `status: "running"` and a `chat_id`. Ask Cortex Code to poll `get_chat_result` with that `chat_id` rather than starting a duplicate run. For the complete tool schema and status codes, see [Connecting an MCP Client](/products/ai-studio/agent-channels/mcp-clients#the-tools).

## Guardrails and Operational Limits

Commands with production side effects (tdx mcp)
`tdx_run` can execute any `tdx` CLI command that your profile's user has permission to run, including commands that modify live CDP resources or trigger audience activations:

- **`tdx wf run`**: Starts a workflow attempt immediately.
- **`tdx journey resume`**: Resumes a paused journey and starts firing stage activations.
- **`tdx sg push` / `tdx journey push` / `tdx ps push`**: Updates live segment or journey configurations.


Always ask Cortex Code to run mutating commands with `--dry-run` first, or use read-only validation commands (`tdx wf validate`, `tdx sg validate`, `tdx journey validate`). Point the `cortex` profile at a sandbox account whenever possible.

- **Blocked `tdx` commands**: For security, `tdx mcp` blocks authentication (`tdx auth`), profile management (`tdx profile`), and recursive `tdx mcp` commands.
- **Studio MCP Endpoint limits**: A static-token endpoint publishes one shared work folder read-only, runs all chats in a temporary workspace that is discarded after the chat, allows up to 30 new chats per minute (`1` to `32,768` characters per message), and automatically declines clarifying questions from the agent (include all required inputs in your prompt).


## Troubleshooting

| Symptom  | Likely Cause  | Fix  |
|  --- | --- | --- |
| `no such file or directory` error when running `cortex mcp add` | Angle brackets (`< >`) were left around the endpoint ID, which the shell interprets as file redirection | Remove `< >` around the endpoint ID and wrap the URL in double quotes |
| `treasure-studio` or `tdx` is missing from `/mcp` | Cortex Code was started with `--mode code`, which disables MCP servers | Exit and start Cortex Code with plain `cortex` |
| `tdx` shows as failed in `/mcp` | Cortex Code cannot find `tdx` on its `PATH` (common when Node.js is managed by `nvm` or `fnm`) or Node.js is older than 22.12 | Put the full absolute path to `tdx` in `"command"` in `~/.snowflake/cortex/mcp.json`, and verify `node --version` is 22.12+ |
| `401 Unauthorized` from the Studio endpoint | `TAS_TOKEN` is unset in the current shell, expired, revoked, or belongs to a different endpoint | Confirm `TAS_TOKEN` is set in the shell where `cortex` was launched, or issue a new token in **Settings → Agent Channels** |
| `403 Forbidden` from the Studio endpoint | The endpoint is disabled, has no executor, or the executor lost access to the shared work folder | Check the endpoint status in **Settings → Agent Channels** and re-enable it or restore folder access |
| A Studio tool call returns `status: "running"` | The Studio task took longer than 200 seconds | Ask Cortex Code to call `get_chat_result` with the returned `chat_id` |


## Next Steps

- [MCP Server (Platform)](/getting-started/ai/mcp-server-platform) — reference for `tdx_run` and `tdx_search`
- [tdx mcp command reference](/treasure-code/commands/mcp) — full tool reference, blocked commands, and logs (`~/.cache/tdx/logs/tdx.log`)
- [Static-Token MCP Endpoints](/products/ai-studio/agent-channels/mcp-endpoints) — create and govern Treasure AI Studio endpoints
- [Connecting an MCP Client to Treasure AI Studio](/products/ai-studio/agent-channels/mcp-clients) — full reference for the six Studio MCP tools
- Connect a different tool: [Databricks Genie Code](/getting-started/ai/databricks-genie-code) · [Snowflake CoWork](/getting-started/ai/snowflake-cowork) · [Claude Code](/getting-started/ai/claude-code) · [OpenAI Codex](/getting-started/ai/openai-codex) · [VS Code and GitHub Copilot](/getting-started/ai/vscode-github-copilot) · [Cursor](/getting-started/ai/cursor)