Agents code examples¶
Here are some of examples of simple agents using Tinybird's MCP Server:
- They are based on the web analytics project but you can adapt it to your own project by using your
TINYBIRD_TOKEN. - Model and libraries set up (such as API keys and other environmenta variables) is omitted
Building an agent? Want to know which LLM generates best SQL queries? Explore the results in the LLM Benchmark.
Code Snippets¶
Basic Query Execution with Pydantic AI¶
import os
from dotenv import load_dotenv
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP
import asyncio
load_dotenv()
tinybird_token = os.getenv('TINYBIRD_TOKEN')
SYSTEM_PROMPT = "YOUR SYSTEM PROMPT"
async def main():
tinybird = MCPServerStreamableHTTP(
f"https://mcp.tinybird.co?token={tinybird_token}",
timeout=120,
)
agent = Agent(
model="anthropic:claude-4-opus-20250514", # use your favorite model
mcp_servers=[tinybird],
system_prompt=SYSTEM_PROMPT
)
async with agent.run_mcp_servers():
result = await agent.run("top 5 pages with the most visits in the last 24 hours")
print(result.output)
asyncio.run(main())
Basic Query Execution with Agno¶
from agno.agent import Agent
from agno.models.anthropic import Claude
from agno.tools.mcp import MCPTools
import asyncio
import os
tinybird_api_key = os.getenv("TINYBIRD_TOKEN")
SYSTEM_PROMPT = "YOUR SYSTEM PROMPT"
async def main():
async with MCPTools(
transport="streamable-http",
url=f"https://mcp.tinybird.co?token={tinybird_api_key}",
timeout_seconds=120) as mcp_tools:
agent = Agent(
model=Claude(id="claude-4-opus-20250514"),
tools=[mcp_tools], # use your favorite model
instructions=SYSTEM_PROMPT
)
await agent.aprint_response("top 5 pages with the most visits in the last 24 hours", stream=True)
if __name__ == "__main__":
asyncio.run(main())
Basic Query Execution with Vercel AI SDK¶
import { anthropic } from "@ai-sdk/anthropic";
import {
generateText,
experimental_createMCPClient as createMCPClient,
type Message,
} from "ai";
import {
StreamableHTTPClientTransport,
} from "@modelcontextprotocol/sdk/client/streamableHttp";
import * as dotenv from 'dotenv';
dotenv.config();
const SYSTEM_PROMPT = "YOUR SYSTEM PROMPT"
async function main() {
const messages: Message[] = [{
id: "1",
role: "user",
content: "top 5 pages with more visits in the last 24 hours"
}];
const url = new URL(
`https://mcp.tinybird.co?token=${process.env.TINYBIRD_TOKEN}`
);
const mcpClient = await createMCPClient({
transport: new StreamableHTTPClientTransport(url, {
sessionId: "session_123",
}),
});
const tbTools = await mcpClient.tools();
const result = await generateText({
model: anthropic("claude-3-7-sonnet-20250219"), // use your favorite model
messages,
maxSteps: 5,
tools: {...tbTools},
system: SYSTEM_PROMPT
});
console.log(result.text);
}
main();
Advanced Analytics with OpenAI Agents SDK¶
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp
SYSTEM_PROMPT = """
You are a data analyst. When analyzing user behavior:
1. First list available endpoints to understand what data is available
2. Use appropriate endpoints or execute_query for analysis
3. Provide insights with specific numbers and trends
4. Suggest actionable recommendations
"""
async def analyze_user_behavior():
try:
server = MCPServerStreamableHttp(
name="tinybird",
params={
"url": "https://mcp.tinybird.co?token=TINYBIRD_TOKEN",
},
)
async with server:
agent = Agent(
name="user_behavior_analyst",
model="YOUR_FAVORITE_MODEL", # e.g., "openai:gpt-4"
mcp_servers=[server],
instructions=SYSTEM_PROMPT
)
result = await Runner.run(
agent,
input="""
Analyze our user engagement patterns:
1. What are the current weekly active user trends?
2. Which features are most popular?
3. Are there any concerning drops in engagement?
"""
)
print("Engagement Analysis:", result.final_output)
except Exception as e:
print(f"Analysis failed: {e}")
if __name__ == "__main__":
asyncio.run(analyze_user_behavior())
Real-time Dashboard Assistant¶
import asyncio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio
SYSTEM_PROMPT = "YOUR SYSTEM PROMPT"
async def dashboard_assistant():
server = MCPServerStdio(
command="npx",
args=["-y", "mcp-remote", "https://mcp.tinybird.co?token=TINYBIRD_TOKEN"],
)
agent = Agent(
name="dashboard_assistant",
model=MODEL, # e.g. "anthropic:claude-3-5-sonnet-20241022",
mcp_servers=[server],
system_prompt=SYSTEM_PROMPT
)
async with agent.run_mcp_servers():
while True:
try:
user_question = input("\nAsk about your data (or 'quit' to exit): ")
if user_question.lower() == 'quit':
break
result = await agent.run(user_question)
print(f"Assistant: {result.output}")
except KeyboardInterrupt:
break
except Exception as e:
print(f"Error processing question: {e}")
if __name__ == "__main__":
asyncio.run(dashboard_assistant())
Example prompts¶
Use the prompts from the links below as the SYSTEM_PROMPT value in the snippets to build analytics agents for your data.
Tinybird organization metrics¶
Build analytics agents that report summaries on your organization metrics using service data sources.
Configure the MCP Server with an Organization Admin Token. You can manage your Tokens in the Tinybird UI.
https://mcp.tinybird.co?token={organization_admin_token}
- CPU spikes: Analyzes CPU spikes in your dedicated cluster and finds culprits.
- Requests summary: Reports a summary of the requests in your Organization for a given date range.
- Ingestion summary: Reports a summary of ingestion in your Organization for a given date range.
- Storage summary: Reports a summary of storage in your Organization for a given date range.
Tinybird workspace metrics¶
Build analytics agents that report summaries on metrics for a specific Workspace using service data sources.
Configure the MCP server with a Workspace Admin Token. You can manage your Tokens in the Tinybird UI.
https://mcp.tinybird.co?token={admin_token}
- MCP usage: Reports the most-called Endpoints for a given Workspace by agents using MCP.
Analytics agents over your data¶
Every Endpoint in a Workspace is published as an MCP tool. Use a resource-scoped token to create analytics agents for your data.
Some examples:
- PagerDuty incidents: Summarizes PagerDuty incidents
- Plain support summaries: Summarizes the most important Plain support issues
- Vercel logs: Summarizes errors and metrics from your Vercel application logs
- Web analytics: Summarizes your web analytics metrics.
Next steps¶
- Learn best practices to build analytics agents
- Check this repository for more examples