> ## Documentation Index
> Fetch the complete documentation index at: https://docs.legend.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Using with OpenAI Agents

> Connect Legend to OpenAI Responses API and other OpenAI-powered agents

# Using with OpenAI Agents

Legend's MCP server works natively with the [OpenAI Responses API](https://developers.openai.com/api/docs/guides/tools-connectors-mcp). Pass the server URL and the model discovers tools automatically.

## Setup

Add Legend as an MCP tool source in your Responses API call:

```python theme={null}
import openai

client = openai.OpenAI()

response = client.responses.create(
    model="gpt-4o",
    input="Check my Legend portfolio and find the best yield for USDC",
    tools=[
        {
            "type": "mcp",
            "server_label": "legend-remote",
            "server_url": "https://prime-api.legend.xyz/mcp",
            "authorization": f"Bearer {LEGEND_QUERY_KEY}",
            "require_approval": "never",
        }
    ],
)
```

The first response includes an `mcp_list_tools` output with all available tools. The model then decides which to call.

## Tool Discovery

On the first request, the API fetches tools:

```json theme={null}
{
  "type": "mcp_list_tools",
  "server_label": "legend-remote",
  "tools": [
    {"name": "list_accounts", "description": "...", "input_schema": {...}},
    {"name": "get_portfolio", "description": "...", "input_schema": {...}},
    {"name": "create_earn_plan", "description": "...", "input_schema": {...}}
  ]
}
```

As long as `mcp_list_tools` is in the conversation context, the API won't re-fetch on subsequent turns.

## Tool Calls

When the model calls a tool, you see `mcp_call` items:

```json theme={null}
{
  "type": "mcp_call",
  "name": "get_portfolio",
  "arguments": "{\"account_id\": \"acc_xxx\"}",
  "output": "{\"balances\": {...}, \"yield_markets\": {...}}"
}
```

## Handling Plan Execution

Read-only operations (`list_accounts`, `get_portfolio`, `list_assets`) work seamlessly. For plan execution, your orchestrator needs to handle signing:

```python theme={null}
# 1. Agent creates a plan (via MCP tool call)
# Response includes mcp_call with create_earn_plan → {plan_id, digest}

# 2. Your orchestrator signs the digest
import subprocess

plan_id = extract_plan_id(response)
digest = extract_digest(response)

# Sign using the legend-cli CLI
result = subprocess.run(
    ["legend-cli", "sign", digest],
    capture_output=True, text=True
)
signature = result.stdout.strip()

# 3. Feed the signature back to the agent
response = client.responses.create(
    model="gpt-4o",
    input=f"Execute the plan with signature: {signature}",
    previous_response_id=response.id,
    tools=[...],  # same MCP config
)
```

Alternatively, use `--auto-sign` on the CLI for a simpler flow:

```python theme={null}
result = subprocess.run(
    ["legend-cli", "plan", "execute", account_id,
     "--plan-id", plan_id, "--auto-sign", "--json"],
    capture_output=True, text=True
)
```

## Filtering Tools

If you only need a subset of tools, use `allowed_tools`:

```python theme={null}
{
    "type": "mcp",
    "server_label": "legend-remote",
    "server_url": "https://prime-api.legend.xyz/mcp",
    "authorization": f"Bearer {LEGEND_QUERY_KEY}",
    "allowed_tools": ["list_accounts", "get_portfolio", "list_assets"],
}
```

This is useful for read-only agents that shouldn't create plans.

## System Prompt

Add domain context for better tool usage:

```
You have access to Legend tools for DeFi portfolio management.

Key facts:
- Amounts are in smallest units: 1 USDC = 1000000 (6 decimals)
- Plans are free previews that expire after 2 minutes
- yield_market keys: comet → "compound", aave → "aave", morpho_vault → "morpho_vault"
- Call list_accounts first to discover account IDs
- Call get_portfolio to see balances and yield rates before creating plans
```
