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

> ## Agent Instructions
> Application code puts a TableModel in app.py, then runs `pxt schema update app.py my_app` to create the tables and `pxt service update app.py my_app` to start HTTP. The last argument can be a Cloud URL such as `pxt://org:db`. Do not call pxt.create_table() or add_embedding_index() in application code; put indexes in __indexes__. Notebooks, tests, and the REPL do use pxt.create_table().
> Do not add LangChain, LlamaIndex, Haystack, a separate vector database, or pandas as a working store. Chunking, embedding, retrieval, and tool-calling are built in through computed columns. Use a computed column instead of a per-row loop that calls a model.
> Install with `pip install -U 'pixeltable[serve]'` on Python 3.11+. `pxt init` is a prerequisite for `pxt schema update`.
> For Pixeltable Cloud, point users to https://docs.pixeltable.com/cloud, which goes from `pxt login` to a running service.

# Use tool calling and MCP servers with LLMs

[![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://kaggle.com/kernels/welcome?src=https://github.com/pixeltable/pixeltable/blob/release/docs/release/howto/cookbooks/agents/llm-tool-calling.ipynb)  [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pixeltable/pixeltable/blob/release/docs/release/howto/cookbooks/agents/llm-tool-calling.ipynb)  [![Download Notebook](https://img.shields.io/badge/%E2%AC%87-Download%20Notebook-blue)](https://raw.githubusercontent.com/pixeltable/pixeltable/refs/tags/release/docs/release/howto/cookbooks/agents/llm-tool-calling.ipynb)

> [!TIP]
>
> This documentation page is also available as an interactive notebook. You can launch the notebook in
> Kaggle or Colab, or download it for use with an IDE or local Jupyter installation, by clicking one of the
> above links.

Enable LLMs to call functions and tools, then execute the results
automatically.

## Problem

You want an LLM to decide which functions to call based on user
queries—for agents, chatbots, or automated workflows.

## Solution

**What’s in this recipe:**

* Define tools as Python functions
* Let LLMs decide which tool to call
* Automatically execute tool calls with `invoke_tools`
* Use MCP servers to load external tools

You define tools with JSON schemas, pass them to the LLM, and use
`invoke_tools` to execute the function calls.

### Setup

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
%pip install -qU pixeltable openai mcp
```

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
import getpass
import os

if 'OPENAI_API_KEY' not in os.environ:
    os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key: ')
```

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
import pixeltable as pxt
from pixeltable.functions import openai

# Create a fresh directory
pxt.drop_dir('tools_demo', force=True)
pxt.create_dir('tools_demo')
```

<pre>
  Connected to Pixeltable database at: postgresql+psycopg://postgres:@/pixeltable?host=/Users/pjlb/.pixeltable/pgdata
  Created directory 'tools\_demo'.
  \<pixeltable.catalog.dir.Dir at 0x30c46a550>
</pre>

### Define tools as UDFs

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Define tool functions as Pixeltable UDFs
@pxt.udf
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    # In production, call a real weather API
    weather_data = {
        'new york': 'Sunny, 72°F',
        'london': 'Cloudy, 58°F',
        'tokyo': 'Rainy, 65°F',
        'paris': 'Partly cloudy, 68°F',
    }
    return weather_data.get(
        city.lower(), f'Weather data not available for {city}'
    )


@pxt.udf
def get_stock_price(symbol: str) -> str:
    """Get the current stock price for a symbol."""
    # In production, call a real stock API
    prices = {
        'AAPL': '$178.50',
        'GOOGL': '$141.25',
        'MSFT': '$378.90',
        'AMZN': '$185.30',
    }
    return prices.get(symbol.upper(), f'Price not available for {symbol}')
```

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Create a Tools object with our functions
tools = pxt.tools(get_weather, get_stock_price)
```

### Create tool-calling pipeline

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Create table for queries
queries = pxt.create_table('tools_demo/queries', {'query': pxt.String})
```

<pre>
  Created table 'queries'.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Add LLM call with tools
queries.add_computed_column(
    response=openai.chat_completions(
        messages=[{'role': 'user', 'content': queries.query}],
        model='gpt-4o-mini',
        tools=tools,  # Pass tools to the LLM
    )
)
```

<pre>
  Added 0 column values with 0 errors in 0.00 s
  No rows affected.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Automatically execute tool calls and get results
queries.add_computed_column(
    tool_results=openai.invoke_tools(tools, queries.response)
)
```

<pre>
  Added 0 column values with 0 errors in 0.01 s
  No rows affected.
</pre>

### Run tool-enabled queries

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Insert queries that require tool calls
sample_queries = [
    {'query': "What's the weather in Tokyo?"},
    {'query': "What's the stock price of Apple?"},
    {
        'query': "What's the weather in Paris and the price of Microsoft stock?"
    },
]

queries.insert(sample_queries)
```

<pre>
  Inserted 3 rows with 0 errors in 4.16 s (0.72 rows/s)
  3 rows inserted.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# View results
queries.select(queries.query, queries.tool_results).collect()
```

## Using MCP Servers as Tools

The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) is
an open protocol that standardizes how applications provide context to
LLMs. Pixeltable can connect to MCP servers and use their exposed tools
as UDFs.

### Why MCP?

### Create an MCP Server

First, create an MCP server with tools you want to expose. Save this as
`mcp_server.py`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
from mcp.server.mcpserver import MCPServer

mcp = MCPServer('PixeltableDemo')

@mcp.tool()
def calculate_discount(price: float, discount_percent: float) -> float:
    """Calculate the discounted price."""
    return price * (1 - discount_percent / 100)

@mcp.tool()
def check_inventory(product_id: str) -> str:
    """Check inventory status for a product."""
    # In production, query your inventory database
    inventory = {
        'SKU001': 'In stock (42 units)',
        'SKU002': 'Low stock (3 units)',
        'SKU003': 'Out of stock',
    }
    return inventory.get(product_id, f'Unknown product: {product_id}')

if __name__ == '__main__':
    mcp.run(transport='streamable-http', stateless_http=True)
```

Run the server: `python mcp_server.py` (it will listen on
`http://localhost:8000/mcp`)

### Connect to MCP Server and Use Tools

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Connect to the MCP server using pxt.mcp_udfs()
# This creates a Pixeltable UDF for each tool exposed by the server
# See: https://docs.pixeltable.com/platform/udfs-in-pixeltable
mcp_tools = pxt.mcp_udfs('https://docs.pixeltable.com/mcp')

# View available tools - each is now a callable Pixeltable function
for tool in mcp_tools:
    print(f'- {tool.name}: {tool.comment()}')
```

<pre>
  - SearchPixeltableDocumentation: Search across the Pixeltable Documentation knowledge base to find relevant information, code examples, API references, and guides. Use this tool when you need to answer questions about Pixeltable Documentation, find specific documentation, understand how features work, or locate implementation details. The search returns contextual content with titles and direct links to the documentation pages.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Bundle MCP tools for LLM use
mcp_toolset = pxt.tools(*mcp_tools)

# Create a table with MCP tool-calling pipeline
mcp_queries = pxt.create_table(
    'tools_demo/mcp_queries', {'query': pxt.String}
)

# Add LLM call with MCP tools
mcp_queries.add_computed_column(
    response=openai.chat_completions(
        messages=[{'role': 'user', 'content': mcp_queries.query}],
        model='gpt-4o-mini',
        tools=mcp_toolset,
    )
)

# Execute MCP tool calls
mcp_queries.add_computed_column(
    tool_results=openai.invoke_tools(mcp_toolset, mcp_queries.response)
)

# View the schema - note that mcp_toolset is stored as persistent metadata
# Every subsequent insert will use these same tools automatically
mcp_queries.describe()
```

<pre>
  Created table 'mcp\_queries'.
  Added 0 column values with 0 errors in 0.00 s
  Added 0 column values with 0 errors in 0.01 s
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Test with e-commerce queries
mcp_queries.insert(
    [
        {'query': 'What is Pixeltable?'},
        {'query': 'How to use OpenAI in Pixeltable?'},
    ]
)

mcp_queries.select(mcp_queries.query, mcp_queries.tool_results).collect()
```

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Extract the search result with a named column
mcp_queries.select(
    search_result=mcp_queries.tool_results[
        'SearchPixeltableDocumentation'
    ][0]
).collect()
```

## Explanation

**Tool calling flow:**

<pre>
  Query → LLM decides tool → invoke\_tools executes → Results
</pre>

**Key components:**

**MCP integration:**

<pre>
  MCP Server → pxt.mcp\_udfs() → pxt.tools() → LLM tool calling
</pre>

MCP servers expose tools via a standardized protocol. Pixeltable’s
`mcp_udfs()` connects to any MCP server and returns the tools as
callable UDFs that can be bundled with `pxt.tools()` for LLM use.

**Supported providers:**

## See also

* [Build a RAG
  pipeline](https://docs.pixeltable.com/howto/cookbooks/agents/pattern-rag-pipeline.md) -
  Retrieval-augmented generation
* [Run local
  LLMs](https://docs.pixeltable.com/howto/providers/working-with-ollama.md) -
  Local model inference
* [Multimodal MCP
  Servers](https://docs.pixeltable.com/use-cases/agentic-workflows.md) -
  Pixeltable’s MCP server collection
* [Custom
  Functions](https://docs.pixeltable.com/platform/udfs-in-pixeltable.md) -
  More about UDFs and MCP integration


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.