# A/B Testing Assistant Source: https://docs.pylar.ai/examples/ab-testing-assistant Build an AI agent that analyzes experiments, determines statistical significance, and recommends winners ## Overview An A/B Testing Assistant powered by Pylar analyzes experiment data, calculates statistical significance, and provides clear recommendations on which variant performs better. ## What the Agent Needs to Accomplish The agent must: * Analyze A/B test results * Calculate statistical significance * Compare variant performance * Recommend winning variants * Track experiment progress * Identify significant differences ## How Pylar Helps Pylar enables the agent by: * **Unified Experiment View**: Combining experiment data, user behavior, and conversion data * **Statistical Analysis**: Automated significance calculations * **Real-time Monitoring**: Querying current experiment performance * **Clear Recommendations**: Data-driven variant recommendations ```mermaid theme={null} graph LR subgraph "Data Sources" EXPERIMENTS[Experiment Data] BEHAVIOR[User Behavior] CONVERSIONS[Conversions] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_results
calculate_significance
recommend_winner] AGENT[AB Testing Assistant] TEAM[Product Team] EXPERIMENTS --> PYLAR BEHAVIOR --> PYLAR CONVERSIONS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Manual statistical calculations * ❌ Complex experiment data aggregation * ❌ Time-consuming analysis * ❌ Limited real-time monitoring **Implementation Complexity**: \~4-5 weeks ### With Pylar **Benefits**: * ✅ Automated statistical analysis * ✅ Real-time experiment monitoring * ✅ Clear winner recommendations * ✅ Easy experiment tracking **Implementation Complexity**: \~5-6 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Experiment Platform** (A/B test data, variants) 2. **Connect Analytics** (User behavior, conversions) 3. **Connect Product Data** (Feature usage, engagement) ### Step 2: Create Experiment Views **Experiment Results View**: ```sql theme={null} CREATE VIEW experiment_results AS SELECT e.experiment_id, e.experiment_name, e.variant, COUNT(DISTINCT u.user_id) as participants, COUNT(DISTINCT CASE WHEN u.converted THEN u.user_id END) as conversions, (COUNT(DISTINCT CASE WHEN u.converted THEN u.user_id END) / NULLIF(COUNT(DISTINCT u.user_id), 0)) * 100 as conversion_rate, AVG(u.time_on_page) as avg_time_on_page, AVG(u.engagement_score) as avg_engagement FROM experiments.experiments e JOIN experiments.users u ON e.experiment_id = u.experiment_id GROUP BY e.experiment_id, e.experiment_name, e.variant; ``` ### Step 3: Create MCP Tools **Tool 1: Analyze Experiment** * `analyze_experiment(experiment_id: string)` **Tool 2: Check Statistical Significance** * `check_significance(experiment_id: string, confidence_level: number)` **Tool 3: Recommend Winner** * `recommend_winner(experiment_id: string)` **Tool 4: Monitor Experiment** * `monitor_experiment(experiment_id: string, check_interval: number)` ## Example Agent Interactions **User**: "What's the status of the homepage headline test?" **Agent**: "Homepage Headline Test Results: * Variant A: 12.5% conversion (2,450 participants) * Variant B: 14.8% conversion (2,380 participants) * Statistical Significance: 95% confidence * Winner: Variant B (18% improvement) * Recommendation: Deploy Variant B" ## Outcomes * **Decision Speed**: 60% faster test decisions * **Accuracy**: 95% confidence in recommendations * **Testing Efficiency**: 2x more tests run * **Conversion Improvement**: 15% average lift from tests ## Next Steps * [Marketing Campaign Optimizer Example](/examples/marketing-campaign-optimizer) * [Marketing Attribution Analyzer Example](/examples/marketing-attribution-analyzer) # Content Performance Analyzer Source: https://docs.pylar.ai/examples/content-performance-analyzer Build an AI agent that analyzes blog posts, content engagement, content ROI, and identifies top performers ## Overview A Content Performance Analyzer powered by Pylar analyzes blog posts, content engagement metrics, content ROI, and identifies top-performing content to inform content strategy. ## What the Agent Needs to Accomplish The agent must: * Analyze blog post performance * Track content engagement metrics * Calculate content ROI * Identify top-performing content * Recommend content topics * Track content trends over time ## How Pylar Helps Pylar enables the agent by: * **Unified Content View**: Combining blog data, analytics, and conversion data * **Real-time Analysis**: Querying current content performance * **ROI Calculation**: Automated content ROI calculations * **Trend Analysis**: Identifying content performance trends * **Recommendation Engine**: Data-driven content recommendations ```mermaid theme={null} graph LR subgraph "Data Sources" BLOG[Blog Posts] ANALYTICS[Analytics] CONVERSIONS[Conversions] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_performance
calculate_roi
recommend_topics] AGENT[Content Analyzer] TEAM[Content Team] BLOG --> PYLAR ANALYTICS --> PYLAR CONVERSIONS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple systems (CMS, analytics, CRM) * ❌ Manual content analysis * ❌ Difficult to correlate content with conversions * ❌ Time-consuming ROI calculations **Implementation Complexity**: \~4-5 weeks ### With Pylar **Benefits**: * ✅ Single endpoint for all content data * ✅ Automated performance analysis * ✅ Real-time ROI tracking * ✅ Easy content optimization **Implementation Complexity**: \~5-6 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect CMS** (Blog posts, content metadata) 2. **Connect Analytics** (Page views, engagement, time on page) 3. **Connect CRM** (Content-to-lead conversions) ### Step 2: Create Content Views **Content Performance View**: ```sql theme={null} CREATE VIEW content_performance AS SELECT c.post_id, c.title, c.category, c.publish_date, c.author, a.page_views, a.unique_visitors, a.avg_time_on_page, a.bounce_rate, l.leads_generated, l.conversions, -- Engagement score (a.page_views * 0.3 + a.unique_visitors * 0.4 + (a.avg_time_on_page / 60) * 0.3) as engagement_score, -- ROI (l.conversions * 100) / NULLIF(a.page_views, 0) as conversion_rate FROM cms.posts c LEFT JOIN analytics.page_metrics a ON c.post_id = a.post_id LEFT JOIN crm.content_leads l ON c.post_id = l.post_id; ``` ### Step 3: Create MCP Tools **Tool 1: Analyze Content Performance** * `analyze_content_performance(post_id: string, start_date: date, end_date: date)` **Tool 2: Get Top Performing Content** * `get_top_performing_content(metric: string, limit: number, category: string)` **Tool 3: Calculate Content ROI** * `calculate_content_roi(post_id: string, period: string)` **Tool 4: Recommend Content Topics** * `recommend_content_topics(based_on: string, limit: number)` ## Example Agent Interactions **User**: "What are our top performing blog posts?" **Agent**: "Top 5 Performing Posts: 1. '10 Ways to Improve Sales' - 45K views, 8% conversion rate, \$12K revenue 2. 'Customer Success Guide' - 32K views, 6.5% conversion, \$8.5K revenue 3. 'Product Feature Deep Dive' - 28K views, 5.2% conversion, \$6K revenue" ## Outcomes * **Content ROI**: 40% improvement * **Engagement**: 30% increase in average engagement * **Conversion Rate**: 25% improvement * **Content Strategy**: Data-driven topic selection ## Next Steps * [Marketing Campaign Optimizer Example](/examples/marketing-campaign-optimizer) * [A/B Testing Assistant Example](/examples/ab-testing-assistant) # Customer Churn Predictor Source: https://docs.pylar.ai/examples/customer-churn-predictor Build an AI agent that identifies at-risk customers and recommends retention actions using usage and engagement data ## Overview A Customer Churn Predictor agent powered by Pylar analyzes customer usage patterns, engagement metrics, support history, and billing data to identify customers at risk of churning and recommend proactive retention actions. ## What the Agent Needs to Accomplish The agent must: * Analyze customer usage patterns and engagement metrics * Track support ticket frequency and sentiment * Monitor billing and payment history * Identify churn risk indicators * Generate churn risk scores * Recommend specific retention actions * Track retention campaign effectiveness ## How Pylar Helps Pylar enables the agent by: * **Unified Customer Data**: Combining usage, engagement, support, and billing data * **Real-time Analysis**: Querying current customer behavior patterns * **Multi-Source Integration**: Joining data from product analytics, CRM, support, and billing systems * **Pattern Recognition**: SQL views identify churn indicators * **Actionable Insights**: Generating retention recommendations based on data ```mermaid theme={null} graph LR subgraph "Data Sources" ANALYTICS[Product Analytics] CRM[CRM] SUPPORT[Support] BILLING[Billing] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
calculate_churn_risk
get_usage_patterns
get_retention_actions] AGENT[Churn Predictor] TEAM[CS Team] ANALYTICS --> PYLAR CRM --> PYLAR SUPPORT --> PYLAR BILLING --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Data scattered across multiple systems (analytics, CRM, support, billing) * ❌ Complex ETL pipelines to combine data * ❌ Difficult to get real-time churn risk scores * ❌ Manual analysis of churn indicators * ❌ No unified customer view * ❌ Time-consuming to update models * ❌ Limited ability to track retention actions **Implementation Complexity**: * 4-5 different data source integrations * Complex data pipeline setup * Custom ML model development * Churn scoring infrastructure * \~6-8 weeks development time ### With Pylar **Benefits**: * ✅ Single endpoint for all customer data * ✅ Real-time churn risk calculation * ✅ Easy to update churn indicators * ✅ Unified customer 360 view * ✅ Built-in analytics on retention actions * ✅ Simple query-based risk scoring **Implementation Complexity**: * Connect 4-5 data sources (1.5 hours) * Create churn analysis views (3 hours) * Build MCP tools with AI (1.5 hours) * Connect to agent builder (15 minutes) * **Total: \~6-7 hours** ## Step-by-Step Implementation ### Step 1: Connect Data Sources Connect all customer data sources: 1. **Connect Product Analytics** (Usage metrics, feature adoption, engagement) 2. **Connect CRM** (Account data, contract info, renewal dates) 3. **Connect Support System** (Ticket history, satisfaction scores) 4. **Connect Billing System** (Payment history, invoices, subscription status) ### Step 2: Create Churn Analysis Views **Customer Engagement Score View**: ```sql theme={null} CREATE VIEW customer_engagement_score AS SELECT c.customer_id, c.customer_name, c.subscription_tier, c.contract_start_date, c.contract_end_date, DATEDIFF(CURRENT_DATE, c.contract_end_date) as days_until_renewal, -- Usage metrics u.active_days_last_30, u.features_used_count, u.total_actions_last_30, u.last_activity_date, DATEDIFF(CURRENT_DATE, u.last_activity_date) as days_since_last_activity, -- Support metrics s.ticket_count_last_30, s.avg_satisfaction_score, s.avg_resolution_time_hours, -- Billing metrics b.total_invoices, b.payment_failures_count, b.days_overdue, -- Engagement score calculation CASE WHEN u.active_days_last_30 >= 20 THEN 100 WHEN u.active_days_last_30 >= 15 THEN 75 WHEN u.active_days_last_30 >= 10 THEN 50 WHEN u.active_days_last_30 >= 5 THEN 25 ELSE 0 END as usage_score, CASE WHEN s.avg_satisfaction_score >= 4.5 THEN 100 WHEN s.avg_satisfaction_score >= 4.0 THEN 75 WHEN s.avg_satisfaction_score >= 3.5 THEN 50 ELSE 25 END as satisfaction_score FROM crm.customers c LEFT JOIN analytics.user_usage u ON c.customer_id = u.customer_id LEFT JOIN support.ticket_summary s ON c.customer_id = s.customer_id LEFT JOIN billing.payment_summary b ON c.customer_id = b.customer_id; ``` **Churn Risk Score View**: ```sql theme={null} CREATE VIEW churn_risk_score AS SELECT e.*, -- Risk indicators CASE WHEN e.days_since_last_activity > 30 THEN 1 ELSE 0 END as low_activity_flag, CASE WHEN e.ticket_count_last_30 > 5 THEN 1 ELSE 0 END as high_support_flag, CASE WHEN e.payment_failures_count > 0 THEN 1 ELSE 0 END as payment_issue_flag, CASE WHEN e.days_until_renewal < 30 THEN 1 ELSE 0 END as renewal_approaching_flag, -- Churn risk score (0-100, higher = more risk) ( (CASE WHEN e.days_since_last_activity > 30 THEN 30 ELSE 0 END) + (CASE WHEN e.active_days_last_30 < 10 THEN 25 ELSE 0 END) + (CASE WHEN e.ticket_count_last_30 > 5 THEN 20 ELSE 0 END) + (CASE WHEN e.payment_failures_count > 0 THEN 15 ELSE 0 END) + (CASE WHEN e.avg_satisfaction_score < 3.5 THEN 10 ELSE 0 END) ) as churn_risk_score, -- Risk level CASE WHEN ( (CASE WHEN e.days_since_last_activity > 30 THEN 30 ELSE 0 END) + (CASE WHEN e.active_days_last_30 < 10 THEN 25 ELSE 0 END) + (CASE WHEN e.ticket_count_last_30 > 5 THEN 20 ELSE 0 END) + (CASE WHEN e.payment_failures_count > 0 THEN 15 ELSE 0 END) + (CASE WHEN e.avg_satisfaction_score < 3.5 THEN 10 ELSE 0 END) ) >= 50 THEN 'High Risk' WHEN ( (CASE WHEN e.days_since_last_activity > 30 THEN 30 ELSE 0 END) + (CASE WHEN e.active_days_last_30 < 10 THEN 25 ELSE 0 END) + (CASE WHEN e.ticket_count_last_30 > 5 THEN 20 ELSE 0 END) + (CASE WHEN e.payment_failures_count > 0 THEN 15 ELSE 0 END) + (CASE WHEN e.avg_satisfaction_score < 3.5 THEN 10 ELSE 0 END) ) >= 25 THEN 'Medium Risk' ELSE 'Low Risk' END as risk_level FROM customer_engagement_score e; ``` **Retention Action Recommendations View**: ```sql theme={null} CREATE VIEW retention_actions AS SELECT r.*, CASE WHEN r.low_activity_flag = 1 THEN 'Send re-engagement email campaign' WHEN r.high_support_flag = 1 THEN 'Schedule success manager call' WHEN r.payment_issue_flag = 1 THEN 'Contact billing team for payment assistance' WHEN r.renewal_approaching_flag = 1 AND r.churn_risk_score > 30 THEN 'Offer renewal discount' WHEN r.avg_satisfaction_score < 3.5 THEN 'Request feedback and address concerns' ELSE 'Monitor closely' END as recommended_action, CASE WHEN r.churn_risk_score >= 50 THEN 'Urgent' WHEN r.churn_risk_score >= 25 THEN 'High Priority' ELSE 'Normal' END as action_priority FROM churn_risk_score r WHERE r.churn_risk_score > 20; ``` ### Step 3: Create MCP Tools with AI **Tool 1: Get Churn Risk Score** * Prompt: "Create a tool to get churn risk score for a customer by customer ID" * AI generates: `get_churn_risk(customer_id: string)` **Tool 2: List High-Risk Customers** * Prompt: "Create a tool to list customers with high churn risk scores" * AI generates: `get_high_risk_customers(risk_level: string, limit: number)` **Tool 3: Get Retention Recommendations** * Prompt: "Create a tool to get recommended retention actions for at-risk customers" * AI generates: `get_retention_recommendations(customer_id: string)` **Tool 4: Analyze Churn Patterns** * Prompt: "Create a tool to analyze churn patterns and identify common indicators" * AI generates: `analyze_churn_patterns(days_back: number, min_risk_score: number)` ### Step 4: Test and Publish 1. Test churn risk calculation 2. Verify high-risk customer identification 3. Validate retention recommendations 4. Publish tools 5. Connect to agent builder ## Example Agent Interactions ### Scenario 1: High-Risk Customer Identification **User**: "Show me customers at high risk of churning" **Agent** (using Pylar tools): 1. Calls `get_high_risk_customers("High Risk", 50)` 2. Analyzes results: * "I found 23 high-risk customers: * Acme Corp: 65 risk score, last active 42 days ago, 3 payment failures * TechCo: 58 risk score, 8 support tickets last month, low satisfaction * ..." ### Scenario 2: Retention Action Recommendation **User**: "What should we do about customer ID 12345?" **Agent** (using Pylar tools): 1. Calls `get_churn_risk("12345")` 2. Calls `get_retention_recommendations("12345")` 3. Responds: * "Customer 12345 has a 72 churn risk score (High Risk) * Indicators: No activity for 38 days, 6 support tickets, payment failure * Recommended action: Schedule success manager call + offer renewal discount * Priority: Urgent" ### Scenario 3: Churn Pattern Analysis **User**: "What are the common patterns in churned customers?" **Agent** (using Pylar tools): 1. Calls `analyze_churn_patterns(90, 50)` 2. Analyzes patterns: * "Common churn indicators in last 90 days: 1. 68% had no activity for 30+ days 2. 45% had payment failures 3. 52% had low satisfaction scores (less than 3.5) 4. 38% had 5+ support tickets" ## Outcomes ### Churn Prevention * **Early Detection**: 40% earlier identification of at-risk customers * **Retention Rate**: 25% improvement in customer retention * **Proactive Actions**: 3x increase in proactive retention outreach * **Churn Reduction**: 30% reduction in overall churn rate ### Data-Driven Decisions * **Risk Scoring**: Automated, real-time churn risk scores * **Action Recommendations**: Data-driven retention strategies * **Pattern Recognition**: Identification of common churn indicators * **Effectiveness Tracking**: Monitor retention campaign success ### Business Impact * **Revenue Protection**: Save \$500K+ in annual revenue through retention * **Customer Lifetime Value**: 20% increase in average CLV * **Customer Satisfaction**: Improved satisfaction through proactive outreach * **Team Efficiency**: 50% reduction in manual churn analysis time ## Best Practices 1. **Regular Monitoring**: Check churn risk scores weekly 2. **Action Follow-up**: Track retention action effectiveness 3. **Model Refinement**: Update risk indicators based on outcomes 4. **Communication**: Integrate with CRM for automatic outreach 5. **Analytics**: Use Evals to track agent churn prediction accuracy ## Next Steps * [Customer Support Agent Example](/examples/customer-support-agent) - Build a support agent * [Sales Assistant Example](/examples/sales-assistant) - Analyze sales pipeline * [Revenue Operations Agent Example](/examples/revenue-operations-agent) - Track revenue metrics # Customer Onboarding Assistant Source: https://docs.pylar.ai/examples/customer-onboarding-assistant Build an AI agent that tracks onboarding progress, identifies blockers, and provides personalized guidance ## Overview A Customer Onboarding Assistant powered by Pylar tracks customer progress through onboarding milestones, identifies potential blockers, and provides personalized guidance based on product usage, engagement patterns, and historical onboarding data. ## What the Agent Needs to Accomplish The agent must: * Track customer progress through onboarding milestones * Monitor feature adoption and usage patterns * Identify customers who are stuck or at risk * Provide personalized onboarding guidance * Recommend next steps based on customer profile * Analyze onboarding effectiveness and time-to-value ## How Pylar Helps Pylar enables the agent by: * **Unified Onboarding View**: Combining account data, usage metrics, and milestone tracking * **Real-time Progress**: Querying current onboarding status across all customers * **Pattern Recognition**: Identifying successful onboarding patterns * **Personalized Recommendations**: Tailoring guidance based on customer profile * **Effectiveness Analysis**: Measuring onboarding success metrics ```mermaid theme={null} graph LR subgraph "Data Sources" ACCOUNTS[Account Data] USAGE[Usage Metrics] MILESTONES[Milestones] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
track_progress
identify_blockers
recommend_steps] AGENT[Onboarding Assistant] CUSTOMERS[Customers] ACCOUNTS --> PYLAR USAGE --> PYLAR MILESTONES --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> CUSTOMERS style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Data scattered across product analytics, CRM, and onboarding tools * ❌ Manual tracking of onboarding progress * ❌ Difficult to identify at-risk customers * ❌ No unified view of onboarding effectiveness * ❌ Time-consuming to generate personalized recommendations * ❌ Limited ability to correlate onboarding with outcomes **Implementation Complexity**: * 3-4 different system integrations * Custom onboarding tracking logic * Manual analysis of progress * Complex correlation of data sources * \~4-5 weeks development time ### With Pylar **Benefits**: * ✅ Single endpoint for all onboarding data * ✅ Real-time progress tracking * ✅ Automated at-risk customer identification * ✅ Unified onboarding effectiveness metrics * ✅ Easy personalized recommendations * ✅ Built-in analytics on onboarding patterns **Implementation Complexity**: * Connect 3-4 data sources (1 hour) * Create onboarding views (2.5 hours) * Build MCP tools with AI (1 hour) * Connect to agent builder (15 minutes) * **Total: \~5 hours** ## Step-by-Step Implementation ### Step 1: Connect Data Sources Connect your onboarding data sources: 1. **Connect Product Analytics** (Feature usage, user actions, engagement) 2. **Connect CRM** (Account data, customer profile, subscription tier) 3. **Connect Onboarding System** (Milestone tracking, completion status) 4. **Connect Support System** (Onboarding-related tickets) ### Step 2: Create Onboarding Views **Onboarding Progress View**: ```sql theme={null} CREATE VIEW onboarding_progress AS SELECT c.customer_id, c.customer_name, c.account_created_date, DATEDIFF(CURRENT_DATE, c.account_created_date) as days_since_signup, c.subscription_tier, -- Milestone tracking o.milestone_1_completed, o.milestone_1_completion_date, o.milestone_2_completed, o.milestone_2_completion_date, o.milestone_3_completed, o.milestone_3_completion_date, o.milestone_4_completed, o.milestone_4_completion_date, -- Feature adoption u.features_activated_count, u.total_actions_count, u.active_days_count, u.last_activity_date, DATEDIFF(CURRENT_DATE, u.last_activity_date) as days_since_last_activity, -- Support tickets s.onboarding_tickets_count, s.last_ticket_date, -- Progress calculation ( CASE WHEN o.milestone_1_completed THEN 25 ELSE 0 END + CASE WHEN o.milestone_2_completed THEN 25 ELSE 0 END + CASE WHEN o.milestone_3_completed THEN 25 ELSE 0 END + CASE WHEN o.milestone_4_completed THEN 25 ELSE 0 END ) as progress_percentage, -- Risk indicators CASE WHEN DATEDIFF(CURRENT_DATE, c.account_created_date) > 14 AND o.milestone_1_completed = FALSE THEN 1 ELSE 0 END as stalled_flag, CASE WHEN DATEDIFF(CURRENT_DATE, u.last_activity_date) > 7 THEN 1 ELSE 0 END as inactive_flag FROM crm.customers c LEFT JOIN onboarding.milestones o ON c.customer_id = o.customer_id LEFT JOIN analytics.user_usage u ON c.customer_id = u.customer_id LEFT JOIN support.onboarding_tickets s ON c.customer_id = s.customer_id; ``` **Onboarding Effectiveness View**: ```sql theme={null} CREATE VIEW onboarding_effectiveness AS SELECT o.*, -- Time to value metrics CASE WHEN o.milestone_4_completed = TRUE THEN DATEDIFF(o.milestone_4_completion_date, o.account_created_date) ELSE NULL END as days_to_complete, -- Success indicators CASE WHEN o.progress_percentage = 100 AND o.days_since_last_activity <= 7 AND o.features_activated_count >= 3 THEN 'Successful' WHEN o.progress_percentage < 50 AND o.days_since_last_activity > 7 THEN 'At Risk' WHEN o.progress_percentage >= 50 AND o.progress_percentage < 100 THEN 'In Progress' ELSE 'Needs Attention' END as onboarding_status, -- Recommended next steps CASE WHEN o.milestone_1_completed = FALSE THEN 'Complete account setup' WHEN o.milestone_2_completed = FALSE THEN 'Import your first data' WHEN o.milestone_3_completed = FALSE THEN 'Create your first dashboard' WHEN o.milestone_4_completed = FALSE THEN 'Invite your team' ELSE 'Continue exploring advanced features' END as recommended_action FROM onboarding_progress o; ``` **At-Risk Customers View**: ```sql theme={null} CREATE VIEW at_risk_onboarding AS SELECT e.* FROM onboarding_effectiveness e WHERE e.onboarding_status IN ('At Risk', 'Needs Attention') AND e.days_since_signup <= 30 ORDER BY e.churn_risk_score DESC, e.days_since_signup DESC; ``` ### Step 3: Create MCP Tools with AI **Tool 1: Get Onboarding Progress** * Prompt: "Create a tool to get onboarding progress for a customer by customer ID" * AI generates: `get_onboarding_progress(customer_id: string)` **Tool 2: List At-Risk Customers** * Prompt: "Create a tool to list customers who are at risk in onboarding" * AI generates: `get_at_risk_onboarding(days_since_signup: number, limit: number)` **Tool 3: Get Recommended Next Steps** * Prompt: "Create a tool to get recommended next steps for a customer in onboarding" * AI generates: `get_onboarding_next_steps(customer_id: string)` **Tool 4: Analyze Onboarding Effectiveness** * Prompt: "Create a tool to analyze onboarding effectiveness and time-to-value" * AI generates: `analyze_onboarding_effectiveness(days_back: number, subscription_tier: string)` ### Step 4: Test and Publish 1. Test onboarding progress tracking 2. Verify at-risk customer identification 3. Validate next step recommendations 4. Publish tools 5. Connect to agent builder ## Example Agent Interactions ### Scenario 1: Check Onboarding Status **User**: "What's the onboarding status for customer ABC Corp?" **Agent** (using Pylar tools): 1. Calls `get_onboarding_progress("abc_corp")` 2. Responds: * "ABC Corp onboarding status: 50% complete * Completed: Account setup, Data import * Pending: Dashboard creation, Team invitation * Last active: 3 days ago * Status: In Progress * Recommended: Create your first dashboard" ### Scenario 2: Identify At-Risk Customers **User**: "Show me customers who need help with onboarding" **Agent** (using Pylar tools): 1. Calls `get_at_risk_onboarding(30, 20)` 2. Analyzes results: * "Found 12 at-risk customers: * TechCo: 25% complete, stalled on milestone 2, inactive 10 days * StartupXYZ: 0% complete, no activity for 14 days * ..." ### Scenario 3: Onboarding Effectiveness Analysis **User**: "How effective is our onboarding process?" **Agent** (using Pylar tools): 1. Calls `analyze_onboarding_effectiveness(90, null)` 2. Analyzes results: * "Onboarding effectiveness (last 90 days): * Average time to complete: 12 days * Completion rate: 68% * At-risk rate: 18% * Most common blocker: Dashboard creation (32% of stalled customers)" ## Outcomes ### Onboarding Success * **Completion Rate**: 25% increase in onboarding completion * **Time to Value**: 30% reduction in time-to-value * **At-Risk Identification**: 60% earlier identification of stuck customers * **Customer Engagement**: 40% improvement in early-stage engagement ### Efficiency Gains * **Automated Tracking**: 80% reduction in manual tracking time * **Proactive Outreach**: 3x increase in proactive customer outreach * **Personalized Guidance**: 50% improvement in onboarding recommendations * **Team Productivity**: 2x more customers managed per success manager ### Data-Driven Insights * **Pattern Recognition**: Identification of successful onboarding paths * **Bottleneck Analysis**: Clear visibility into where customers get stuck * **Effectiveness Metrics**: Continuous monitoring of onboarding performance * **Optimization Opportunities**: Data-driven improvements to onboarding flow ## Best Practices 1. **Milestone Design**: Define clear, measurable onboarding milestones 2. **Regular Monitoring**: Check onboarding progress daily 3. **Proactive Outreach**: Reach out to at-risk customers within 48 hours 4. **Personalization**: Tailor recommendations based on customer profile 5. **Continuous Improvement**: Use analytics to optimize onboarding flow ## Next Steps * [Customer Support Agent Example](/examples/customer-support-agent) - Build a support agent * [Customer Churn Predictor Example](/examples/customer-churn-predictor) - Predict churn * [Product Usage Analyst Example](/examples/product-usage-analyst) - Analyze product usage # Customer Support Agent Source: https://docs.pylar.ai/examples/customer-support-agent Build an AI agent that handles support tickets with full customer context from multiple data sources ## Overview A Customer Support Agent powered by Pylar can access customer history, order details, previous interactions, and product information to provide comprehensive support without requiring direct database access. ## What the Agent Needs to Accomplish The agent must: * Retrieve customer information from multiple sources (CRM, order system, support history) * Access order details and transaction history * Review previous support interactions and resolutions * Query product catalog and documentation * Provide accurate, context-aware responses * Track and update support ticket status ## How Pylar Helps Pylar enables the agent by: * **Unified Customer View**: Creating a single view combining customer data from CRM, orders, and support systems * **Governed Access**: Ensuring the agent only accesses appropriate customer data * **Real-time Queries**: Allowing natural language queries that translate to efficient SQL * **Multi-Source Integration**: Joining data across Snowflake (orders), HubSpot (CRM), and Zendesk (support tickets) * **No API Hassles**: Eliminating the need to manage multiple API integrations ```mermaid theme={null} graph LR subgraph "Data Sources" HS[HubSpot] SF[Snowflake] ZD[Zendesk] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
get_customer_info
get_order_details
get_support_history] AGENT[Support Agent] USER[Customer] HS --> PYLAR SF --> PYLAR ZD --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT USER --> AGENT style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple API integrations required (HubSpot API, Order API, Zendesk API) * ❌ Complex authentication for each service * ❌ Rate limiting and API quota management * ❌ Manual data joining across sources * ❌ No unified customer view * ❌ Security concerns with direct database access * ❌ Difficult to maintain and update **Implementation Complexity**: * 3-5 different API integrations * Custom code for data joining * Complex error handling * Rate limit management * Authentication token management * \~2-3 weeks development time ### With Pylar **Benefits**: * ✅ Single MCP endpoint for all data sources * ✅ Unified customer 360 view * ✅ Governed SQL views ensure data security * ✅ No API rate limits or authentication complexity * ✅ Easy to update views and tools * ✅ Real-time querying across all sources * ✅ Built-in observability with Evals **Implementation Complexity**: * Connect 3 data sources (30 minutes) * Create unified customer view (1 hour) * Build MCP tools with AI (30 minutes) * Connect to agent builder (15 minutes) * **Total: \~2 hours** ## Step-by-Step Implementation ### Step 1: Connect Data Sources Connect your data sources to Pylar: 1. **Connect HubSpot** (Customer data, deals, interactions) 2. **Connect Snowflake** (Order history, transaction data) 3. **Connect Zendesk** (Support tickets, previous interactions) ### Step 2: Create Customer 360 View In Pylar's SQL IDE, create a unified customer view: ```sql theme={null} CREATE VIEW customer_360 AS SELECT h.customer_id, h.customer_name, h.email, h.phone, h.company_name, h.deal_stage, h.total_deal_value, s.order_count, s.total_spent, s.last_order_date, s.avg_order_value, z.ticket_count, z.last_ticket_date, z.resolved_tickets, z.open_tickets FROM hubspot.customers h LEFT JOIN snowflake.order_summary s ON h.email = s.customer_email LEFT JOIN zendesk.ticket_summary z ON h.email = z.customer_email; ``` ### Step 3: Create Support-Specific Views Create views for common support scenarios: **Order History View**: ```sql theme={null} CREATE VIEW customer_order_history AS SELECT c.customer_id, c.customer_name, o.order_id, o.order_date, o.order_status, o.total_amount, o.items, o.shipping_address FROM hubspot.customers c JOIN snowflake.orders o ON c.email = o.customer_email ORDER BY o.order_date DESC; ``` **Support History View**: ```sql theme={null} CREATE VIEW customer_support_history AS SELECT c.customer_id, c.customer_name, t.ticket_id, t.subject, t.status, t.created_date, t.resolved_date, t.agent_name, t.resolution FROM hubspot.customers c JOIN zendesk.tickets t ON c.email = t.customer_email ORDER BY t.created_date DESC; ``` ### Step 4: Create MCP Tools with AI Use Pylar's AI to create MCP tools: **Tool 1: Get Customer Information** * Prompt: "Create a tool to fetch complete customer information including contact details, order history, and support tickets" * AI generates: `get_customer_info(customer_email: string)` **Tool 2: Get Order Details** * Prompt: "Create a tool to retrieve order details by order ID or customer email" * AI generates: `get_order_details(order_id: string, customer_email: string)` **Tool 3: Get Support History** * Prompt: "Create a tool to fetch customer support ticket history" * AI generates: `get_support_history(customer_email: string, limit: number)` **Tool 4: Search Products** * Prompt: "Create a tool to search product catalog by name or SKU" * AI generates: `search_products(query: string, category: string)` ### Step 5: Test Tools Test each tool in Pylar: * Verify customer data retrieval * Test order lookup * Confirm support history access * Validate product search ### Step 6: Publish and Connect 1. **Publish Tools**: Click "Publish" in Pylar 2. **Copy Credentials**: Get MCP HTTP Stream URL and Authorization Token 3. **Connect to Agent Builder**: Add to your agent builder (Claude Desktop, Cursor, LangGraph, etc.) ### Step 7: Monitor with Evals Use Pylar's Evals dashboard to: * Monitor agent performance * Track common queries * Identify errors * Optimize tool usage ## Example Agent Interactions ### Scenario 1: Customer Order Inquiry **User**: "Can you check the status of order #12345 for [john@example.com](mailto:john@example.com)?" **Agent** (using Pylar tools): 1. Calls `get_customer_info("john@example.com")` 2. Calls `get_order_details("12345", "john@example.com")` 3. Responds: "Order #12345 for John Smith is currently 'Shipped' and expected to arrive on March 15th. The order contains 2 items totaling \$149.99." ### Scenario 2: Support Ticket Creation **User**: "I need help with my recent purchase" **Agent** (using Pylar tools): 1. Calls `get_customer_info(user_email)` 2. Calls `get_order_details(null, user_email)` - gets recent orders 3. Calls `get_support_history(user_email, 5)` - checks previous issues 4. Responds: "I see you purchased a laptop on March 10th. I also notice you had a previous ticket about setup. How can I help you today?" ## Outcomes ### Efficiency Gains * **Response Time**: 80% faster responses with instant data access * **First Contact Resolution**: 60% increase in resolving issues on first contact * **Agent Productivity**: 3x more tickets handled per agent * **Customer Satisfaction**: 40% improvement in CSAT scores ### Data Access * **Unified View**: Single source of truth for all customer data * **Real-time Updates**: Always current data from all sources * **No API Limits**: No rate limiting or quota concerns * **Secure Access**: Governed views ensure data security ### Maintenance * **Easy Updates**: Modify views without redeploying agents * **Observability**: Full visibility into agent queries and performance * **Iteration**: Quickly refine tools based on Evals insights ## Best Practices 1. **Data Governance**: Create views that only expose necessary customer data 2. **Error Handling**: Use Evals to identify and fix common query errors 3. **Performance**: Optimize views for common query patterns 4. **Security**: Ensure views filter sensitive data appropriately 5. **Monitoring**: Regularly review Evals dashboard for insights ## Next Steps * [Sales Assistant Example](/examples/sales-assistant) - Build a sales pipeline agent * [Customer Churn Predictor Example](/examples/customer-churn-predictor) - Predict and prevent churn * [Marketing Campaign Optimizer Example](/examples/marketing-campaign-optimizer) - Optimize marketing campaigns # Customer Wiki Agent Source: https://docs.pylar.ai/examples/customer-wiki-agent Build an AI agent that creates and maintains a customer knowledge base from support interactions and product data ## Overview A Customer Wiki Agent powered by Pylar automatically generates and maintains a comprehensive knowledge base by analyzing support tickets, customer interactions, product documentation, and frequently asked questions. ## What the Agent Needs to Accomplish The agent must: * Analyze support tickets and customer interactions to identify common questions * Extract key information from product documentation and manuals * Generate and update knowledge base articles * Answer FAQs using existing knowledge base * Identify knowledge gaps and suggest new articles * Track article effectiveness and update recommendations ## How Pylar Helps Pylar enables the agent by: * **Unified Data Access**: Combining support tickets, product docs, and knowledge base in one view * **Pattern Recognition**: Analyzing ticket patterns to identify common issues * **Content Analysis**: Querying product documentation and existing articles * **Real-time Updates**: Keeping knowledge base current with latest interactions * **Governed Access**: Ensuring only appropriate content is accessible ```mermaid theme={null} graph LR subgraph "Data Sources" ZD[Zendesk] DOCS[Product Docs] KB[Knowledge Base] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_tickets
search_docs
update_kb] AGENT[Wiki Agent] USERS[Users] ZD --> PYLAR DOCS --> PYLAR KB --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT USERS --> AGENT style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple systems to query (Zendesk, Confluence, Notion, product docs) * ❌ Complex API integrations for each system * ❌ Manual analysis of ticket patterns * ❌ Difficult to correlate support data with product documentation * ❌ No unified view of knowledge gaps * ❌ Time-consuming content updates * ❌ Limited ability to track article effectiveness **Implementation Complexity**: * 3-4 different API integrations * Custom analytics for ticket patterns * Manual content curation * Complex data correlation logic * \~3-4 weeks development time ### With Pylar **Benefits**: * ✅ Single endpoint for all knowledge sources * ✅ SQL views combine tickets, docs, and articles * ✅ Easy pattern analysis through SQL queries * ✅ Real-time knowledge base updates * ✅ Built-in analytics on article effectiveness * ✅ Simple content updates via view modifications **Implementation Complexity**: * Connect 3-4 data sources (1 hour) * Create knowledge base views (2 hours) * Build MCP tools with AI (1 hour) * Connect to agent builder (15 minutes) * **Total: \~4-5 hours** ## Step-by-Step Implementation ### Step 1: Connect Data Sources Connect your knowledge sources: 1. **Connect Zendesk** (Support tickets, articles) 2. **Connect Confluence/Notion** (Product documentation) 3. **Connect Product Analytics** (Feature usage, user behavior) 4. **Connect Knowledge Base** (Existing articles, FAQs) ### Step 2: Create Knowledge Base Views **Support Ticket Patterns View**: ```sql theme={null} CREATE VIEW support_ticket_patterns AS SELECT t.category, t.subject, COUNT(*) as frequency, AVG(t.resolution_time_hours) as avg_resolution_time, GROUP_CONCAT(DISTINCT t.tags) as common_tags, MAX(t.created_date) as last_occurrence FROM zendesk.tickets t WHERE t.status = 'resolved' GROUP BY t.category, t.subject HAVING COUNT(*) >= 5 ORDER BY frequency DESC; ``` **Knowledge Gap Analysis View**: ```sql theme={null} CREATE VIEW knowledge_gaps AS SELECT t.subject, t.category, COUNT(*) as ticket_count, CASE WHEN kb.article_id IS NULL THEN 'No Article' ELSE 'Article Exists' END as article_status, AVG(t.resolution_time_hours) as avg_resolution_time FROM zendesk.tickets t LEFT JOIN knowledge_base.articles kb ON LOWER(t.subject) LIKE LOWER(CONCAT('%', kb.title, '%')) WHERE t.created_date >= DATE_SUB(CURRENT_DATE, INTERVAL 90 DAY) GROUP BY t.subject, t.category, kb.article_id HAVING COUNT(*) >= 3 AND kb.article_id IS NULL ORDER BY ticket_count DESC; ``` **Article Effectiveness View**: ```sql theme={null} CREATE VIEW article_effectiveness AS SELECT kb.article_id, kb.title, kb.category, kb.view_count, COUNT(DISTINCT t.ticket_id) as related_tickets, AVG(t.resolution_time_hours) as avg_resolution_time, CASE WHEN kb.view_count > 0 THEN (COUNT(DISTINCT t.ticket_id) / kb.view_count) * 100 ELSE 0 END as ticket_to_view_ratio FROM knowledge_base.articles kb LEFT JOIN zendesk.tickets t ON LOWER(t.subject) LIKE LOWER(CONCAT('%', kb.title, '%')) GROUP BY kb.article_id, kb.title, kb.category, kb.view_count ORDER BY ticket_to_view_ratio DESC; ``` ### Step 3: Create MCP Tools with AI **Tool 1: Identify Knowledge Gaps** * Prompt: "Create a tool to find topics with many support tickets but no knowledge base articles" * AI generates: `find_knowledge_gaps(min_tickets: number, days_back: number)` **Tool 2: Generate Article Suggestions** * Prompt: "Create a tool to suggest new knowledge base articles based on support ticket patterns" * AI generates: `suggest_articles(category: string, min_frequency: number)` **Tool 3: Analyze Article Effectiveness** * Prompt: "Create a tool to analyze how well articles are reducing support tickets" * AI generates: `analyze_article_effectiveness(article_id: string, days_back: number)` **Tool 4: Search Knowledge Base** * Prompt: "Create a tool to search knowledge base articles and product documentation" * AI generates: `search_knowledge_base(query: string, category: string)` **Tool 5: Get FAQ Answers** * Prompt: "Create a tool to retrieve FAQ answers from knowledge base" * AI generates: `get_faq_answer(question: string)` ### Step 4: Test and Publish 1. Test each tool with sample queries 2. Verify knowledge gap identification 3. Validate article suggestions 4. Publish tools 5. Connect to agent builder ## Example Agent Interactions ### Scenario 1: Knowledge Gap Identification **User**: "What topics should we create articles for?" **Agent** (using Pylar tools): 1. Calls `find_knowledge_gaps(5, 90)` - finds topics with 5+ tickets in last 90 days 2. Analyzes results and responds: * "I found 12 topics that need articles: 1. 'Password Reset Issues' - 23 tickets, avg resolution 2.5 hours 2. 'Payment Processing Errors' - 18 tickets, avg resolution 4.2 hours 3. ..." ### Scenario 2: FAQ Answering **User**: "How do I reset my password?" **Agent** (using Pylar tools): 1. Calls `search_knowledge_base("password reset", null)` 2. Finds relevant article 3. Responds: "To reset your password: 1. Go to login page, 2. Click 'Forgot Password', 3. Enter your email, 4. Check your inbox for reset link..." ### Scenario 3: Article Effectiveness Analysis **User**: "Which articles are most effective?" **Agent** (using Pylar tools): 1. Calls `analyze_article_effectiveness(null, 30)` 2. Analyzes results: * "Top performing articles: 'Account Setup Guide' has 0.5% ticket-to-view ratio, 'Billing FAQ' has 0.8% ratio..." ## Outcomes ### Knowledge Base Quality * **Article Coverage**: 40% increase in topics covered * **Article Effectiveness**: 35% reduction in related support tickets * **Update Frequency**: 3x faster article updates * **Content Relevance**: 50% improvement in article relevance scores ### Support Efficiency * **Self-Service Rate**: 60% of common questions answered via knowledge base * **Ticket Reduction**: 25% reduction in support tickets * **Resolution Time**: 30% faster resolution for topics with articles * **Agent Productivity**: More time for complex issues ### Data-Driven Insights * **Gap Identification**: Automated identification of knowledge gaps * **Content Strategy**: Data-driven article prioritization * **Effectiveness Tracking**: Continuous monitoring of article performance * **Trend Analysis**: Identification of emerging support patterns ## Best Practices 1. **Regular Updates**: Schedule weekly knowledge gap analysis 2. **Content Quality**: Review and update articles based on effectiveness metrics 3. **User Feedback**: Incorporate user feedback into article improvements 4. **Categorization**: Maintain clear article categories for better search 5. **Analytics**: Use Evals to track agent knowledge base usage patterns ## Next Steps * [Customer Support Agent Example](/examples/customer-support-agent) - Build a support agent * [Product Feedback Analyzer Example](/examples/product-feedback-analyzer) - Analyze user feedback * [Content Performance Analyzer Example](/examples/content-performance-analyzer) - Analyze content effectiveness # Expense Auditor Source: https://docs.pylar.ai/examples/expense-auditor Build an AI agent that reviews expenses, identifies anomalies, ensures compliance, and generates audit reports ## Overview An Expense Auditor powered by Pylar reviews expenses, identifies anomalies, ensures policy compliance, and generates audit reports to maintain financial integrity. ## What the Agent Needs to Accomplish The agent must: * Review expense submissions * Identify anomalies and outliers * Check policy compliance * Generate audit reports * Track approval workflows * Identify fraud patterns ## How Pylar Helps Pylar enables the agent by: * **Unified Expense View**: Combining expenses, policies, and approvals * **Anomaly Detection**: Automated anomaly identification * **Compliance Checking**: Policy compliance validation * **Audit Reporting**: Automated audit report generation ```mermaid theme={null} graph LR subgraph "Data Sources" EXPENSES[Expenses] POLICIES[Policies] APPROVALS[Approvals] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
detect_anomalies
check_compliance
generate_reports] AGENT[Expense Auditor] TEAM[Finance Team] EXPENSES --> PYLAR POLICIES --> PYLAR APPROVALS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Manual expense review * ❌ Time-consuming anomaly detection * ❌ Complex compliance checking * ❌ Limited audit capabilities **Implementation Complexity**: \~5-6 weeks ### With Pylar **Benefits**: * ✅ Automated expense review * ✅ Real-time anomaly detection * ✅ Policy compliance automation * ✅ Efficient audit reporting **Implementation Complexity**: \~6-7 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Expense System** (Expense reports, receipts) 2. **Connect HR System** (Employee data, policies) 3. **Connect Approval System** (Approvals, workflows) ### Step 2: Create Expense Views **Expense Anomaly View**: ```sql theme={null} CREATE VIEW expense_anomalies AS SELECT e.expense_id, e.employee_id, e.category, e.amount, e.submission_date, -- Anomaly indicators CASE WHEN e.amount > AVG(e.amount) OVER (PARTITION BY e.category) * 2 THEN 1 ELSE 0 END as high_amount_flag, CASE WHEN e.amount < AVG(e.amount) OVER (PARTITION BY e.category) * 0.1 THEN 1 ELSE 0 END as low_amount_flag, CASE WHEN e.category NOT IN (SELECT category FROM policies.allowed_categories) THEN 1 ELSE 0 END as policy_violation_flag FROM expenses.expenses e; ``` ### Step 3: Create MCP Tools **Tool 1: Review Expense** * `review_expense(expense_id: string)` **Tool 2: Identify Anomalies** * `identify_anomalies(days_back: number, min_amount: number)` **Tool 3: Check Compliance** * `check_compliance(expense_id: string, policy_version: string)` **Tool 4: Generate Audit Report** * `generate_audit_report(period: string, include_anomalies: boolean)` ## Example Agent Interactions **User**: "Review expenses for potential fraud" **Agent**: "Expense Audit Results: * Total Expenses: \$125K * Anomalies Found: 12 * High Risk: 3 expenses (\$15K total) * Employee #456: $8K meal expense (policy limit: $500) * Employee #789: \$5K travel (no receipts) * Employee #123: \$2K duplicate submission * Recommendation: Flag for manual review" ## Outcomes * **Review Speed**: 85% faster * **Anomaly Detection**: 90% accuracy * **Compliance**: 95% policy compliance * **Fraud Detection**: 60% earlier detection ## Next Steps * [Financial Analyst Example](/examples/financial-analyst) * [Invoice & Billing Assistant Example](/examples/invoice-billing-assistant) # Feature Flag Manager Source: https://docs.pylar.ai/examples/feature-flag-manager Build an AI agent that manages feature rollouts, analyzes flag performance, and recommends rollback decisions ## Overview A Feature Flag Manager powered by Pylar monitors feature flag performance, analyzes user impact, and provides data-driven recommendations for rollouts and rollbacks. ## What the Agent Needs to Accomplish The agent must: * Monitor feature flag status * Analyze flag performance metrics * Track error rates and user impact * Recommend rollback decisions * Optimize rollout percentages * Track feature flag effectiveness ## How Pylar Helps Pylar enables the agent by: * **Unified Flag View**: Combining flag data, error rates, and user metrics * **Real-time Monitoring**: Querying current flag performance * **Impact Analysis**: Automated impact calculations * **Decision Support**: Data-driven rollout recommendations ```mermaid theme={null} graph LR subgraph "Data Sources" FLAGS[Feature Flags] ERRORS[Error Rates] METRICS[User Metrics] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
monitor_flags
analyze_impact
recommend_rollback] AGENT[Flag Manager] TEAM[Engineering Team] FLAGS --> PYLAR ERRORS --> PYLAR METRICS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Manual flag monitoring * ❌ Complex error correlation * ❌ Time-consuming impact analysis * ❌ Limited real-time visibility **Implementation Complexity**: \~3-4 weeks ### With Pylar **Benefits**: * ✅ Automated flag monitoring * ✅ Real-time performance tracking * ✅ Instant impact analysis * ✅ Clear rollback recommendations **Implementation Complexity**: \~4-5 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Feature Flag Platform** (LaunchDarkly, Split.io) 2. **Connect Error Tracking** (Sentry, Bugsnag) 3. **Connect Product Analytics** (User behavior, engagement) ### Step 2: Create Flag Views **Feature Flag Performance View**: ```sql theme={null} CREATE VIEW flag_performance AS SELECT f.flag_name, f.enabled_percentage, f.status, COUNT(DISTINCT u.user_id) as users_affected, e.error_count, e.error_rate, a.engagement_score, -- Risk score (e.error_rate * 50 + CASE WHEN a.engagement_score < 50 THEN 30 ELSE 0 END + CASE WHEN f.enabled_percentage > 50 AND e.error_rate > 0.05 THEN 20 ELSE 0 END) as risk_score FROM feature_flags.flags f LEFT JOIN errors.error_summary e ON f.flag_name = e.flag_name LEFT JOIN analytics.user_engagement a ON f.flag_name = a.flag_name GROUP BY f.flag_name, f.enabled_percentage, f.status, e.error_count, e.error_rate, a.engagement_score; ``` ### Step 3: Create MCP Tools **Tool 1: Monitor Feature Flag** * `monitor_feature_flag(flag_name: string)` **Tool 2: Analyze Flag Performance** * `analyze_flag_performance(flag_name: string, hours_back: number)` **Tool 3: Recommend Rollback** * `recommend_rollback(flag_name: string, threshold: number)` **Tool 4: Optimize Rollout** * `optimize_rollout(flag_name: string, target_percentage: number)` ## Example Agent Interactions **User**: "Should we rollback the new checkout feature?" **Agent**: "Feature Flag Analysis: 'new\_checkout' * Status: 35% enabled * Error Rate: 2.1% (Threshold: 1%) * User Impact: 1,200 users affected * Engagement: -15% vs baseline * Risk Score: 68 (High) Recommendation: ROLLBACK - Error rate exceeds threshold and engagement is declining" ## Outcomes * **Incident Detection**: 60% faster detection * **Rollback Decisions**: 50% more accurate decisions * **User Impact**: 40% reduction in negative impact * **Feature Success**: 25% improvement in successful rollouts ## Next Steps * [Product Usage Analyst Example](/examples/product-usage-analyst) * [Product Feedback Analyzer Example](/examples/product-feedback-analyzer) # Financial Analyst Source: https://docs.pylar.ai/examples/financial-analyst Build an AI agent that analyzes revenue trends, expenses, profitability, and generates financial reports ## Overview A Financial Analyst powered by Pylar analyzes revenue trends, expenses, profitability metrics, and generates comprehensive financial reports to support business decisions. ## What the Agent Needs to Accomplish The agent must: * Analyze revenue trends and patterns * Track expenses by category * Calculate profitability metrics * Generate financial reports * Identify budget variances * Forecast financial performance ## How Pylar Helps Pylar enables the agent by: * **Unified Financial View**: Combining revenue, expenses, and budget data * **Real-time Analysis**: Querying current financial metrics * **Automated Calculations**: Complex financial calculations * **Trend Analysis**: Identifying financial patterns * **Report Generation**: Automated financial reporting ```mermaid theme={null} graph LR subgraph "Data Sources" REVENUE[Revenue] EXPENSES[Expenses] BUDGET[Budget] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_trends
calculate_metrics
generate_reports] AGENT[Financial Analyst] TEAM[Finance Team] REVENUE --> PYLAR EXPENSES --> PYLAR BUDGET --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple financial systems * ❌ Manual financial calculations * ❌ Time-consuming report generation * ❌ Limited real-time insights **Implementation Complexity**: \~5-6 weeks ### With Pylar **Benefits**: * ✅ Single endpoint for all financial data * ✅ Automated calculations * ✅ Real-time financial metrics * ✅ Easy report generation **Implementation Complexity**: \~6-7 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Accounting System** (Revenue, expenses, transactions) 2. **Connect Billing System** (Invoices, payments) 3. **Connect Budget System** (Budgets, forecasts) ### Step 2: Create Financial Views **Financial Performance View**: ```sql theme={null} CREATE VIEW financial_performance AS SELECT DATE_TRUNC('month', transaction_date) as month, SUM(CASE WHEN type = 'Revenue' THEN amount ELSE 0 END) as revenue, SUM(CASE WHEN type = 'Expense' THEN amount ELSE 0 END) as expenses, SUM(CASE WHEN type = 'Revenue' THEN amount ELSE 0 END) - SUM(CASE WHEN type = 'Expense' THEN amount ELSE 0 END) as profit, ((SUM(CASE WHEN type = 'Revenue' THEN amount ELSE 0 END) - SUM(CASE WHEN type = 'Expense' THEN amount ELSE 0 END)) / NULLIF(SUM(CASE WHEN type = 'Revenue' THEN amount ELSE 0 END), 0)) * 100 as profit_margin FROM accounting.transactions GROUP BY DATE_TRUNC('month', transaction_date); ``` ### Step 3: Create MCP Tools **Tool 1: Analyze Revenue Trends** * `analyze_revenue_trends(period: string, start_date: date, end_date: date)` **Tool 2: Track Expenses** * `track_expenses(category: string, period: string)` **Tool 3: Calculate Profitability** * `calculate_profitability(period: string, segment: string)` **Tool 4: Generate Financial Report** * `generate_financial_report(report_type: string, period: string)` ## Example Agent Interactions **User**: "What's our financial performance this quarter?" **Agent**: "Q2 Financial Performance: * Revenue: \$2.4M (+15% vs Q1) * Expenses: \$1.8M (+8% vs Q1) * Profit: \$600K (+35% vs Q1) * Profit Margin: 25% (up from 20%) * Top Expense: Salaries (\$850K) * Budget Variance: Under budget by 5%" ## Outcomes * **Report Generation**: 80% faster * **Financial Visibility**: Real-time metrics * **Decision Speed**: 50% faster financial decisions * **Accuracy**: 95% calculation accuracy ## Next Steps * [Invoice & Billing Assistant Example](/examples/invoice-billing-assistant) * [Expense Auditor Example](/examples/expense-auditor) # Invoice & Billing Assistant Source: https://docs.pylar.ai/examples/invoice-billing-assistant Build an AI agent that handles billing queries, generates invoices, tracks payments, and manages collections ## Overview An Invoice & Billing Assistant powered by Pylar handles billing inquiries, generates invoices, tracks payment status, and manages collections to streamline billing operations. ## What the Agent Needs to Accomplish The agent must: * Answer billing queries * Generate invoices * Track payment status * Manage collections * Identify overdue accounts * Generate billing reports ## How Pylar Helps Pylar enables the agent by: * **Unified Billing View**: Combining invoices, payments, and customer data * **Real-time Status**: Querying current billing and payment status * **Automated Tracking**: Automated payment tracking * **Collection Management**: Identifying and managing overdue accounts ```mermaid theme={null} graph LR subgraph "Data Sources" INVOICES[Invoices] PAYMENTS[Payments] CUSTOMERS[Customer Data] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
get_invoice
track_payment
manage_collections] AGENT[Billing Assistant] USERS[Users] INVOICES --> PYLAR PAYMENTS --> PYLAR CUSTOMERS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT USERS --> AGENT style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple billing systems * ❌ Manual invoice generation * ❌ Time-consuming payment tracking * ❌ Limited collection visibility **Implementation Complexity**: \~4-5 weeks ### With Pylar **Benefits**: * ✅ Single endpoint for billing data * ✅ Automated invoice generation * ✅ Real-time payment tracking * ✅ Efficient collection management **Implementation Complexity**: \~5-6 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Billing System** (Invoices, subscriptions) 2. **Connect Payment Processor** (Payments, transactions) 3. **Connect CRM** (Customer data, billing contacts) ### Step 2: Create Billing Views **Invoice Status View**: ```sql theme={null} CREATE VIEW invoice_status AS SELECT i.invoice_id, i.customer_id, i.invoice_date, i.due_date, i.amount, i.status, p.payment_amount, p.payment_date, i.amount - COALESCE(p.payment_amount, 0) as outstanding_amount, DATEDIFF(CURRENT_DATE, i.due_date) as days_overdue FROM billing.invoices i LEFT JOIN billing.payments p ON i.invoice_id = p.invoice_id; ``` ### Step 3: Create MCP Tools **Tool 1: Get Invoice Details** * `get_invoice_details(invoice_id: string, customer_id: string)` **Tool 2: Track Payment Status** * `track_payment_status(invoice_id: string)` **Tool 3: Identify Overdue Accounts** * `identify_overdue_accounts(days_overdue: number, min_amount: number)` **Tool 4: Generate Invoice** * `generate_invoice(customer_id: string, items: array, due_date: date)` ## Example Agent Interactions **User**: "What's the status of invoice #12345?" **Agent**: "Invoice #12345 Status: * Customer: Acme Corp * Amount: \$5,000 * Status: Partially Paid (\$2,000 paid) * Outstanding: \$3,000 * Due Date: March 15, 2024 (5 days overdue) * Action: Send payment reminder" ## Outcomes * **Query Response**: 80% faster * **Payment Tracking**: 90% automation * **Collection Efficiency**: 40% improvement * **Customer Satisfaction**: 30% improvement ## Next Steps * [Financial Analyst Example](/examples/financial-analyst) * [Expense Auditor Example](/examples/expense-auditor) # IT Operations Monitor Source: https://docs.pylar.ai/examples/it-operations-monitor Build an AI agent that monitors system health, analyzes performance metrics, and generates incident reports ## Overview An IT Operations Monitor powered by Pylar monitors system health, analyzes performance metrics, tracks errors, and generates incident reports to ensure reliable infrastructure. ## What the Agent Needs to Accomplish The agent must: * Monitor system health and status * Analyze performance metrics * Track errors and incidents * Generate incident reports * Identify performance degradation * Recommend optimizations ## How Pylar Helps Pylar enables the agent by: * **Unified Operations View**: Combining system logs, metrics, and error data * **Real-time Monitoring**: Querying current system status * **Automated Analysis**: Performance and error analysis * **Incident Management**: Automated incident detection and reporting ```mermaid theme={null} graph LR subgraph "Data Sources" LOGS[System Logs] METRICS[Metrics] ERRORS[Error Data] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
monitor_health
analyze_performance
generate_reports] AGENT[IT Monitor] TEAM[IT Team] LOGS --> PYLAR METRICS --> PYLAR ERRORS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple monitoring tools * ❌ Manual log analysis * ❌ Time-consuming incident detection * ❌ Limited correlation **Implementation Complexity**: \~5-6 weeks ### With Pylar **Benefits**: * ✅ Single endpoint for operations data * ✅ Real-time monitoring * ✅ Automated incident detection * ✅ Comprehensive visibility **Implementation Complexity**: \~6-7 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect System Logs** (Application logs, server logs) 2. **Connect Metrics** (Performance metrics, system stats) 3. **Connect Error Tracking** (Error logs, exceptions) ### Step 2: Create Operations Views **System Health View**: ```sql theme={null} CREATE VIEW system_health AS SELECT s.server_id, s.server_name, s.status, m.cpu_usage, m.memory_usage, m.disk_usage, e.error_count_last_hour, e.critical_errors, -- Health score CASE WHEN s.status = 'Down' THEN 0 WHEN e.critical_errors > 0 THEN 25 WHEN m.cpu_usage > 90 OR m.memory_usage > 90 THEN 50 WHEN e.error_count_last_hour > 100 THEN 75 ELSE 100 END as health_score FROM infrastructure.servers s LEFT JOIN metrics.server_metrics m ON s.server_id = m.server_id LEFT JOIN errors.error_summary e ON s.server_id = e.server_id; ``` ### Step 3: Create MCP Tools **Tool 1: Monitor System Health** * `monitor_system_health(server_id: string, service_name: string)` **Tool 2: Analyze Performance** * `analyze_performance(server_id: string, hours_back: number)` **Tool 3: Track Errors** * `track_errors(server_id: string, error_type: string, hours_back: number)` **Tool 4: Generate Incident Report** * `generate_incident_report(incident_id: string, include_metrics: boolean)` ## Example Agent Interactions **User**: "What's the system health status?" **Agent**: "System Health Report: * Overall Status: Healthy (95/100) * Servers: 12/12 online * Issues: * Server DB-02: High memory usage (92%) * API-01: Increased error rate (150 errors/hour) * Recommendations: * Scale DB-02 memory * Investigate API-01 error spike" ## Outcomes * **Incident Detection**: 70% faster * **Uptime**: 99.9% uptime achieved * **MTTR**: 40% reduction in mean time to repair * **Efficiency**: 60% improvement in operations efficiency ## Next Steps * [Supply Chain Coordinator Example](/examples/supply-chain-coordinator) * [Product Usage Analyst Example](/examples/product-usage-analyst) # Lead Qualification Agent Source: https://docs.pylar.ai/examples/lead-qualification-agent Build an AI agent that scores leads, routes to appropriate sales reps, and prioritizes high-value prospects ## Overview A Lead Qualification Agent powered by Pylar automatically scores leads based on firmographic data, behavioral signals, and historical conversion patterns, then routes them to the right sales reps. ## What the Agent Needs to Accomplish The agent must: * Score leads based on multiple criteria * Route leads to appropriate sales reps * Prioritize high-value prospects * Track lead conversion rates * Identify lead quality trends * Optimize routing rules ## How Pylar Helps Pylar enables the agent by: * **Unified Lead View**: Combining lead data, firmographics, and behavioral signals * **Real-time Scoring**: Querying current lead data for instant scoring * **Multi-Source Integration**: Joining lead data with CRM and marketing data * **Pattern Recognition**: Identifying high-converting lead patterns * **Automated Routing**: Intelligent lead distribution ```mermaid theme={null} graph LR subgraph "Data Sources" LEADS[Lead Data] CRM[CRM] MARKETING[Marketing] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
score_leads
route_leads
prioritize_prospects] AGENT[Lead Qualifier] REPS[Sales Reps] LEADS --> PYLAR CRM --> PYLAR MARKETING --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> REPS style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Manual lead scoring * ❌ Complex routing logic across systems * ❌ Limited lead data integration * ❌ Time-consuming qualification * ❌ Inconsistent scoring **Implementation Complexity**: \~4-5 weeks ### With Pylar **Benefits**: * ✅ Automated lead scoring * ✅ Real-time routing * ✅ Unified lead data * ✅ Pattern-based optimization **Implementation Complexity**: \~5-6 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Marketing Platform** (Lead data, behavioral signals) 2. **Connect CRM** (Lead conversion, historical data) 3. **Connect Firmographic Data** (Company data, industry) ### Step 2: Create Lead Scoring Views **Lead Score View**: ```sql theme={null} CREATE VIEW lead_scoring AS SELECT l.lead_id, l.email, l.company_name, l.industry, l.company_size, -- Behavioral signals l.page_views, l.download_count, l.webinar_attended, -- Firmographic score CASE WHEN l.company_size >= 1000 THEN 30 WHEN l.company_size >= 500 THEN 20 WHEN l.company_size >= 100 THEN 10 ELSE 5 END as firmographic_score, -- Behavioral score (l.page_views * 2 + l.download_count * 5 + CASE WHEN l.webinar_attended THEN 10 ELSE 0 END) as behavioral_score, -- Total score (CASE WHEN l.company_size >= 1000 THEN 30 ELSE 0 END + CASE WHEN l.company_size >= 500 THEN 20 ELSE 0 END + l.page_views * 2 + l.download_count * 5 + CASE WHEN l.webinar_attended THEN 10 ELSE 0 END) as total_score FROM marketing.leads l; ``` ### Step 3: Create MCP Tools **Tool 1: Score Lead** * `score_lead(lead_id: string)` **Tool 2: Route Lead** * `route_lead(lead_id: string, territory: string)` **Tool 3: Get High-Value Leads** * `get_high_value_leads(min_score: number, limit: number)` **Tool 4: Analyze Lead Quality** * `analyze_lead_quality(days_back: number, source: string)` ## Example Agent Interactions **User**: "Score and route this new lead" **Agent**: "Lead scored: 85/100 (High Quality) * Company: TechCorp (500 employees) * Activity: 15 page views, 2 downloads * Routed to: Sarah Johnson (Enterprise team) * Recommended: Immediate outreach" ## Outcomes * **Qualification Speed**: 80% faster * **Conversion Rate**: 25% improvement * **Routing Accuracy**: 40% better match * **Sales Efficiency**: 2x more qualified leads per rep ## Next Steps * [Sales Assistant Example](/examples/sales-assistant) * [Marketing Campaign Optimizer Example](/examples/marketing-campaign-optimizer) # Marketing Attribution Analyzer Source: https://docs.pylar.ai/examples/marketing-attribution-analyzer Build an AI agent that tracks customer journey, attributes conversions, and measures channel effectiveness ## Overview A Marketing Attribution Analyzer powered by Pylar tracks the complete customer journey across touchpoints, attributes conversions to marketing channels, and measures channel effectiveness. ## What the Agent Needs to Accomplish The agent must: * Track customer journey across touchpoints * Attribute conversions to marketing channels * Measure channel effectiveness * Analyze multi-touch attribution * Compare attribution models * Optimize channel mix ## How Pylar Helps Pylar enables the agent by: * **Unified Journey View**: Combining touchpoints, channels, and conversions * **Multi-Touch Analysis**: Tracking all customer interactions * **Attribution Models**: Multiple attribution model calculations * **Channel Comparison**: Side-by-side channel effectiveness ```mermaid theme={null} graph LR subgraph "Data Sources" TOUCHPOINTS[Touchpoints] CHANNELS[Channels] CONVERSIONS[Conversions] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
track_journey
attribute_conversions
compare_channels] AGENT[Attribution Analyzer] TEAM[Marketing Team] TOUCHPOINTS --> PYLAR CHANNELS --> PYLAR CONVERSIONS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Complex journey tracking across systems * ❌ Manual attribution calculations * ❌ Limited multi-touch visibility * ❌ Time-consuming analysis **Implementation Complexity**: \~6-8 weeks ### With Pylar **Benefits**: * ✅ Automated journey tracking * ✅ Multiple attribution models * ✅ Real-time channel analysis * ✅ Easy model comparison **Implementation Complexity**: \~7-8 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Marketing Channels** (Ads, email, social) 2. **Connect Analytics** (Website touchpoints) 3. **Connect CRM** (Conversions, customer data) ### Step 2: Create Attribution Views **Customer Journey View**: ```sql theme={null} CREATE VIEW customer_journey AS SELECT c.customer_id, c.conversion_date, t.touchpoint_id, t.channel, t.touchpoint_date, t.touchpoint_type, ROW_NUMBER() OVER (PARTITION BY c.customer_id ORDER BY t.touchpoint_date) as touchpoint_order FROM conversions c JOIN touchpoints t ON c.customer_id = t.customer_id WHERE t.touchpoint_date <= c.conversion_date; ``` **Attribution Analysis View**: ```sql theme={null} CREATE VIEW attribution_analysis AS SELECT channel, COUNT(DISTINCT customer_id) as conversions, -- First touch SUM(CASE WHEN touchpoint_order = 1 THEN 1 ELSE 0 END) as first_touch, -- Last touch SUM(CASE WHEN touchpoint_order = max_touchpoint THEN 1 ELSE 0 END) as last_touch, -- Linear COUNT(DISTINCT customer_id) / max_touchpoint as linear_attribution FROM customer_journey GROUP BY channel; ``` ### Step 3: Create MCP Tools **Tool 1: Track Customer Journey** * `track_customer_journey(customer_id: string)` **Tool 2: Attribute Conversion** * `attribute_conversion(conversion_id: string, model: string)` **Tool 3: Analyze Channel Effectiveness** * `analyze_channel_effectiveness(model: string, period: string)` **Tool 4: Compare Attribution Models** * `compare_attribution_models(conversion_id: string)` ## Example Agent Interactions **User**: "Which channels drive the most conversions?" **Agent**: "Channel Attribution Analysis (Last Touch): * Google Ads: 35% of conversions (\$420K revenue) * Email Marketing: 28% (\$336K revenue) * LinkedIn Ads: 22% (\$264K revenue) * Organic Search: 15% (\$180K revenue) Multi-touch analysis shows Google Ads + Email drives 45% of conversions" ## Outcomes * **Attribution Accuracy**: 40% improvement * **Channel Optimization**: 25% better budget allocation * **Journey Visibility**: 100% touchpoint tracking * **ROI Improvement**: 30% increase in marketing ROI ## Next Steps * [Marketing Campaign Optimizer Example](/examples/marketing-campaign-optimizer) * [Content Performance Analyzer Example](/examples/content-performance-analyzer) # Marketing Campaign Optimizer Source: https://docs.pylar.ai/examples/marketing-campaign-optimizer Build an AI agent that analyzes campaign performance, identifies high-value segments, and optimizes marketing spend ## Overview A Marketing Campaign Optimizer powered by Pylar analyzes campaign performance across channels, identifies high-value customer segments, and provides data-driven recommendations to optimize marketing spend and ROI. ## What the Agent Needs to Accomplish The agent must: * Analyze campaign performance across channels * Identify high-value customer segments * Calculate ROI and conversion metrics * Optimize marketing spend allocation * Track campaign effectiveness over time * Recommend campaign adjustments ## How Pylar Helps Pylar enables the agent by: * **Unified Campaign View**: Combining campaign data, customer segments, and conversion metrics * **Real-time Analysis**: Querying current campaign performance * **Multi-Channel Integration**: Joining data from multiple marketing channels * **ROI Calculation**: Automated ROI and conversion rate calculations * **Segment Analysis**: Identifying profitable customer segments ```mermaid theme={null} graph LR subgraph "Data Sources" CAMPAIGNS[Campaigns] ANALYTICS[Analytics] CRM[CRM] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_campaigns
calculate_roi
optimize_spend] AGENT[Campaign Optimizer] TEAM[Marketing Team] CAMPAIGNS --> PYLAR ANALYTICS --> PYLAR CRM --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple marketing platforms (Google Ads, Facebook, email, etc.) * ❌ Complex API integrations for each channel * ❌ Manual campaign analysis * ❌ Difficult to correlate campaigns with conversions * ❌ Time-consuming ROI calculations * ❌ Limited real-time insights **Implementation Complexity**: \~5-6 weeks ### With Pylar **Benefits**: * ✅ Single endpoint for all campaign data * ✅ Real-time campaign analysis * ✅ Automated ROI calculations * ✅ Unified conversion tracking * ✅ Easy campaign optimization **Implementation Complexity**: \~6-7 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Marketing Platforms** (Google Ads, Facebook Ads, LinkedIn Ads) 2. **Connect Email Platform** (Email campaigns, open rates) 3. **Connect Analytics** (Website traffic, conversions) 4. **Connect CRM** (Customer segments, conversion data) ### Step 2: Create Campaign Views **Campaign Performance View**: ```sql theme={null} CREATE VIEW campaign_performance AS SELECT c.campaign_id, c.campaign_name, c.channel, c.start_date, c.end_date, c.spend, c.impressions, c.clicks, c.conversions, -- Metrics (c.clicks / NULLIF(c.impressions, 0)) * 100 as ctr, (c.conversions / NULLIF(c.clicks, 0)) * 100 as conversion_rate, c.revenue, (c.revenue - c.spend) as profit, ((c.revenue - c.spend) / NULLIF(c.spend, 0)) * 100 as roi_percent FROM marketing.campaigns c; ``` **Segment Performance View**: ```sql theme={null} CREATE VIEW segment_performance AS SELECT s.segment_name, s.channel, COUNT(DISTINCT c.customer_id) as customers, SUM(c.spend) as total_spend, SUM(c.revenue) as total_revenue, AVG(c.conversion_rate) as avg_conversion_rate, AVG(c.roi_percent) as avg_roi FROM marketing.segments s JOIN marketing.campaigns c ON s.campaign_id = c.campaign_id GROUP BY s.segment_name, s.channel; ``` ### Step 3: Create MCP Tools **Tool 1: Analyze Campaign Performance** * `analyze_campaign_performance(campaign_id: string, start_date: date, end_date: date)` **Tool 2: Identify High-Value Segments** * `identify_high_value_segments(min_roi: number, channel: string)` **Tool 3: Optimize Marketing Spend** * `optimize_marketing_spend(budget: number, channels: array)` **Tool 4: Campaign ROI Analysis** * `analyze_campaign_roi(period: string, channel: string)` ## Example Agent Interactions **User**: "Which campaigns should we increase budget for?" **Agent**: "Top Performing Campaigns (ROI > 200%): 1. LinkedIn B2B Campaign: 285% ROI, $50K revenue from $13K spend 2. Email Product Launch: 240% ROI, $72K revenue from $30K spend 3. Google Search - Enterprise: 210% ROI, $105K revenue from $50K spend Recommendation: Increase budget by 30% for LinkedIn B2B campaign" ## Outcomes * **ROI Improvement**: 35% increase in average ROI * **Spend Efficiency**: 25% better budget allocation * **Conversion Rate**: 20% improvement in conversion rates * **Campaign Performance**: 40% reduction in underperforming campaigns ## Next Steps * [Content Performance Analyzer Example](/examples/content-performance-analyzer) * [A/B Testing Assistant Example](/examples/ab-testing-assistant) * [Marketing Attribution Analyzer Example](/examples/marketing-attribution-analyzer) # Product Feedback Analyzer Source: https://docs.pylar.ai/examples/product-feedback-analyzer Build an AI agent that analyzes user feedback, feature requests, sentiment, and prioritizes improvements ## Overview A Product Feedback Analyzer powered by Pylar analyzes user feedback, feature requests, sentiment, and prioritizes product improvements based on data-driven insights. ## What the Agent Needs to Accomplish The agent must: * Analyze user feedback and reviews * Track feature requests * Perform sentiment analysis * Prioritize improvements * Identify common pain points * Track feedback trends ## How Pylar Helps Pylar enables the agent by: * **Unified Feedback View**: Combining feedback from multiple sources * **Sentiment Analysis**: Automated sentiment scoring * **Priority Calculation**: Data-driven prioritization * **Trend Analysis**: Identifying feedback patterns over time ```mermaid theme={null} graph LR subgraph "Data Sources" FEEDBACK[User Feedback] REVIEWS[Reviews] REQUESTS[Feature Requests] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_sentiment
prioritize_features
track_trends] AGENT[Feedback Analyzer] TEAM[Product Team] FEEDBACK --> PYLAR REVIEWS --> PYLAR REQUESTS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Feedback scattered across platforms * ❌ Manual sentiment analysis * ❌ Difficult to prioritize requests * ❌ Limited trend visibility **Implementation Complexity**: \~4-5 weeks ### With Pylar **Benefits**: * ✅ Single endpoint for all feedback * ✅ Automated sentiment analysis * ✅ Data-driven prioritization * ✅ Real-time trend tracking **Implementation Complexity**: \~5-6 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Feedback Platform** (UserVoice, Canny, Intercom) 2. **Connect Reviews** (App Store, G2, Capterra) 3. **Connect Support** (Support tickets, feature requests) ### Step 2: Create Feedback Views **Feedback Analysis View**: ```sql theme={null} CREATE VIEW feedback_analysis AS SELECT f.feedback_id, f.feedback_text, f.category, f.votes, f.sentiment_score, f.created_date, -- Priority score (f.votes * 0.4 + ABS(f.sentiment_score) * 30 + CASE WHEN f.category = 'Critical' THEN 30 ELSE 0 END) as priority_score FROM feedback.feedback f; ``` ### Step 3: Create MCP Tools **Tool 1: Analyze Feedback Sentiment** * `analyze_feedback_sentiment(category: string, days_back: number)` **Tool 2: Get Top Feature Requests** * `get_top_feature_requests(limit: number, min_votes: number)` **Tool 3: Identify Common Pain Points** * `identify_pain_points(category: string, min_mentions: number)` **Tool 4: Prioritize Improvements** * `prioritize_improvements(criteria: string, limit: number)` ## Example Agent Interactions **User**: "What are users saying about our mobile app?" **Agent**: "Mobile App Feedback Analysis: * Overall Sentiment: 3.8/5 (Moderately Positive) * Top Issues: App crashes (45 mentions), Slow loading (32 mentions) * Top Requests: Dark mode (120 votes), Offline mode (95 votes) * Priority: Fix app crashes (High), Add dark mode (Medium)" ## Outcomes * **Feedback Processing**: 70% faster analysis * **Prioritization**: 40% improvement in feature prioritization * **User Satisfaction**: 25% increase in satisfaction scores * **Product Roadmap**: Data-driven roadmap decisions ## Next Steps * [Product Usage Analyst Example](/examples/product-usage-analyst) * [Feature Flag Manager Example](/examples/feature-flag-manager) # Product Usage Analyst Source: https://docs.pylar.ai/examples/product-usage-analyst Build an AI agent that analyzes product usage, feature adoption, user engagement, and identifies trends ## Overview A Product Usage Analyst powered by Pylar analyzes product usage patterns, feature adoption rates, user engagement metrics, and identifies trends to inform product decisions. ## What the Agent Needs to Accomplish The agent must: * Analyze product usage patterns * Track feature adoption rates * Measure user engagement * Identify usage trends * Compare user segments * Recommend feature improvements ## How Pylar Helps Pylar enables the agent by: * **Unified Usage View**: Combining product analytics, user data, and feature usage * **Real-time Analysis**: Querying current usage patterns * **Trend Identification**: Detecting usage trends over time * **Segment Comparison**: Comparing usage across user segments * **Data-Driven Insights**: Generating actionable product recommendations ```mermaid theme={null} graph LR subgraph "Data Sources" ANALYTICS[Product Analytics] USERS[User Data] FEATURES[Feature Usage] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_usage
track_adoption
identify_trends] AGENT[Usage Analyst] TEAM[Product Team] ANALYTICS --> PYLAR USERS --> PYLAR FEATURES --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple analytics tools and data sources * ❌ Manual usage analysis * ❌ Difficult to correlate features with engagement * ❌ Time-consuming trend identification **Implementation Complexity**: \~4-5 weeks ### With Pylar **Benefits**: * ✅ Single endpoint for all usage data * ✅ Automated usage analysis * ✅ Real-time trend detection * ✅ Easy feature comparison **Implementation Complexity**: \~5-6 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Product Analytics** (User actions, events, feature usage) 2. **Connect User Data** (User segments, subscription tiers) 3. **Connect Product Catalog** (Features, releases) ### Step 2: Create Usage Views **Feature Adoption View**: ```sql theme={null} CREATE VIEW feature_adoption AS SELECT f.feature_name, f.release_date, COUNT(DISTINCT u.user_id) as total_users, COUNT(DISTINCT CASE WHEN u.feature_used THEN u.user_id END) as adopted_users, (COUNT(DISTINCT CASE WHEN u.feature_used THEN u.user_id END) / NULLIF(COUNT(DISTINCT u.user_id), 0)) * 100 as adoption_rate, AVG(u.usage_count) as avg_usage_per_user, AVG(u.last_used_days_ago) as avg_days_since_last_use FROM product.features f LEFT JOIN analytics.feature_usage u ON f.feature_id = u.feature_id GROUP BY f.feature_name, f.release_date; ``` **User Engagement View**: ```sql theme={null} CREATE VIEW user_engagement AS SELECT u.user_id, u.user_segment, u.subscription_tier, u.active_days_last_30, u.features_used_count, u.total_actions, u.last_activity_date, -- Engagement score (u.active_days_last_30 * 0.4 + (u.features_used_count / 10) * 30 + (u.total_actions / 100) * 30) as engagement_score FROM analytics.user_usage u; ``` ### Step 3: Create MCP Tools **Tool 1: Analyze Feature Adoption** * `analyze_feature_adoption(feature_name: string, days_back: number)` **Tool 2: Get Usage Trends** * `get_usage_trends(metric: string, period: string)` **Tool 3: Compare User Segments** * `compare_user_segments(segment1: string, segment2: string, metric: string)` **Tool 4: Identify Usage Patterns** * `identify_usage_patterns(feature_id: string, user_segment: string)` ## Example Agent Interactions **User**: "How is the new dashboard feature being adopted?" **Agent**: "Dashboard Feature Adoption: * Adoption Rate: 42% (8,400 of 20,000 users) * Average Usage: 12 times per user * Top User Segment: Enterprise (65% adoption) * Growth Trend: +15% week-over-week * Recommendation: Promote to mid-market segment" ## Outcomes * **Feature Adoption**: 30% improvement in adoption rates * **User Engagement**: 25% increase in engagement * **Product Decisions**: Data-driven feature prioritization * **Trend Detection**: 60% faster identification of usage trends ## Next Steps * [Product Feedback Analyzer Example](/examples/product-feedback-analyzer) * [Feature Flag Manager Example](/examples/feature-flag-manager) # Revenue Operations Agent Source: https://docs.pylar.ai/examples/revenue-operations-agent Build an AI agent for revenue forecasting, deal analysis, pipeline health monitoring, and quota tracking ## Overview A Revenue Operations Agent powered by Pylar provides comprehensive revenue analytics, forecasts, deal analysis, and pipeline health monitoring to help revenue teams make data-driven decisions. ## What the Agent Needs to Accomplish The agent must: * Forecast revenue across multiple time periods * Analyze deal progression and conversion rates * Monitor pipeline health and identify risks * Track quota attainment and performance * Identify trends and patterns in revenue data * Generate revenue reports and insights ## How Pylar Helps Pylar enables the agent by: * **Unified Revenue View**: Combining deals, contracts, billing, and historical data * **Real-time Analytics**: Querying current revenue metrics and forecasts * **Multi-Source Integration**: Joining CRM, billing, and finance data * **Advanced Calculations**: Complex revenue calculations and forecasting * **Trend Analysis**: Identifying revenue patterns and trends ```mermaid theme={null} graph LR subgraph "Data Sources" CRM[CRM] BILLING[Billing] FINANCE[Finance] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
forecast_revenue
analyze_pipeline
track_quota] AGENT[RevOps Agent] TEAM[Revenue Team] CRM --> PYLAR BILLING --> PYLAR FINANCE --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Data scattered across CRM, billing, and finance systems * ❌ Manual revenue calculations and forecasting * ❌ Complex data aggregation across systems * ❌ Time-consuming report generation * ❌ Limited real-time insights * ❌ Difficult to track quota and performance **Implementation Complexity**: * 4-5 different system integrations * Custom revenue calculation logic * Manual forecasting models * Complex data aggregation * \~6-8 weeks development time ### With Pylar **Benefits**: * ✅ Single endpoint for all revenue data * ✅ Automated revenue calculations * ✅ Real-time forecasting * ✅ Unified quota tracking * ✅ Easy to update calculations * ✅ Built-in analytics **Implementation Complexity**: * Connect 4-5 data sources (1.5 hours) * Create revenue views (3 hours) * Build MCP tools with AI (2 hours) * Connect to agent builder (15 minutes) * **Total: \~7 hours** ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect CRM** (Deals, opportunities, contracts) 2. **Connect Billing System** (Invoices, subscriptions, payments) 3. **Connect Finance System** (Revenue recognition, financial data) 4. **Connect Sales Activity** (Quota, performance data) ### Step 2: Create Revenue Views **Revenue Forecast View**: ```sql theme={null} CREATE VIEW revenue_forecast AS SELECT DATE_TRUNC('month', close_date) as forecast_month, SUM(amount * (probability / 100)) as weighted_revenue, SUM(amount) as best_case_revenue, COUNT(*) as deal_count, AVG(probability) as avg_probability FROM crm.deals WHERE close_date >= CURRENT_DATE GROUP BY DATE_TRUNC('month', close_date); ``` **Quota Tracking View**: ```sql theme={null} CREATE VIEW quota_tracking AS SELECT rep_name, quota_amount, SUM(closed_won_amount) as attained_amount, (SUM(closed_won_amount) / quota_amount) * 100 as quota_attainment_percent, SUM(weighted_pipeline) as pipeline_value, (SUM(weighted_pipeline) / quota_amount) * 100 as pipeline_coverage_percent FROM sales.rep_performance GROUP BY rep_name, quota_amount; ``` ### Step 3: Create MCP Tools **Tool 1: Get Revenue Forecast** * `get_revenue_forecast(months_ahead: number, include_breakdown: boolean)` **Tool 2: Track Quota Attainment** * `get_quota_tracking(rep_name: string, period: string)` **Tool 3: Analyze Pipeline Health** * `analyze_pipeline_health(threshold: number)` **Tool 4: Revenue Trend Analysis** * `analyze_revenue_trends(period: string, metric: string)` ## Example Agent Interactions **User**: "What's our revenue forecast for Q2?" **Agent**: "Q2 Revenue Forecast: * Weighted Forecast: \$1.2M * Best Case: \$1.8M * Pipeline Coverage: 3.2x quota * Top Rep: Sarah Johnson (145% of quota)" ## Outcomes * **Forecast Accuracy**: 30% improvement * **Quota Visibility**: Real-time tracking * **Pipeline Health**: 25% better pipeline management * **Report Efficiency**: 85% reduction in report time ## Next Steps * [Sales Assistant Example](/examples/sales-assistant) * [Financial Analyst Example](/examples/financial-analyst) # Sales Assistant Source: https://docs.pylar.ai/examples/sales-assistant Build an AI agent that analyzes sales pipeline, identifies opportunities, forecasts revenue, and tracks deal progress ## Overview A Sales Assistant powered by Pylar analyzes sales pipeline data, identifies opportunities, forecasts revenue, and provides insights to help sales teams close more deals faster. ## What the Agent Needs to Accomplish The agent must: * Analyze sales pipeline and deal stages * Identify high-value opportunities * Forecast revenue based on pipeline data * Track deal progress and identify stalled deals * Provide insights on win rates and conversion metrics * Recommend next actions for deals * Analyze sales performance by rep, region, or product ## How Pylar Helps Pylar enables the agent by: * **Unified Pipeline View**: Combining CRM data, sales activity, and historical performance * **Real-time Analysis**: Querying current pipeline status and forecasts * **Multi-Source Integration**: Joining CRM data with product catalog and customer data * **Pattern Recognition**: Identifying successful deal patterns * **Actionable Insights**: Generating recommendations based on data ```mermaid theme={null} graph LR subgraph "Data Sources" CRM[CRM] PRODUCTS[Product Catalog] HISTORY[Sales History] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_pipeline
forecast_revenue
identify_opportunities] AGENT[Sales Assistant] TEAM[Sales Team] CRM --> PYLAR PRODUCTS --> PYLAR HISTORY --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple systems (CRM, sales tools, analytics) * ❌ Complex API integrations for each system * ❌ Manual pipeline analysis and forecasting * ❌ Difficult to correlate deals with customer data * ❌ Time-consuming report generation * ❌ Limited real-time insights **Implementation Complexity**: * 3-4 different API integrations * Custom pipeline analysis logic * Manual forecasting calculations * Complex data correlation * \~4-5 weeks development time ### With Pylar **Benefits**: * ✅ Single endpoint for all sales data * ✅ Real-time pipeline analysis * ✅ Automated forecasting * ✅ Unified customer-deal view * ✅ Easy to update analysis logic * ✅ Built-in analytics on sales patterns **Implementation Complexity**: * Connect 3-4 data sources (1 hour) * Create sales pipeline views (2.5 hours) * Build MCP tools with AI (1.5 hours) * Connect to agent builder (15 minutes) * **Total: \~5 hours** ## Step-by-Step Implementation ### Step 1: Connect Data Sources Connect your sales data sources: 1. **Connect CRM** (Salesforce/HubSpot - deals, opportunities, contacts) 2. **Connect Sales Activity** (Email, calls, meetings tracking) 3. **Connect Product Catalog** (Product pricing, configurations) 4. **Connect Customer Data** (Account information, historical purchases) ### Step 2: Create Sales Pipeline Views **Pipeline Overview View**: ```sql theme={null} CREATE VIEW pipeline_overview AS SELECT d.deal_id, d.deal_name, d.account_name, d.owner_name, d.stage, d.amount, d.probability, d.expected_close_date, d.created_date, DATEDIFF(d.expected_close_date, CURRENT_DATE) as days_to_close, -- Weighted pipeline value d.amount * (d.probability / 100) as weighted_value, -- Deal age DATEDIFF(CURRENT_DATE, d.created_date) as deal_age_days, -- Activity metrics a.email_count, a.call_count, a.meeting_count, a.last_activity_date, DATEDIFF(CURRENT_DATE, a.last_activity_date) as days_since_last_activity, -- Risk indicators CASE WHEN DATEDIFF(CURRENT_DATE, a.last_activity_date) > 14 THEN 1 ELSE 0 END as stalled_flag FROM crm.deals d LEFT JOIN sales.activity_summary a ON d.deal_id = a.deal_id; ``` **Revenue Forecast View**: ```sql theme={null} CREATE VIEW revenue_forecast AS SELECT DATE_TRUNC('month', expected_close_date) as forecast_month, stage, COUNT(*) as deal_count, SUM(amount) as total_pipeline_value, SUM(amount * (probability / 100)) as weighted_forecast, AVG(probability) as avg_probability, SUM(CASE WHEN stage = 'Closed Won' THEN amount ELSE 0 END) as closed_won_value FROM pipeline_overview WHERE expected_close_date >= CURRENT_DATE GROUP BY DATE_TRUNC('month', expected_close_date), stage ORDER BY forecast_month, stage; ``` **Opportunity Analysis View**: ```sql theme={null} CREATE VIEW opportunity_analysis AS SELECT p.*, -- Win probability based on stage CASE WHEN p.stage = 'Closed Won' THEN 100 WHEN p.stage = 'Negotiation' THEN 75 WHEN p.stage = 'Proposal' THEN 50 WHEN p.stage = 'Qualified' THEN 25 ELSE 10 END as stage_based_probability, -- Recommendation CASE WHEN p.stalled_flag = 1 THEN 'Re-engage customer' WHEN p.days_to_close < 7 AND p.probability < 50 THEN 'Increase activity' WHEN p.weighted_value > 100000 THEN 'Prioritize - high value' ELSE 'Continue normal cadence' END as recommended_action FROM pipeline_overview p; ``` ### Step 3: Create MCP Tools with AI **Tool 1: Get Pipeline Summary** * Prompt: "Create a tool to get sales pipeline summary by stage, rep, or date range" * AI generates: `get_pipeline_summary(stage: string, rep_name: string, start_date: date, end_date: date)` **Tool 2: Forecast Revenue** * Prompt: "Create a tool to forecast revenue for a specific time period" * AI generates: `forecast_revenue(months_ahead: number, include_probability: boolean)` **Tool 3: Identify Opportunities** * Prompt: "Create a tool to identify high-value opportunities or stalled deals" * AI generates: `identify_opportunities(min_value: number, stage: string, stalled_only: boolean)` **Tool 4: Analyze Sales Performance** * Prompt: "Create a tool to analyze sales performance by rep, region, or product" * AI generates: `analyze_sales_performance(group_by: string, start_date: date, end_date: date)` ### Step 4: Test and Publish 1. Test pipeline analysis 2. Verify revenue forecasting 3. Validate opportunity identification 4. Publish tools 5. Connect to agent builder ## Example Agent Interactions ### Scenario 1: Pipeline Summary **User**: "What's our current pipeline status?" **Agent** (using Pylar tools): 1. Calls `get_pipeline_summary(null, null, null, null)` 2. Responds: * "Current Pipeline Status: * Total Pipeline Value: \$2.4M * Weighted Forecast: \$1.2M * Deals by Stage: * Qualified: 45 deals (\$800K) * Proposal: 28 deals (\$900K) * Negotiation: 12 deals (\$500K) * Closed Won this month: \$200K" ### Scenario 2: Revenue Forecast **User**: "What's our revenue forecast for next quarter?" **Agent** (using Pylar tools): 1. Calls `forecast_revenue(3, true)` 2. Responds: * "Q2 Revenue Forecast: * Best Case: \$1.8M (all deals close) * Weighted Forecast: \$1.2M (probability-adjusted) * Committed: \$450K (closed deals) * At Risk: \$200K (stalled deals)" ### Scenario 3: Opportunity Identification **User**: "Show me high-value opportunities that need attention" **Agent** (using Pylar tools): 1. Calls `identify_opportunities(50000, null, true)` 2. Responds: * "High-Value Stalled Opportunities: * Enterprise Corp: \$150K, stalled 18 days, recommended: Re-engage * TechStartup: \$85K, stalled 12 days, recommended: Schedule meeting * ..." ## Outcomes ### Sales Performance * **Pipeline Visibility**: 100% real-time pipeline visibility * **Forecast Accuracy**: 25% improvement in forecast accuracy * **Deal Velocity**: 20% faster deal progression * **Win Rate**: 15% improvement in win rates ### Efficiency Gains * **Report Generation**: 90% reduction in report creation time * **Opportunity Identification**: 3x faster identification of high-value deals * **Activity Tracking**: Automated tracking of sales activities * **Team Productivity**: 2x more deals managed per rep ### Data-Driven Decisions * **Pattern Recognition**: Identification of successful deal patterns * **Risk Identification**: Early detection of at-risk deals * **Performance Insights**: Clear visibility into rep and region performance * **Optimization**: Data-driven improvements to sales process ## Best Practices 1. **Regular Updates**: Keep pipeline data current 2. **Activity Tracking**: Monitor sales activity regularly 3. **Forecast Reviews**: Review forecasts weekly 4. **Stalled Deal Follow-up**: Follow up on stalled deals within 48 hours 5. **Performance Analysis**: Analyze performance trends monthly ## Next Steps * [Revenue Operations Agent Example](/examples/revenue-operations-agent) - Track revenue operations * [Lead Qualification Agent Example](/examples/lead-qualification-agent) - Qualify leads automatically * [Customer Support Agent Example](/examples/customer-support-agent) - Support customers effectively # Sales Territory Optimizer Source: https://docs.pylar.ai/examples/sales-territory-optimizer Build an AI agent that allocates territories, balances workload, and identifies growth opportunities ## Overview A Sales Territory Optimizer agent powered by Pylar analyzes sales performance, geographic data, and account information to optimize territory allocation and identify growth opportunities. ## What the Agent Needs to Accomplish The agent must: * Analyze territory performance * Balance workload across territories * Identify growth opportunities * Optimize territory boundaries * Track account distribution * Recommend territory adjustments ## How Pylar Helps Pylar enables the agent by: * **Unified Territory View**: Combining sales data, geographic data, and account information * **Performance Analysis**: Real-time territory performance metrics * **Workload Balancing**: Analyzing and optimizing rep workload * **Growth Identification**: Identifying untapped opportunities ```mermaid theme={null} graph LR subgraph "Data Sources" SALES[Sales Data] GEO[Geographic Data] ACCOUNTS[Account Info] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
analyze_territories
balance_workload
identify_opportunities] AGENT[Territory Optimizer] TEAM[Sales Ops] SALES --> PYLAR GEO --> PYLAR ACCOUNTS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Manual territory analysis * ❌ Complex data aggregation * ❌ Limited visibility into territory performance * ❌ Time-consuming optimization **Implementation Complexity**: \~5-6 weeks ### With Pylar **Benefits**: * ✅ Automated territory analysis * ✅ Real-time performance tracking * ✅ Data-driven optimization * ✅ Easy territory adjustments **Implementation Complexity**: \~6-7 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect CRM** (Accounts, deals, rep assignments) 2. **Connect Geographic Data** (Territory boundaries, regions) 3. **Connect Sales Performance** (Rep performance, quota data) ### Step 2: Create Territory Views **Territory Performance View**: ```sql theme={null} CREATE VIEW territory_performance AS SELECT t.territory_name, t.region, COUNT(DISTINCT a.account_id) as account_count, SUM(d.amount) as total_pipeline, SUM(CASE WHEN d.stage = 'Closed Won' THEN d.amount ELSE 0 END) as closed_won, COUNT(DISTINCT r.rep_id) as rep_count, AVG(r.quota_attainment) as avg_quota_attainment FROM territories t LEFT JOIN accounts a ON t.territory_id = a.territory_id LEFT JOIN deals d ON a.account_id = d.account_id LEFT JOIN reps r ON t.territory_id = r.territory_id GROUP BY t.territory_name, t.region; ``` ### Step 3: Create MCP Tools **Tool 1: Analyze Territory Performance** * `analyze_territory_performance(territory_name: string)` **Tool 2: Optimize Territory Allocation** * `optimize_territory_allocation(criteria: string)` **Tool 3: Identify Growth Opportunities** * `identify_growth_opportunities(region: string, min_value: number)` **Tool 4: Balance Workload** * `balance_workload(territory_id: string)` ## Example Agent Interactions **User**: "Analyze territory performance in the West region" **Agent**: "West Region Territory Analysis: * Top Territory: California (45 accounts, \$2.1M pipeline) * Underperforming: Nevada (12 accounts, \$300K pipeline) * Recommendation: Redistribute 8 accounts from CA to NV * Growth Opportunity: 15 untapped accounts in Oregon" ## Outcomes * **Territory Balance**: 30% improvement * **Rep Utilization**: 25% better distribution * **Revenue Growth**: 20% increase in underperforming territories * **Planning Efficiency**: 70% reduction in planning time ## Next Steps * [Sales Assistant Example](/examples/sales-assistant) * [Revenue Operations Agent Example](/examples/revenue-operations-agent) # Supply Chain Coordinator Source: https://docs.pylar.ai/examples/supply-chain-coordinator Build an AI agent that manages inventory levels, tracks shipments, and optimizes reorder points ## Overview A Supply Chain Coordinator powered by Pylar manages inventory levels, tracks shipments, optimizes reorder points, and ensures efficient supply chain operations. ## What the Agent Needs to Accomplish The agent must: * Monitor inventory levels * Track shipments and deliveries * Optimize reorder points * Identify stockouts and overstock * Analyze supplier performance * Generate supply chain reports ## How Pylar Helps Pylar enables the agent by: * **Unified Supply Chain View**: Combining inventory, shipments, and supplier data * **Real-time Monitoring**: Querying current inventory and shipment status * **Automated Optimization**: Calculating optimal reorder points * **Performance Analysis**: Analyzing supplier and logistics performance ```mermaid theme={null} graph LR subgraph "Data Sources" INVENTORY[Inventory] SHIPMENTS[Shipments] SUPPLIERS[Supplier Data] end PYLAR[Pylar
Unified Views] TOOLS[MCP Tools
monitor_inventory
track_shipments
optimize_reorder] AGENT[Supply Chain Coordinator] TEAM[Operations Team] INVENTORY --> PYLAR SHIPMENTS --> PYLAR SUPPLIERS --> PYLAR PYLAR --> TOOLS TOOLS --> AGENT AGENT --> TEAM style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Without Pylar vs With Pylar ### Without Pylar **Challenges**: * ❌ Multiple systems (inventory, shipping, suppliers) * ❌ Manual inventory tracking * ❌ Complex reorder calculations * ❌ Limited visibility **Implementation Complexity**: \~5-6 weeks ### With Pylar **Benefits**: * ✅ Single endpoint for supply chain data * ✅ Real-time inventory monitoring * ✅ Automated reorder optimization * ✅ Comprehensive visibility **Implementation Complexity**: \~6-7 hours ## Step-by-Step Implementation ### Step 1: Connect Data Sources 1. **Connect Inventory System** (Stock levels, products) 2. **Connect Shipping System** (Shipments, tracking) 3. **Connect Supplier System** (Supplier data, orders) ### Step 2: Create Supply Chain Views **Inventory Status View**: ```sql theme={null} CREATE VIEW inventory_status AS SELECT p.product_id, p.product_name, i.current_stock, i.reorder_point, i.max_stock, i.avg_daily_sales, -- Stock status CASE WHEN i.current_stock <= 0 THEN 'Out of Stock' WHEN i.current_stock <= i.reorder_point THEN 'Low Stock' WHEN i.current_stock >= i.max_stock THEN 'Overstock' ELSE 'Normal' END as stock_status, -- Days until reorder CASE WHEN i.avg_daily_sales > 0 THEN (i.current_stock - i.reorder_point) / i.avg_daily_sales ELSE NULL END as days_until_reorder FROM products p JOIN inventory.stock i ON p.product_id = i.product_id; ``` ### Step 3: Create MCP Tools **Tool 1: Check Inventory Status** * `check_inventory_status(product_id: string, warehouse_id: string)` **Tool 2: Track Shipment** * `track_shipment(shipment_id: string, order_id: string)` **Tool 3: Optimize Reorder Points** * `optimize_reorder_points(product_id: string, lead_time_days: number)` **Tool 4: Analyze Supplier Performance** * `analyze_supplier_performance(supplier_id: string, period: string)` ## Example Agent Interactions **User**: "What products need reordering?" **Agent**: "Low Stock Alert: * Product A: 45 units (reorder point: 100) - ORDER NOW * Product B: 120 units (reorder point: 150) - Order in 3 days * Product C: 0 units - OUT OF STOCK - URGENT Supplier Performance: * Supplier X: 98% on-time delivery, recommend for Product A * Supplier Y: 95% on-time, recommend for Product B" ## Outcomes * **Stockouts**: 50% reduction * **Overstock**: 35% reduction * **Inventory Costs**: 25% reduction * **Efficiency**: 60% improvement ## Next Steps * [IT Operations Monitor Example](/examples/it-operations-monitor) # Frequently Asked Questions Source: https://docs.pylar.ai/help/faq Find answers to common questions about Pylar, connections, views, MCP tools, and more ## General Questions ### What is Pylar? Pylar is a secure data access layer for AI agents that enables interaction with structured data sources. It provides governed SQL views, AI-powered MCP tool creation, and seamless multi-database integration without requiring direct database access or complex API integrations. Read our detailed introduction to understand Pylar's capabilities ### How is Pylar different from connecting directly to databases? Pylar provides several key advantages: * **Governed Access**: Agents only access data through SQL views you create, never raw database access * **Unified Interface**: Single MCP endpoint for all data sources, eliminating API hassles * **Security**: Centralized security and governance with views as the only access level * **Easy Updates**: Modify views and tools without redeploying agents * **Observability**: Built-in Evals dashboard for monitoring agent interactions * **Multi-Database**: Join data across multiple databases and warehouses seamlessly Learn about the benefits of using Pylar ### What data sources can I connect to Pylar? Pylar supports two types of data sources: **Business Applications** (synced to Pylar Warehouse): * Google Sheets, HubSpot, Salesforce, Airtable, and more **Databases and Data Warehouses** (indexed, data stays in place): * BigQuery, Snowflake, PostgreSQL, MySQL, Redshift, MotherDuck, Supabase, AlloyDB, Databricks, and more See the complete list of supported data sources ### Do I need to give Pylar direct database access? For databases and data warehouses, you need to: 1. Provide connection credentials (host, database name, username, password) 2. Whitelist Pylar's IP address: `34.122.205.142` However, Pylar only indexes your data for querying and autocompletion. Your data remains in its original location, and queries are executed on your infrastructure. Agents never get raw database access—only through views you create. Learn about security best practices ## Getting Started ### How do I get started with Pylar? The Pylar workflow is straightforward: 1. **Connect Databases**: Connect your data sources to Pylar 2. **Create a Project**: Organize your views in a project 3. **Create Views**: Use the SQL IDE to create governed views 4. **Create MCP Tools**: Use AI or manually create MCP tools on your views 5. **Test Tools**: Test your tools before deploying 6. **Publish**: Get your MCP HTTP Stream URL and Authorization Token 7. **Connect to Agent Builder**: Paste credentials into your agent builder 8. **Monitor with Evals**: Track performance and optimize Follow our step-by-step quick start guide ### What role do I need to connect data sources? You need at least **Analyst role privileges** in Pylar to connect data sources. If you don't have the necessary database credentials, you can invite a team member who does have access. ### How long does it take to set up Pylar? Setting up Pylar typically takes: * **Connecting data sources**: 30-60 minutes per source * **Creating views**: 1-2 hours depending on complexity * **Creating MCP tools**: 30 minutes to 1 hour (using AI) * **Testing and publishing**: 15-30 minutes **Total**: You can have your first agent running in 2-4 hours, compared to weeks of development without Pylar. ## Connections ### What IP address do I need to whitelist? Pylar's IP address is **34.122.205.142** (permanently assigned). Whitelist this IP in your database firewall settings to allow Pylar to connect. The process varies by database provider: * **AWS RDS**: Add to security group inbound rules * **Google Cloud SQL**: Add to authorized networks * **Azure Database**: Add to firewall rules * **Self-hosted**: Configure server firewall (iptables, ufw, etc.) Learn how to connect your databases ### Can I connect multiple instances of the same data source? Yes! You can connect multiple instances of the same data source (e.g., multiple Google Sheets documents, multiple Snowflake databases). Each connection must have a unique name following these rules: * Lowercase letters only * Numbers and underscores allowed * No spaces or special characters ### How do I name my connections? Connection names must follow these rules: * ✅ **Allowed**: Lowercase letters, numbers, underscores * ❌ **Not Allowed**: Capital letters, special characters, spaces **Good examples**: `production_db`, `snowflake_analytics`, `customer_data_v2` **Bad examples**: `Production DB`, `snowflake-analytics`, `Customer Data` This name will be used in SQL queries to reference the connection. ### What happens after I connect a data source? After connecting: * **Business Applications**: Data syncs to Pylar Warehouse (may take time depending on data volume) * **Databases**: Data is indexed for querying (your data stays in place) You'll receive an email and in-app notification when the sync/indexing is complete and you can start querying. ### Can I use SSH connections for enhanced security? Yes! Pylar supports SSH tunnel connections for enhanced security. This involves: 1. Setting up a bastion VM in your VPC 2. Installing the database auth proxy 3. Configuring SSH key authentication 4. Connecting through the SSH tunnel This provides maximum security for sensitive databases. Learn about SSH tunnel connections ## Creating Views ### What is a data view? A data view is a governed SQL query that defines what data agents can access. Views are the only level of access agents get—they never access raw database tables. Views provide: * **Security**: Control exactly what data is exposed * **Governance**: Scoped access to specific data * **Flexibility**: Easy to update without redeploying agents Learn about creating data views ### Can I join data from multiple databases? Yes! Pylar supports cross-database joins. You can join data from: * Different databases (Snowflake + PostgreSQL) * Different warehouses (BigQuery + Redshift) * Business applications (HubSpot + Salesforce) * Local dataframes loaded into Pylar This enables powerful unified views across all your data sources. Learn how to join data across multiple sources ### How do I write my first view? 1. Open the SQL IDE in Pylar 2. Select your data source from the dropdown 3. Write your SQL query 4. Run the query to test 5. Save it as a view Pylar provides autocompletion and syntax highlighting to help you write queries. Follow our tutorial to create your first view ### Can I query local dataframes? Yes! You can load dataframes into Pylar and query them using SQL. This is useful for: * Testing queries with sample data * Joining local data with database data * Analyzing CSV/excel files * Prototyping before connecting production databases ## MCP Tools ### What is an MCP tool? An MCP (Model Context Protocol) tool is a function that AI agents can call to interact with your data views. Tools define: * **Function name**: What the agent calls * **Description**: What the tool does * **SQL query**: The query to execute * **Parameters**: Inputs the agent can provide Learn about MCP tool components ### How do I create MCP tools? You can create MCP tools in two ways: 1. **AI-Powered Creation**: Describe what you want in natural language, and Pylar's AI generates the tool 2. **Manual Creation**: Build tools manually with full control Most users start with AI-powered creation and then refine manually. Learn how to create tools using AI ### Can I create multiple tools on the same view? Yes! You can create multiple MCP tools on the same data view. Each tool can: * Query different aspects of the view * Have different parameters * Serve different use cases For example, you might have: * `get_customer_info` - Get basic customer details * `get_customer_orders` - Get customer order history * `get_customer_support_tickets` - Get support history All using the same underlying customer 360 view. ### How do I test my MCP tools? Pylar provides a built-in testing interface: 1. Select the tool you want to test 2. Enter test parameters 3. Run the test 4. Review the results 5. Check the SQL query executed 6. Verify the output Learn how to test your MCP tools ### Can I edit MCP tools after creating them? Yes! You can edit MCP tools at any time: * Modify function names and descriptions * Update SQL queries * Add or remove parameters * View the JSON structure Changes take effect immediately—no redeployment needed. Learn how to edit your tools ## Publishing and Deployment ### How do I publish my tools? 1. After creating and testing your tools, click **"Publish"** in Pylar 2. You'll receive: * **MCP HTTP Stream URL**: The endpoint for your agent builder * **Authorization Bearer Token**: Authentication token 3. Copy these credentials to your agent builder Learn how to publish and deploy your tools ### Do I need to redeploy when I update views or tools? No! That's one of Pylar's key benefits. When you: * Update a SQL view * Modify an MCP tool * Add or remove tools The changes are reflected immediately across all agent builders. No redeployment needed. ### Which agent builders can I use? Pylar works with any agent builder that supports MCP (Model Context Protocol), including: **AI Coding Assistants**: * Claude Desktop * Cursor * Windsurf * VS Code (with MCP extension) **Agent Frameworks**: * LangGraph * OpenAI Platform * Custom Python/JavaScript agents **No-Code Platforms**: * Zapier * Make (Integromat) * n8n See guides for connecting to different agent builders ### How do I connect to Claude Desktop? 1. Get your MCP credentials from Pylar (HTTP Stream URL and Bearer Token) 2. Edit Claude Desktop's MCP configuration file 3. Add Pylar as an MCP server 4. Restart Claude Desktop 5. Your tools will be available in Claude Step-by-step Claude Desktop connection guide ## Monitoring and Evals ### What is Evals? Evals is Pylar's built-in observability dashboard that provides: * **Performance Metrics**: Success rates, error rates, call counts * **Error Analysis**: Detailed error breakdown and patterns * **Query Shapes**: Understanding how agents query your data * **Raw Logs**: Complete audit trail of all tool calls Learn about Pylar's Evals dashboard ### How do I access the Evals dashboard? Click the **"Eval"** button in the top-right corner of your Pylar workspace. You'll see: * Overview metrics (Total Count, Success Count, Error Count) * Visual graphs (Calls/Success/Errors over time, Success/Error rates) * Error Explorer * Query Shape analysis * Raw Logs Learn how to use the Evals dashboard ### How do I analyze errors? Use the Error Explorer in the Evals dashboard to: 1. Filter by MCP tool 2. View error codes and frequencies 3. Analyze error patterns 4. Review raw logs for specific errors 5. Identify common issues Learn how to analyze and fix errors ### What are query shapes? Query shapes are patterns in how agents query your data. They show: * Common query patterns * Parameter usage * Data access patterns * Optimization opportunities Understanding query shapes helps you improve your tools and views. Learn how to analyze query shapes ## Security and Governance ### How secure is my data with Pylar? Pylar employs multiple security layers: * **Encryption**: Default encryption for all data * **Secret Management**: Credentials stored in Google Cloud Platform's Secret Key Manager * **HTTPS**: All API interactions use HTTPS * **Governed Access**: Views are the only access level—agents never get raw database access * **Access Control**: Stringent access controls on all data Learn about Pylar's security features ### Do agents have access to my raw database? No! Agents only access data through the SQL views you create. This means: * ✅ You control exactly what data is exposed * ✅ Agents never see raw database tables * ✅ You can filter sensitive data in views * ✅ Views provide an additional security layer ### Can I use dedicated database users for Pylar? Yes! This is a security best practice: 1. Create a dedicated database user for Pylar 2. Grant only necessary permissions (read-only if possible) 3. Limit access to specific schemas or tables 4. Use audit logging to monitor all queries This provides granular control and better security. ### How do I handle sensitive data in views? Filter sensitive data in your views: * Exclude PII, financial data, or other sensitive columns * Implement row-level security with WHERE clauses * Use column selection to only expose necessary data * Document what each view exposes ## Troubleshooting ### My connection is failing. What should I check? Common issues and solutions: 1. **IP Whitelisting**: Ensure `34.122.205.142` is whitelisted 2. **Credentials**: Verify username and password are correct 3. **Network**: Check if database is publicly accessible 4. **Firewall**: Review firewall rules and security groups 5. **Database Status**: Verify database is running and accessible Get help troubleshooting connection issues ### My data isn't showing up after connecting * **Wait for Indexing**: Databases need time to index (you'll get an email when complete) * **Check Permissions**: Verify user has SELECT permissions on tables * **Verify Connection**: Test the connection in Pylar * **Check Logs**: Review connection logs for errors ### My MCP tool is returning errors 1. **Check Evals Dashboard**: Review error details in Evals 2. **Test the Tool**: Use Pylar's test interface 3. **Verify SQL Query**: Check if the SQL query works directly 4. **Check Parameters**: Ensure parameters are correctly defined 5. **Review Logs**: Check raw logs for specific error messages ### My agent can't access the tools 1. **Verify Credentials**: Check MCP HTTP Stream URL and Bearer Token 2. **Test Connection**: Ensure agent builder can reach Pylar 3. **Check Authentication**: Verify Bearer Token is correct 4. **Review Agent Builder Logs**: Check for connection errors 5. **Validate Tools**: Ensure tools are published and active ## Pricing and Limits ### Is there a free tier? Contact Pylar support to learn about pricing plans and free tier availability. ### Are there rate limits? Pylar is designed to handle high-volume queries. For databases, queries execute on your infrastructure, so limits depend on your database capacity. For Business Applications, check with Pylar support for specific limits. ### Can I use Pylar for production workloads? Yes! Pylar is designed for production use with: * High availability * Scalability * Security and compliance * Enterprise-grade infrastructure ## Support ### Where can I get help? * **Documentation**: Browse our comprehensive guides * **Examples**: Check out our agent examples * **Support**: Contact Pylar support team ### How do I report bugs or request features? Contact Pylar support with: * Bug descriptions * Feature requests * Feedback * Questions We're here to help! *** ## Still Have Questions? If you can't find the answer you're looking for, check out: * [Quick Start Guide](/introduction/quick-start) - Get started with Pylar * [All Examples](/examples/customer-support-agent) - See real-world use cases * [Documentation](/learn/making-connections/overview) - Comprehensive guides Start building your first agent with Pylar # Troubleshooting Guide Source: https://docs.pylar.ai/help/troubleshooting Common issues and solutions for Pylar connections, views, tools, and agents ## Connection Issues ### Connection Test Fails **Symptoms**: Connection test fails when trying to connect a database **Common Causes**: * IP address not whitelisted * Incorrect credentials * Database not publicly accessible * Firewall blocking connections **Solutions**: 1. **Verify IP Whitelisting**: * Ensure `34.122.205.142` is whitelisted in your firewall * Check security group settings (AWS, GCP, Azure) * Review network policies (Snowflake) 2. **Check Credentials**: * Verify username and password are correct * Test credentials in a database client * Ensure user has necessary permissions 3. **Network Connectivity**: * Verify database is publicly accessible * Check if database is in private VPC (may need SSH tunnel) * Test connection from your local machine 4. **Database Status**: * Ensure database is running * Check database logs for connection attempts * Verify port number is correct More detailed connection troubleshooting ### Data Not Appearing After Connection **Symptoms**: Connection succeeds but data doesn't appear in queries **Solutions**: * **Wait for Indexing**: Databases need time to index (check email notification) * **Verify Permissions**: Ensure database user has SELECT permissions * **Check Schema/Table Names**: Verify you're using correct names * **Review Connection Logs**: Check for indexing errors ### Connection Timeout **Symptoms**: Connection attempt times out **Solutions**: * Check network connectivity * Verify firewall allows connections * Ensure database is accessible from internet * Review security group settings * Consider using SSH tunnel for private databases ## View and Query Issues ### SQL Query Errors **Symptoms**: Query fails with syntax or execution errors **Solutions**: 1. **Check Syntax**: Review SQL syntax carefully 2. **Test in Database**: Run query directly in database client 3. **Verify Table Names**: Ensure table/schema names are correct 4. **Check Permissions**: Verify user has access to tables 5. **Review Error Message**: Check specific error details in Pylar ### Cross-Database Join Not Working **Symptoms**: Joins between different databases fail **Solutions**: * Verify both connections are active * Check connection names in query * Ensure join keys match data types * Review query in SQL IDE for syntax errors ### View Performance Issues **Symptoms**: Views are slow or timing out **Solutions**: * Add appropriate WHERE clauses to filter data * Create indexes on join columns * Limit result sets with LIMIT clause * Optimize queries for your database type * Consider materialized views for complex queries ## MCP Tool Issues ### Tool Returns Errors **Symptoms**: MCP tool calls fail or return errors **Solutions**: 1. **Check Evals Dashboard**: * Review error details in Evals * Check error frequency and patterns * Review raw logs for specific errors 2. **Test Tool in Pylar**: * Use Pylar's test interface * Verify SQL query works * Check parameter values 3. **Verify Tool Definition**: * Review function name and description * Check SQL query syntax * Verify parameters are correctly defined 4. **Check Data Access**: * Ensure view is accessible * Verify data exists in view * Check permissions on underlying tables Learn how to test and debug tools ### Agent Can't Find Tools **Symptoms**: Agent builder can't see or access MCP tools **Solutions**: 1. **Verify Publishing**: * Ensure tools are published in Pylar * Check tool status is "Active" * Verify view is published 2. **Check Credentials**: * Verify MCP HTTP Stream URL is correct * Check Authorization Bearer Token * Ensure credentials are copied correctly 3. **Test Connection**: * Verify agent builder can reach Pylar endpoint * Check network connectivity * Review agent builder logs 4. **Agent Builder Configuration**: * Verify MCP configuration is correct * Check agent builder supports MCP * Review agent builder documentation ### Tool Parameters Not Working **Symptoms**: Tool parameters aren't being passed correctly **Solutions**: * Verify parameter names match tool definition * Check parameter types (string, number, etc.) * Review parameter validation rules * Test with different parameter values * Check agent builder parameter formatting ## Agent Builder Connection Issues ### Claude Desktop Not Connecting **Symptoms**: Claude Desktop can't connect to Pylar **Solutions**: 1. **Check MCP Configuration**: * Verify configuration file syntax * Ensure URL and token are correct * Check file location 2. **Restart Claude Desktop**: * Close and restart after configuration changes * Check for error messages on startup 3. **Verify Network**: * Ensure Claude Desktop can reach Pylar URL * Check firewall settings * Review network connectivity Claude Desktop connection guide ### HTTP-Based Agent Builders (Zapier, Make, n8n) **Symptoms**: HTTP requests to Pylar fail **Solutions**: * Verify HTTP Stream URL is correct * Check Authorization header format (Bearer token) * Review request format (MCP HTTP Stream protocol) * Test with curl or Postman first * Check agent builder HTTP configuration ## Data Issues ### Data Not Updating **Symptoms**: Data in views is stale or not updating **Solutions**: **For Business Applications**: * Check sync status in Connections * Manually trigger sync if available * Verify sync schedule * Review sync logs **For Databases**: * Data is queried in real-time * Verify database data is current * Check if query filters are excluding data * Review connection status ### Incorrect Data in Views **Symptoms**: View returns unexpected or incorrect data **Solutions**: * Review SQL query logic * Test query directly in database * Verify join conditions * Check WHERE clause filters * Review data types and conversions * Validate data in source systems ## Performance Issues ### Slow Queries **Symptoms**: Queries take too long to execute **Solutions**: * Add appropriate filters (WHERE clauses) * Use LIMIT to restrict result sets * Optimize join conditions * Create indexes on join columns * Review query execution plan * Consider materialized views for complex queries ### High Error Rates **Symptoms**: High error rate in Evals dashboard **Solutions**: 1. **Analyze Errors**: * Review Error Explorer in Evals * Identify common error patterns * Check error frequencies 2. **Fix Root Causes**: * Update SQL queries based on errors * Fix parameter validation * Improve error handling in tools 3. **Monitor Continuously**: * Use Evals dashboard regularly * Set up alerts for high error rates * Review query shapes for patterns Learn how to analyze and fix errors ## Getting More Help ### Review Documentation * [Connection Troubleshooting](/learn/making-connections/troubleshooting-connections) * [Testing Your Tools](/learn/building-mcp-tools/testing-your-tools) * [Evals Dashboard](/learn/evals/evals-dashboard) ### Check Examples * [Customer Support Agent](/examples/customer-support-agent) * [Sales Assistant](/examples/sales-assistant) * See how others solved similar problems ### Contact Support If you're still experiencing issues: * Contact Pylar support team * Provide error messages and logs * Include steps to reproduce * Share relevant configuration details *** Browse our FAQ for more answers # Quick Start Source: https://docs.pylar.ai/introduction/quick-start Get started with Pylar in minutes - connect databases, create views, build MCP tools, and deploy to your AI agents ## Prerequisites Before you begin, make sure you have: * **Pylar Account**: Sign up at [pylar.ai](https://www.pylar.ai) * **Database Credentials**: Access to at least one supported database or data warehouse * **AI Agent Builder**: An agent builder that supports MCP tools (Claude Desktop, Cursor, Windsurf, or custom) Don't have a Pylar account yet? [Sign up for free](https://www.pylar.ai) to get started. ## Step 1: Connect Your Databases Start by connecting Pylar to your data sources. You can connect multiple databases and warehouses. ### Supported Data Sources Pylar supports a wide range of data sources: * **BigQuery** * **Snowflake** * **PostgreSQL** * **MySQL** * **Redshift** * **AlloyDB** * **Databricks** * **And more...** ### Add a Connection 1. Log in to your [Pylar dashboard](https://dashboard.pylar.ai) 2. Navigate to **Connections** → **Add Connection** 3. Select your database type 4. Enter your connection credentials 5. Test the connection and save Start with a development or staging database to test Pylar before connecting production systems. Your credentials are encrypted and stored securely. Pylar never exposes your raw database credentials to AI agents. ## Step 2: Create a Project Projects are containers for your views and MCP tools. All your work is organized within projects. 1. From the dashboard, click **Create Project** 2. Give your project a name (e.g., "Customer Analytics" or "Error Monitoring") 3. Optionally add a description 4. Click **Create** Your project is now ready. You can create multiple projects to organize different use cases or teams. ## Step 3: Create Your First View Views define what data AI agents can access. They're the only level of access agents get—no raw database access. ### Open the SQL IDE 1. In your project, click **Create View** 2. The SQL IDE opens with your available data sources Pylar interface showing project view with create view option ### Select Your Data Source 1. Choose a data source from the dropdown 2. You can see available databases, schemas, and tables 3. Select the database you want to query ### Write Your Query Use the SQL IDE to write your query. You can: * **Query Single Tables**: Select from individual tables * **Join Multiple Tables**: Combine data from multiple tables * **Cross-Database Joins**: Join across different databases and warehouses in a single query * **Apply Filters**: Use WHERE clauses to filter data * **Aggregate Data**: Use GROUP BY, aggregations, and window functions Pylar's SQL IDE supports all standard SQL operations. You can write complex queries just like you would in any SQL editor. ### Example: Customer Analytics View ```sql theme={null} -- Customer Analytics View -- This view provides aggregated customer data for AI analysis -- without exposing PII or sensitive financial details SELECT c.customer_id, c.region, c.signup_date, COUNT(o.order_id) as total_orders, SUM(o.amount) as total_revenue, AVG(o.amount) as avg_order_value, MAX(o.order_date) as last_order_date FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id WHERE c.is_active = true GROUP BY c.customer_id, c.region, c.signup_date; ``` ### Example: Cross-Database Join ```sql theme={null} -- Join data across multiple databases SELECT customers.name, orders.total, payments.status FROM bigquery.production.customers customers JOIN snowflake.analytics.orders orders ON customers.id = orders.customer_id JOIN postgres.payments.payments payments ON orders.id = payments.order_id WHERE orders.date >= '2024-01-01'; ``` ### Save Your View 1. Click **Save View** when your query is ready 2. Give your view a descriptive name 3. Add a description (this helps when creating MCP tools) 4. Your view is now saved in your project Test your query in the SQL IDE before saving. You can preview results to ensure the data looks correct. ## Step 4: Create MCP Tools Once your view is created, you can build MCP tools that govern how AI agents interact with your data. You can create multiple MCP tools on a single view, each with different purposes. ### Method 1: Create with AI (Recommended) Use natural language to describe what you want, and Pylar's AI will configure the MCP tool for you. 1. Click **Create MCP Tool** on your view 2. Select **Create with AI** 3. Write a natural language prompt describing what you want: Example prompts: * *"Create a tool to fetch error codes, events, and deal information"* * *"Build a tool that returns customer analytics by region"* * *"Make a tool to get order history for a specific customer"* 4. Pylar's AI will: * Understand your intent * Configure tool parameters * Generate tool descriptions * Set up the tool schema 5. Review the generated tool configuration 6. Make any adjustments if needed 7. Click **Save Tool** ### Method 2: Create Manually For more control, you can configure the tool manually: 1. Click **Create MCP Tool** on your view 2. Select **Create Manually** 3. Configure: * **Tool Name**: Descriptive name for the tool * **Description**: What the tool does * **Parameters**: Input parameters the tool accepts * **Query Logic**: How parameters map to your SQL view * **Response Format**: Structure of returned data 4. Click **Save Tool** You can create multiple MCP tools on the same view. Each tool can have different parameters, filters, or purposes, giving you flexibility in how agents interact with your data. ## Step 5: Test Your MCP Tools Before deploying, test your MCP tools to ensure they work correctly. 1. Click on any MCP tool you've created 2. Select **Test Tool** 3. Enter test parameters 4. Click **Run Test** 5. Review the results: * Verify the query executes correctly * Check the response format * Ensure data is returned as expected * Look for any errors Testing helps catch issues before deploying to production. Test with various parameter combinations to ensure robustness. ## Step 6: Publish Your Tools Once your MCP tools are ready, publish them to make them available to AI agents. 1. In your project, click **Publish** 2. Pylar generates: * **MCP Server Link**: A unique URL for your tools * **Header Token**: An authentication token for secure access 3. Copy both the link and the header token Keep your header token secure. It provides access to your data views. Don't share it publicly or commit it to version control. ## Step 7: Connect to Your Agent Builder Add your published tools to any agent builder that supports MCP. ### Add to Agent Builder 1. Open your agent builder (Claude Desktop, Cursor, Windsurf, etc.) 2. Navigate to MCP configuration settings 3. Add a new MCP server: * **Server URL**: Paste your MCP server link * **Authorization Header**: Add your header token (format: `Bearer YOUR_TOKEN`) 4. Save and restart your agent ### Verify Connection 1. In your agent, ask it to use your new tool 2. The agent should be able to access your data view 3. Test a few queries to ensure everything works Your tools are now live! The agent can query your data through the governed views you created. ## Step 8: Monitor with Evals Once your agent is running, use Pylar's Evals to understand how agents interact with your views. ### Access Evals 1. In your Pylar dashboard, click **Evals** 2. Select your project and view 3. Explore comprehensive analytics ### What You'll See Evals provide in-depth insights: * **Interaction Patterns**: How agents are using your tools * **Success vs. Errors**: Track successful queries and failures * **Error Analysis**: Detailed breakdown of errors: * What errors occurred * When they happened * Why they failed * How to fix them * **Query Shape**: Understand the types of queries agents are making * **Raw Logs**: Access full query logs for debugging ### Use Evals to Improve Based on evals insights, you can: 1. **Adjust View Scope**: Modify your SQL views to include or exclude data 2. **Refine MCP Tools**: Update tool parameters or descriptions 3. **Add New Tools**: Create additional tools for common use cases 4. **Fix Errors**: Address issues revealed in the error analysis Evals help you iteratively improve your views and tools. Make adjustments on the Pylar platform, and changes automatically reflect in all connected agent builders. ## Iterate and Improve One of Pylar's key features is the ability to iterate without disruption. ### Make Changes Anytime You can adjust: * **SQL Queries**: Update your view queries to change data scope * **View Definitions**: Modify what data is included * **MCP Tools**: Add, remove, or modify tools * **Tool Configurations**: Update parameters or descriptions ### Changes Reflect Automatically 1. Make your changes in the Pylar platform 2. Changes are automatically reflected in all connected agent builders 3. No need to redeploy or reconfigure agents 4. Agents immediately have access to updated views and tools Start simple and expand based on evals insights. You can always refine your views and tools as you learn how agents interact with your data. ## Key Concepts ### Views Are the Only Access Level **Important**: AI agents never get raw database access. They can only query through the views you create. This means: * ✅ Complete control over what data agents can see * ✅ No risk of agents accessing unauthorized data * ✅ All queries go through your defined views * ✅ Full audit trail of all data access ### Multiple Tools on One View A single view can have multiple MCP tools, each with different purposes: * Different parameter sets * Different query filters * Different use cases * Different agent interaction patterns This flexibility lets you tailor how different agents or use cases interact with the same underlying data. ## Next Steps Now that you have the basics: * [What is Pylar?](/introduction/what-is-pylar) - Deep dive into Pylar's capabilities * [Why Pylar?](/introduction/why-pylar) - Understand the benefits * Explore advanced features like cross-database joins and complex queries * Build more views and tools for different use cases * Use Evals to optimize your tools based on real usage Our support team is here to help you succeed with Pylar # What is Pylar? Source: https://docs.pylar.ai/introduction/what-is-pylar Learn about Pylar, a secure data access layer designed for AI agents to safely interact with structured data sources ## Overview Pylar is a secure data access layer designed for AI agents, enabling them to interact with structured data sources safely and efficiently. It provides organizations with the tools to create governed views of their data, publish them as MCP tools, and monitor agent performance through comprehensive evaluations. Pylar bridges the gap between your data warehouse and AI agents, providing secure, controlled access without exposing raw database queries or compromising data governance. ## The Problem As AI agents become increasingly powerful, organizations face a critical challenge: **how to provide agents with access to structured data while maintaining security, compliance, and governance.** Traditional approaches often require: * Exposing raw database access to AI agents * Writing custom integration code for each data source * Manually managing permissions and access controls * Building separate pipelines for different agent frameworks * Lack of visibility into what data agents are accessing Giving AI agents direct database access can lead to security vulnerabilities, compliance issues, and uncontrolled data usage. ## The Solution Pylar solves these challenges by providing a **governed data access layer** that sits between your data warehouse and AI agents. Instead of giving agents direct database access, you define secure, scoped views of your data that agents can safely query. ### How It Works 1. **Connect Databases**: Connect to multiple data sources (BigQuery, Snowflake, PostgreSQL, etc.) 2. **Create Projects**: Organize your work in projects that contain all your views and tools 3. **Build Views in SQL IDE**: Use the built-in SQL IDE to select data sources and write queries, including cross-database joins 4. **Create MCP Tools**: Build MCP tools via AI (using natural language) or manually, with multiple tools per view 5. **Test & Publish**: Test your tools, then publish to get a link and header token 6. **Deploy to Agents**: Paste the link and token into any agent builder 7. **Monitor with Evals**: Use comprehensive evals to see how agents interact, errors, query shapes, and raw logs ## Key Features ### Governed SQL Views Create secure, scoped data views using Pylar's SQL IDE. These views are the **only level of access** agents get—they never have raw database access. * **SQL IDE**: Built-in SQL editor where you select data sources and write queries * **Cross-Database Joins**: Join data across multiple databases and warehouses in a single query * **Project Organization**: Organize views within projects for better management * **Complete Isolation**: Agents can only query through your defined views, never raw tables Start with read-only views for your most commonly accessed data. You can always expand access as you gain confidence in your governance policies. Views are the only access level. AI agents never get direct database access, ensuring complete security and governance. ### AI-Powered MCP Tool Creation Create MCP (Model Context Protocol) tools from your SQL views using AI or manual configuration. Build multiple tools on a single view, each governing how agents interact with your data differently. * **AI-Assisted Creation**: Use natural language prompts like "create a tool to fetch error codes, events, and deal information" and Pylar's AI configures the tool * **Manual Configuration**: Fine-tune tools manually for complete control * **Multiple Tools Per View**: Create different tools on the same view for different use cases * **Test Before Deploy**: Test your tools before publishing to ensure they work correctly * **Standard Protocol**: Uses MCP, the emerging standard for AI agent tooling ### Publishing & Deployment Publish your tools and get everything you need to connect to any agent builder. * **Publish with One Click**: Hit publish to generate your deployment package * **Link & Token**: Receive a unique MCP server link and header token for secure access * **Universal Compatibility**: Works with any agent builder that supports MCP (Claude Desktop, Cursor, Windsurf, etc.) * **Automatic Updates**: Adjust queries, view scope, or tools on the platform—changes reflect everywhere automatically ### Evals & Observability Layer Get in-depth insights into how your agents interact with your views. Click "Evals" to see comprehensive analytics that help you optimize your views and tools. * **Interaction Patterns**: See exactly how agents are using your tools * **Success vs. Errors**: Track successful queries and identify failures * **Error Analysis**: Detailed breakdown of errors—what they are, when they occur, and why they failed * **Query Shape**: Understand the types of queries agents are making * **Raw Logs**: Access full query logs for debugging and analysis * **Iterative Improvement**: Use evals insights to adjust view scope and tool configurations With Pylar's observability features, you'll always know what your AI agents are doing with your data. ### Seamless Multi-Database Integration Connect to multiple databases and warehouses simultaneously. Join data across different sources in a single query, giving you flexibility without complexity. **Supported Data Sources:** * BigQuery * Snowflake * PostgreSQL * MySQL * Redshift * AlloyDB * Databricks * And more... You can join tables from BigQuery and Snowflake in the same query, giving you unified access to all your data sources. ## Benefits By implementing Pylar, organizations can: * **Maintain Security**: Control exactly what data agents can access with fine-grained permissions * **Ensure Compliance**: Track all data access and maintain audit trails * **Accelerate Development**: Auto-generate tools instead of writing custom integrations * **Reduce Risk**: Eliminate direct database access for AI agents * **Improve Visibility**: Understand agent behavior and data usage patterns * **Scale Easily**: Add new data sources and tools without complex migrations ## Use Cases Pylar is ideal for: * **AI Agent Development**: Provide agents with safe access to structured data * **Data Analytics Teams**: Enable analysts to build AI-powered data tools * **Enterprise AI Adoption**: Safely scale AI agent usage across your organization * **Compliance-Critical Industries**: Maintain data governance while leveraging AI * **Multi-Tenant Applications**: Isolate data access for different customers or teams ## Next Steps Ready to get started? Learn more about: * [Why Pylar?](/introduction/why-pylar) - Understand the benefits and use cases * [Quick Start](/introduction/quick-start) - Get up and running in minutes # Why Pylar? Source: https://docs.pylar.ai/introduction/why-pylar Discover the benefits and advantages of using Pylar for secure AI agent data access ## Why Choose Pylar? Pylar solves critical challenges in AI agent development by providing a secure, governed data access layer. Here's why organizations choose Pylar over building custom solutions or giving agents direct database access. ## Security & Governance First ### Fine-Grained Access Control Unlike direct database connections, Pylar lets you define exactly what data agents can access at the view, column, and row level. This means you can: * **Restrict Sensitive Data**: Automatically mask or exclude PII, financial data, or other sensitive information * **Row-Level Security**: Control access based on user context, regions, or business rules * **Query Validation**: Prevent unauthorized queries before they reach your database * **Audit Every Access**: Track who accessed what data and when With Pylar, you can start with read-only access to non-sensitive data and gradually expand as you build confidence in your governance policies. ### Compliance Ready Pylar helps you meet regulatory requirements out of the box: * **Complete Audit Trails**: Every query is logged with full context * **Data Lineage**: Understand where data came from and how it's used * **Access Controls**: Enforce policies that meet SOC 2, GDPR, HIPAA, and other standards * **Documentation**: Auto-generated documentation for compliance reviews Direct database access makes compliance nearly impossible. Pylar provides the governance layer you need. ## Developer Experience ### AI-Powered Tool Creation Instead of writing custom integrations, use natural language to create MCP tools: * **Natural Language Prompts**: Write "create a tool to fetch error codes, events, and deal information" and Pylar's AI configures it * **Manual Control Available**: Fine-tune tools manually when needed * **Multiple Tools Per View**: Create different tools on the same view for flexibility * **Test Before Deploy**: Verify tools work correctly before publishing * **Standard Protocol**: Uses MCP, the emerging standard for AI tooling ### One View, Multiple Tools Create multiple MCP tools on a single view, each governing how agents interact with your data differently. All tools work with any MCP-compatible agent: * Claude Desktop * Cursor * Windsurf * Custom agent frameworks * Any MCP-compatible tool Write your data access logic once, create multiple tools, use everywhere. ### Rapid Iteration Without Redeployment * **Adjust Anytime**: Update queries, view scope, or tools on the platform * **Automatic Propagation**: Changes reflect everywhere automatically—no redeployment needed * **Test Before Publish**: Test MCP tools before deploying to ensure they work * **Iterative Improvement**: Use Evals insights to refine views and tools continuously ## Operational Excellence ### In-Depth Evals & Observability Click "Evals" to get comprehensive insights into how agents interact with your views: * **Interaction Patterns**: See exactly how agents use your tools * **Success vs. Errors**: Track successful queries and identify failures * **Error Analysis**: Detailed breakdown—what errors occurred, when, and why * **Query Shape**: Understand the types of queries agents are making * **Raw Logs**: Access full query logs for debugging * **Iterative Optimization**: Use insights to adjust view scope and tool configurations ### Scalability Without Headaches Pylar scales with you: * **Multi-Database Support**: Connect to BigQuery, Snowflake, PostgreSQL, and more * **Cross-Database Joins**: Join data across multiple databases in a single query * **Project Organization**: Organize views and tools in projects for better management * **SQL IDE**: Built-in SQL editor for easy query development * **Views Are the Only Access**: Agents never get raw database access—complete security Start small with one database and one view. Scale to hundreds of views across multiple data sources as you grow. All within projects that keep everything organized. ## Cost Efficiency ### Reduce Development Time Building custom agent integrations typically takes weeks or months. With Pylar: * **Days Instead of Months**: Get your first tools running in hours * **No Maintenance Burden**: Pylar handles protocol updates and compatibility * **Focus on Value**: Spend time on your business logic, not infrastructure ### Lower Infrastructure Costs * **Connection Efficiency**: Shared connections reduce database load * **Query Optimization**: Built-in query analysis and optimization * **Caching Layer**: Reduce redundant queries and costs * **Resource Management**: Prevent runaway queries that spike costs ## Real-World Benefits ### For Data Teams * **Self-Service with SQL IDE**: Use the built-in SQL IDE to create views without waiting for engineering * **Cross-Database Analysis**: Join data across warehouses without complex pipelines * **Governance Without Friction**: Maintain control—views are the only access level * **Evals Insights**: Understand exactly how agents interact with your data * **Iterative Improvement**: Use evals to continuously refine views and tools ### For Engineering Teams * **No Custom Integration Code**: AI-powered tool creation eliminates boilerplate * **Standardization**: One platform for all agent data access needs * **Faster Shipping**: Get agents to market faster with instant tool creation * **Easier Debugging**: Evals provide raw logs, query shapes, and error analysis * **No Redeployment**: Changes reflect automatically everywhere ### For Organizations * **Complete Isolation**: Views are the only access level—agents never get raw database access * **Risk Reduction**: Eliminate direct database access for AI agents * **Faster AI Adoption**: Remove blockers with AI-powered tool creation * **Compliance Confidence**: Meet regulatory requirements with built-in controls * **Cost Control**: Monitor and manage data access costs through Evals * **Iterative Optimization**: Continuously improve based on real agent behavior ## Comparison: Pylar vs. Alternatives ### Pylar vs. Custom Integration | Feature | Pylar | Custom Integration | | ------------------ | --------- | ------------------ | | Time to First Tool | Hours | Weeks/Months | | Maintenance | Automatic | Ongoing | | Governance | Built-in | Manual | | Observability | Included | Custom Build | | Multi-Database | Supported | Per-DB Code | | Protocol Updates | Automatic | Manual | ### Pylar vs. Direct Database Access | Feature | Pylar | Direct Access | | -------------- | -------------------- | ------------------ | | Security | Fine-grained control | All or nothing | | Compliance | Audit-ready | Difficult to audit | | Cost Control | Built-in monitoring | No visibility | | Error Handling | Managed | Manual | | Scaling | Automatic | Manual | ## When Pylar Makes Sense Pylar is ideal if you: * ✅ Have AI agents that need structured data access * ✅ Need to maintain data governance and compliance * ✅ Want to avoid writing custom integration code * ✅ Need visibility into agent data usage * ✅ Work with multiple databases or data sources * ✅ Want to scale AI agent usage safely * ✅ Need to support multiple agent frameworks ## Getting Started Ready to experience these benefits? Check out our [Quick Start guide](/introduction/quick-start) to get up and running in minutes. Get your first Pylar tools running in minutes # Creating Tools with AI Source: https://docs.pylar.ai/learn/building-mcp-tools/creating-tools-with-ai Learn how to use Pylar's AI to create MCP tools from natural language prompts ## Overview Pylar's AI makes creating MCP tools effortless. Simply describe what you want in natural language, and the AI generates a complete, ready-to-use tool for you. This guide walks you through creating your first AI-generated tool. ## Prerequisites Before creating a tool, ensure you have: * ✅ A view created in your project * ✅ The view selected in the right sidebar * ✅ Access to Pylar AI (available in the right sidebar) The Pylar AI assistant is always available in the right sidebar. It understands your data structure and can generate tools tailored to your views. ## Step 1: Select Your View Before asking the AI to create a tool, you need to select the view you want to build the tool on. 1. Navigate to your project 2. Find the view you want to use 3. **Select the view in the right sidebar** - Make sure it's highlighted/selected The AI needs to know which view you're working with. Always select your view before asking the AI to create a tool. ## Step 2: Ask the AI to Create a Tool Once your view is selected, use the Pylar AI to create your tool. ### Using Natural Language In the right sidebar, you'll see the Pylar AI. Simply describe what you want the tool to do in plain English. ### Example Request Let's create an MCP tool that returns engagement scores for a given event type: **Ask the AI**: *"Create an MCP tool to compute the engagement score for a given event type"* AI-powered MCP tool creation interface in Pylar showing natural language input and generated tool ### What the AI Does When you submit your request, the AI: 1. **Analyzes Your View**: Understands the structure of your selected view 2. **Interprets Your Request**: Understands what you want the tool to do 3. **Generates SQL Query**: Creates a SQL query tailored to your use case 4. **Defines Parameters**: Identifies what inputs the tool needs 5. **Creates Tool Structure**: Builds the complete MCP tool configuration The AI generates a complete, production-ready tool. You can use it as-is or refine it further. ## Step 3: Review the Generated Tool Once the AI finishes generating, your new tool appears in the **"MCP Tools"** section of the right sidebar. ### What You'll See The AI-generated tool includes: * **Function Name**: A descriptive name for the tool * **Description**: What the tool does (used by agents) * **SQL Query**: The query that retrieves data * **Parameters**: Inputs the tool accepts * **Tool Call Arguments**: Test values for verification ### Example Generated Tool For our engagement score example, the AI might generate: * **Function Name**: `fetch_engagement_scores_by_event_type` * **Description**: "Fetches engagement scores and related data filtered by event type" * **SQL Query**: ```sql theme={null} SELECT engagement_score FROM table0 WHERE event_type LIKE '%{event_type}%' ORDER BY engagement_score DESC ``` * **Parameter**: `event_type` (string, required) The AI uses placeholders like `{event_type}` in queries. When an agent calls the tool, it provides the actual value, which replaces the placeholder. ## Understanding the Generated Query The AI-generated SQL query is tailored to your request: ### Query Structure ```sql theme={null} SELECT engagement_score FROM table0 WHERE event_type LIKE '%{event_type}%' ORDER BY engagement_score DESC ``` **What This Does**: * Selects `engagement_score` from your view (table0) * Filters by `event_type` using a LIKE pattern match * Uses `{event_type}` as a parameter placeholder * Orders results by engagement score (highest first) ### Parameter Injection When an agent calls this tool: * Agent provides: `event_type = "login"` * Query becomes: `WHERE event_type LIKE '%login%'` * Returns: All engagement scores for login events The `LIKE '%{event_type}%'` pattern allows partial matching. This means searching for "log" will match "login", "logout", etc. ## Refining AI-Generated Tools The AI creates a solid foundation, but you can refine it: ### Common Refinements 1. **Adjust Query Logic**: Modify the SQL to better match your needs 2. **Add Filters**: Include additional WHERE conditions 3. **Change Parameters**: Add or remove parameters 4. **Update Description**: Make it clearer for agents 5. **Rename Function**: Use a more descriptive name Start with the AI-generated tool, then refine it based on your specific requirements. The AI gives you a great starting point. ## Best Practices for AI Prompts ### Write Clear Requests **Good Examples**: * *"Create an MCP tool to get customer revenue for a specific date range"* * *"Build a tool that returns top products by sales in a given category"* * *"Make a tool to find customers with high engagement scores"* **Avoid Vague Requests**: * ❌ "Make a tool" (too vague) * ❌ "Get data" (not specific enough) * ❌ "Something for customers" (unclear purpose) ### Include Key Details Mention: * **What data** you want (engagement scores, revenue, etc.) * **How to filter** (by event type, date range, customer ID, etc.) * **How to sort** (highest first, most recent, etc.) ### Examples of Effective Prompts **Example 1: Filtering by Date** *"Create an MCP tool to get sales data for a specific date range, ordered by amount descending"* **Example 2: Multiple Filters** *"Build a tool that returns customer information filtered by region and account type"* **Example 3: Aggregations** *"Create a tool to calculate average order value for a given product category"* ## Next Steps Now that your tool is created: * [Understanding Tool Structure](/learn/building-mcp-tools/understanding-tool-structure) - Learn about all tool components * [Editing MCP Tools](/learn/building-mcp-tools/editing-mcp-tools) - Refine and customize your tools * [Testing Your Tools](/learn/building-mcp-tools/testing-your-tools) - Verify your tool works correctly * [Publishing Tools](/learn/publishing-tools/overview) - Make your tools available to agents Verify your AI-generated tool works correctly # Editing MCP Tools Source: https://docs.pylar.ai/learn/building-mcp-tools/editing-mcp-tools Learn how to view, edit, and refine MCP tools in Pylar ## Overview After creating an MCP tool (either with AI or manually), you'll often want to refine it. This guide shows you how to access, view, and edit your tools. ## Accessing Your Tools To view and edit a tool: 1. Navigate to your project in Pylar 2. Look for the **"MCP Tools"** section in the right sidebar 3. **Click on the tool** you want to view or edit The tool details will open, showing all its components. ## Tool Components Overview When you open a tool, you'll see: ### Function Name * Located at the top * Can be renamed by clicking and editing * Should be descriptive and unique ### Description * Summary of what the tool does * Visible to AI agents * Can be edited inline ### SQL Query * The query that retrieves data * Can be edited in the query editor * Supports parameter placeholders ### Parameters * Input definitions for the tool * Can add, remove, or modify parameters * Define types and requirements ### Tool Call Arguments * Test values (right side) * Used for testing * Can be modified ## Editing Function Name To rename a tool: 1. Click on the function name at the top 2. Edit the name directly 3. Save your changes Choose names that clearly indicate the tool's purpose. Agents use function names to identify and call tools. ## Editing Description The description helps agents understand when to use your tool. **To edit**: 1. Click on the description field 2. Modify the text 3. Save changes **Best Practices**: * Be specific about what data is returned * Mention any important behaviors (e.g., "supports partial matching") * Keep it concise but informative **Example**: * ❌ "Gets data" (too vague) * ✅ "Fetches engagement scores and related data filtered by event type" (clear and specific) ## Editing SQL Query The SQL query is where you define how the tool retrieves data. ### Accessing the Query Editor 1. Find the **SQL Query** section in the tool view 2. Click to edit (or use the edit button) 3. Modify the query as needed 4. Save your changes ### Common Edits **Adding Filters**: ```sql theme={null} -- Original SELECT engagement_score FROM table0 WHERE event_type = '{event_type}' -- Enhanced SELECT engagement_score FROM table0 WHERE event_type = '{event_type}' AND date >= '{start_date}' AND engagement_score > {min_score} ``` **Changing Sort Order**: ```sql theme={null} -- Ascending instead of descending ORDER BY engagement_score ASC ``` **Adding Columns**: ```sql theme={null} -- Original SELECT engagement_score FROM table0 -- Enhanced SELECT engagement_score, event_id, timestamp, user_id FROM table0 ``` **Improving Performance**: ```sql theme={null} -- Add LIMIT for large result sets SELECT engagement_score FROM table0 WHERE event_type = '{event_type}' ORDER BY engagement_score DESC LIMIT 100 ``` When editing queries, ensure parameter placeholders match parameter names exactly. Mismatched names will cause errors. ## Modifying Parameters Parameters define what inputs your tool accepts. ### Adding Parameters 1. Go to the **Parameters** section 2. Click **Add Parameter** or similar 3. Define: * Parameter name * Type (string, number, etc.) * Whether it's required * Description 4. Update your SQL query to use the new parameter **Example**: Adding a date range parameter ```sql theme={null} -- Query with new parameter SELECT * FROM table0 WHERE event_type = '{event_type}' AND date >= '{start_date}' AND date <= '{end_date}' ``` ### Removing Parameters 1. Find the parameter in the Parameters section 2. Remove it 3. Update your SQL query to remove the placeholder If you remove a parameter, make sure to also remove its placeholder from the SQL query. Otherwise, the query will fail when executed. ### Modifying Parameter Properties You can change: * **Type**: string → number, etc. * **Required/Optional**: Make parameters required or optional * **Description**: Update what the parameter represents ## Updating Tool Call Arguments Tool call arguments are test values used for verification. **To update**: 1. Find the **Tool Call Arguments** section (right side) 2. Modify the test values 3. Use these values when testing the tool **Example**: ```json theme={null} { "event_type": "login" // Change to "purchase" to test different scenarios } ``` Use varied test arguments to verify your tool handles different inputs correctly. Test edge cases like empty strings, special characters, etc. ## Common Editing Scenarios ### Scenario 1: Refining an AI-Generated Tool After AI creates a tool, you might want to: 1. **Add more filters**: Include additional WHERE conditions 2. **Change sort order**: Modify ORDER BY clause 3. **Add columns**: Return more data 4. **Improve description**: Make it clearer for agents ### Scenario 2: Fixing a Tool That's Not Working If a tool fails testing: 1. **Check parameter names**: Ensure placeholders match parameter names 2. **Verify SQL syntax**: Test query manually in SQL IDE 3. **Check data types**: Ensure parameter types match query expectations 4. **Review filters**: Make sure WHERE conditions are valid ### Scenario 3: Optimizing Performance For slow queries: 1. **Add LIMIT**: Restrict result set size 2. **Refine filters**: Make WHERE conditions more selective 3. **Remove unnecessary columns**: Select only needed data 4. **Add indexes**: Ensure source views have proper indexes ## Viewing JSON Structure To see the complete tool configuration: 1. Click **"JSON view"** button 2. View the structured JSON representation 3. Useful for: * Understanding complete configuration * Debugging issues * Copying tool structure **Example JSON View**: ```json theme={null} { "function_name": "fetch_engagement_scores_by_event_type", "description": "Fetches engagement scores and related data filtered by event type", "query": "SELECT engagement_score FROM table0 WHERE event_type LIKE '%{event_type}%' \nORDER BY engagement_score DESC", "parameters": { "type": "object", "required": ["event_type"], "properties": { "event_type": { "type": "string", "description": "Event type to filter by (supports partial matching)" } } }, "tool_call": { "name": "fetch_engagement_scores_by_event_type", "args": { "event_type": "login" } } } ``` ## Best Practices ### Before Editing * ✅ Test the current tool to understand its behavior * ✅ Review the SQL query in the SQL IDE * ✅ Check parameter usage in the query ### While Editing * ✅ Make incremental changes * ✅ Test after each significant change * ✅ Keep parameter names consistent * ✅ Update descriptions when behavior changes ### After Editing * ✅ Always test the tool after changes * ✅ Verify parameters work correctly * ✅ Check that results are as expected * ✅ Update descriptions if needed ## Next Steps After editing your tool: * [Testing Your Tools](/learn/building-mcp-tools/testing-your-tools) - Verify your changes work correctly * [Publishing Tools](/learn/publishing-tools/overview) - Make your tools available to agents Verify your edited tool works correctly # Overview Source: https://docs.pylar.ai/learn/building-mcp-tools/overview Introduction to MCP tools in Pylar - understand how tools enable AI agents to interact with your data views ## What Are MCP Tools? MCP (Model Context Protocol) tools are the interface between your data views and AI agents. They define how agents can query and interact with your data, translating natural language requests into structured SQL queries. ### The Role of MCP Tools MCP tools serve as: * **Agent Interface**: The way AI agents access your data views * **Query Wrappers**: SQL queries tailored to specific use cases * **Parameter Handlers**: Accept inputs from agents and inject them into queries * **Security Layer**: Govern how agents interact with your data Think of MCP tools as functions that AI agents can call. Each tool has a specific purpose and knows how to query your data to fulfill that purpose. ## How MCP Tools Work ### The Workflow 1. **Create a View**: Define what data agents can access 2. **Create MCP Tools**: Build tools on top of your view 3. **Test Tools**: Verify tools work correctly 4. **Publish Tools**: Make them available to agent builders 5. **Agents Use Tools**: AI agents call tools to query your data ### Multiple Tools Per View A single view can have multiple MCP tools, each serving different purposes: * **Different Parameters**: Each tool can accept different inputs * **Different Queries**: Tools can query the same view differently * **Different Use Cases**: Tools can be optimized for specific scenarios ```mermaid theme={null} graph TB VIEW[Customer 360 View
SQL View with customer data] TOOL1[get_customer_by_id
Fetch customer details] TOOL2[get_high_value_customers
Filter by revenue] TOOL3[get_customer_engagement
Calculate engagement score] TOOL4[search_customers
Search by name/email] VIEW --> TOOL1 VIEW --> TOOL2 VIEW --> TOOL3 VIEW --> TOOL4 AGENT[AI Agent
Uses all tools] TOOL1 --> AGENT TOOL2 --> AGENT TOOL3 --> AGENT TOOL4 --> AGENT style VIEW fill:#FF4017,stroke:#CC3300,color:#fff style TOOL1 fill:#e9ecef,stroke:#868e96 style TOOL2 fill:#e9ecef,stroke:#868e96 style TOOL3 fill:#e9ecef,stroke:#868e96 style TOOL4 fill:#e9ecef,stroke:#868e96 ``` Create multiple tools on the same view to provide agents with different ways to interact with your data. For example, one tool for filtering by date, another for filtering by customer segment. ## Key Concepts ### Function Name Each tool has a unique function name that agents use to invoke it. Names should be: * Descriptive and clear * Follow naming conventions * Indicate the tool's purpose ### Description The description tells agents what the tool does. It should: * Clearly explain the tool's purpose * Be concise but informative * Help agents decide when to use the tool ### SQL Query The SQL query defines how the tool queries your view: * Can include parameters from the agent * Uses placeholders like `{parameter_name}` * Can be edited and refined * Executes against your data view ### Parameters Parameters are inputs the tool accepts: * Define what data agents must provide * Can be required or optional * Have types (string, number, etc.) * Include descriptions for clarity ### Tool Call Arguments Test values used to verify the tool works: * Sample inputs for testing * Can be modified during testing * Help validate tool behavior ## Creating MCP Tools MCP Tools section in Pylar showing available tools and create tool option ### Method 1: AI-Assisted Creation (Recommended) Use Pylar's AI to create tools from natural language: 1. Select your view in the sidebar 2. Ask the AI to create a tool 3. Review the generated tool 4. Test and refine as needed **Example**: *"Create an MCP tool to compute the engagement score for a given event type"* ### Method 2: Manual Creation Create tools manually for complete control: 1. Define the function name 2. Write the description 3. Create the SQL query 4. Configure parameters 5. Set test arguments ## Testing Your Tools Before publishing, always test your tools: 1. Click "Test Run" on the tool 2. Review the query execution 3. Check the results 4. Verify parameters work correctly 5. Refine if needed Never skip testing. A tool that works in testing will work in production, but a tool that fails testing will cause agent errors. ## Publishing Tools Once tested, publish your tools: 1. Click "Publish" in the sidebar 2. Generate an authorization token 3. Copy the MCP HTTP Stream URL and Bearer Token 4. Connect to your agent builder ## Next Steps Ready to create your first tool? * [Creating Tools with AI](/learn/building-mcp-tools/creating-tools-with-ai) - Use AI to create tools from natural language * [Creating Tools Manually](/learn/building-mcp-tools/creating-tools-manually) - Build tools with complete control * [Understanding Tool Structure](/learn/building-mcp-tools/understanding-tool-structure) - Learn about tool components * [Testing Your Tools](/learn/building-mcp-tools/testing-your-tools) - Verify tools work correctly Use AI to create an MCP tool in seconds # Testing Your Tools Source: https://docs.pylar.ai/learn/building-mcp-tools/testing-your-tools Learn how to test MCP tools before publishing to ensure they work correctly with your data ## Overview Testing your MCP tools is a critical step before publishing. It ensures your tools work correctly, handle parameters properly, and return expected results. This guide walks you through the testing process. ## Why Test Your Tools? Testing helps you: * ✅ **Verify Functionality**: Ensure queries execute correctly * ✅ **Validate Parameters**: Confirm parameters work as expected * ✅ **Check Results**: Verify returned data is correct * ✅ **Catch Errors Early**: Find issues before agents use the tools * ✅ **Optimize Performance**: Identify slow queries Never skip testing. A tool that fails in testing will fail when agents use it, causing errors and poor user experiences. ## Preparing to Test Before testing, ensure: 1. ✅ Your tool is created and configured 2. ✅ Tool call arguments are set (test values) 3. ✅ Your view has data (empty views return no results) 4. ✅ SQL query syntax is correct ## Step-by-Step Testing ### Step 1: Access Test Functionality 1. Navigate to your project 2. Open the tool you want to test (click on it in the MCP Tools section) 3. Locate the **"Test Run"** button at the top of the tool view 4. Click **"Test Run"** MCP tool testing interface showing test run button and test parameters ### Step 2: Test Execution After clicking "Test Run": 1. A popup window appears showing: * The query being executed * Parameter values being used * Execution status 2. Wait for the query to complete (you'll see a loader) 3. Results appear in the **"Test Results"** section The test uses the Tool Call Arguments you've configured. These are the sample values that will be injected into your query. ### Step 3: Review Results The Test Results section shows: MCP tool test results showing query execution, returned data, and success status * **Query Executed**: The actual SQL query with parameter values injected * **Result Data**: The data returned by the query * **Row Count**: Number of rows returned * **Execution Time**: How long the query took * **Status**: Success or error message ### Example Test Results For our engagement score tool with `event_type = "login"`: **Query Executed**: ```sql theme={null} SELECT engagement_score FROM table0 WHERE event_type LIKE '%login%' ORDER BY engagement_score DESC ``` **Results**: * Engagement scores for all events containing "login" * Ordered from highest to lowest * Row count and execution time displayed If the test succeeds, your tool is working correctly and ready for use. If it fails, review the error message and fix the issue. ## Understanding Test Results ### Successful Test A successful test shows: * ✅ Query executed without errors * ✅ Results returned (even if empty) * ✅ Correct parameter injection * ✅ Expected data structure ### Failed Test If a test fails, you'll see: * ❌ Error message explaining what went wrong * ❌ Query that failed (helpful for debugging) * ❌ Parameter values used ### Common Test Failures **1. Parameter Mismatch** * **Error**: Parameter placeholder doesn't match parameter name * **Fix**: Ensure `{parameter_name}` in SQL matches parameter definition exactly **2. SQL Syntax Error** * **Error**: Invalid SQL syntax * **Fix**: Test query manually in SQL IDE first **3. Data Type Mismatch** * **Error**: Parameter type doesn't match query expectations * **Fix**: Ensure parameter types are correct (string, number, etc.) **4. Empty Results** * **Not an error**: Query works but returns no data * **Check**: Verify your view has data matching the test criteria ## Testing Different Scenarios ### Test with Different Values Use the Tool Call Arguments to test various scenarios: **Scenario 1: Exact Match** ```json theme={null} { "event_type": "login" } ``` **Scenario 2: Partial Match** ```json theme={null} { "event_type": "log" } ``` **Scenario 3: Edge Cases** ```json theme={null} { "event_type": "" // Empty string } ``` ### Testing Multiple Parameters If your tool has multiple parameters: ```json theme={null} { "event_type": "purchase", "start_date": "2024-01-01", "end_date": "2024-12-31" } ``` Test various combinations to ensure all parameters work correctly. ## Best Practices ### Test Before Publishing * ✅ Always test tools before publishing * ✅ Test with realistic data values * ✅ Test edge cases (empty strings, nulls, etc.) * ✅ Verify results match expectations ### Test Incrementally When creating or editing tools: 1. **Test Basic Query**: Verify SQL works in SQL IDE 2. **Test with Parameters**: Ensure parameter injection works 3. **Test Edge Cases**: Try unusual inputs 4. **Test Performance**: Check query execution time ### Use Realistic Test Data * ✅ Use values that represent real agent usage * ✅ Test with data that exists in your view * ✅ Try different parameter combinations * ✅ Test with empty/null values if appropriate ## Troubleshooting Test Failures ### Issue: "Parameter not found" **Cause**: Parameter placeholder in SQL doesn't match parameter name **Solution**: ```sql theme={null} -- Wrong WHERE event_type = '{event_type_param}' -- Correct (matches parameter name) WHERE event_type = '{event_type}' ``` ### Issue: "Query syntax error" **Cause**: Invalid SQL syntax **Solution**: 1. Test the query manually in SQL IDE 2. Replace placeholders with actual values 3. Fix any syntax errors 4. Update tool query ### Issue: "No results returned" **Cause**: Query executes but no data matches criteria **Solution**: 1. Verify your view has data 2. Check if test values match data in view 3. Try broader test criteria 4. Review WHERE conditions ### Issue: "Query timeout" **Cause**: Query takes too long to execute **Solution**: 1. Add LIMIT to restrict results 2. Refine WHERE conditions 3. Optimize query performance 4. Consider data volume ## What to Verify After a successful test, verify: * ✅ **Correct Data**: Results match what you expect * ✅ **Proper Filtering**: WHERE conditions work correctly * ✅ **Sorting**: ORDER BY works as intended * ✅ **Parameter Injection**: Values are inserted correctly * ✅ **Performance**: Query executes in reasonable time * ✅ **Data Structure**: Columns and types are correct ## Next Steps Once your tool passes testing: * [Publishing Tools](/learn/publishing-tools/overview) - Make your tested tools available to agents * [Editing MCP Tools](/learn/building-mcp-tools/editing-mcp-tools) - Refine tools based on test results Make your tested tool available to AI agents # Understanding Tool Structure Source: https://docs.pylar.ai/learn/building-mcp-tools/understanding-tool-structure Learn about the components of an MCP tool: function name, description, SQL query, parameters, and more ## Overview Every MCP tool in Pylar has a structured configuration that defines how it works. Understanding these components helps you create better tools and troubleshoot issues. ## Accessing Tool Details To view a tool's structure: 1. Navigate to your project 2. Find the tool in the **"MCP Tools"** section of the right sidebar 3. **Click on the tool** to open its details You'll see all the tool's components organized in a clear interface. MCP tool details view showing function name, description, SQL query, and parameters ## Tool Components ### 1. Function Name The function name is how agents identify and call your tool. **Location**: At the top of the tool view **Characteristics**: * Must be unique within your project * Should be descriptive and clear * Follows naming conventions (snake\_case is common) * Can be renamed at any time **Example**: `fetch_engagement_scores_by_event_type` Choose function names that clearly indicate what the tool does. Agents will use this name to invoke the tool. ### 2. Description The description tells AI agents what your tool does and when to use it. **Location**: Below the function name **Characteristics**: * Written in natural language * Should be clear and concise * Helps agents decide when to use the tool * Visible to agents when they browse available tools **Example**: *"Fetches engagement scores and related data filtered by event type"* The description is crucial for agents. Make it specific enough that agents understand exactly what the tool does and when to use it. ### 3. SQL Query The SQL query defines how the tool retrieves data from your view. **Location**: In the SQL Query section **Characteristics**: * Standard SQL syntax * Can include parameter placeholders like `{parameter_name}` * Executes against your data view * Can be edited and refined **Example**: ```sql theme={null} SELECT engagement_score FROM table0 WHERE event_type LIKE '%{event_type}%' ORDER BY engagement_score DESC ``` ### Parameter Placeholders Use `{parameter_name}` in your SQL query where you want agent-provided values injected: ```sql theme={null} -- Single parameter WHERE event_type = '{event_type}' -- Multiple parameters WHERE date >= '{start_date}' AND date <= '{end_date}' -- In LIKE patterns WHERE name LIKE '%{search_term}%' ``` Parameter names in SQL must match parameter names exactly. Case-sensitive and spelling must be identical. ### 4. Parameters Parameters define what inputs your tool accepts from agents. **Location**: In the Parameters section **Structure**: * **Type**: The data type (string, number, boolean, etc.) * **Required/Optional**: Whether the parameter must be provided * **Description**: What the parameter represents * **Properties**: Additional constraints or validations **Example Parameter Configuration**: ```json theme={null} { "event_type": { "type": "string", "description": "Event type to filter by (supports partial matching)", "required": true } } ``` ### Parameter Types Common parameter types: * **string**: Text values * **number**: Numeric values (integers or decimals) * **boolean**: True/false values * **array**: Lists of values * **object**: Complex nested structures ### 5. Tool Call Arguments Tool call arguments are test values used to verify your tool works. **Location**: In the Tool Call Arguments section (right side) **Purpose**: * Sample inputs for testing * Can be modified during testing * Help validate tool behavior * Don't affect production tool calls **Example**: ```json theme={null} { "event_type": "login" } ``` Use realistic test values that represent how agents will actually use your tool. This helps catch issues early. ## JSON Structure You can view the complete tool structure as JSON by clicking **"JSON view"**. MCP tool JSON structure view showing the complete tool configuration ### Complete JSON Example ```json theme={null} { "function_name": "fetch_engagement_scores_by_event_type", "description": "Fetches engagement scores and related data filtered by event type", "query": "SELECT engagement_score FROM table0 WHERE event_type LIKE '%{event_type}%' \nORDER BY engagement_score DESC", "parameters": { "type": "object", "required": [ "event_type" ], "properties": { "event_type": { "type": "string", "description": "Event type to filter by (supports partial matching)" } } }, "tool_call": { "name": "fetch_engagement_scores_by_event_type", "args": { "event_type": "login" } } } ``` ### JSON Structure Breakdown * **function\_name**: Tool identifier * **description**: What the tool does * **query**: SQL query with parameter placeholders * **parameters**: Parameter definitions (type, required, properties) * **tool\_call**: Test arguments for validation The JSON view is useful for understanding the complete tool structure and for debugging. It shows exactly how the tool is configured. ## How Components Work Together ### The Flow 1. **Agent Calls Tool**: Uses the function name 2. **Agent Provides Parameters**: Sends values for required/optional parameters 3. **Query Execution**: Parameters replace placeholders in SQL 4. **Results Returned**: Query results sent back to agent ### Example Flow **Agent Request**: ```json theme={null} { "function": "fetch_engagement_scores_by_event_type", "args": { "event_type": "purchase" } } ``` **Query Transformation**: ```sql theme={null} -- Original query with placeholder SELECT engagement_score FROM table0 WHERE event_type LIKE '%{event_type}%' -- After parameter injection SELECT engagement_score FROM table0 WHERE event_type LIKE '%purchase%' ``` **Result**: Returns all engagement scores for events containing "purchase" ## Best Practices ### Function Names * ✅ Use descriptive names: `get_customer_revenue_by_date_range` * ✅ Follow naming conventions: snake\_case * ✅ Be specific: `fetch_engagement_scores_by_event_type` not `get_data` * ❌ Avoid abbreviations unless widely understood ### Descriptions * ✅ Be clear and specific * ✅ Mention what data is returned * ✅ Note any important behaviors (like partial matching) * ❌ Avoid vague descriptions like "gets data" ### SQL Queries * ✅ Use parameter placeholders for dynamic values * ✅ Test queries manually before creating tools * ✅ Include ORDER BY for predictable results * ✅ Consider performance (use LIMIT when appropriate) ### Parameters * ✅ Make parameters required when they're essential * ✅ Provide clear descriptions * ✅ Use appropriate types (string, number, etc.) * ✅ Consider adding validation constraints ## Common Patterns ### Pattern 1: Single Filter ```sql theme={null} SELECT * FROM view_name WHERE column = '{filter_value}' ``` ### Pattern 2: Date Range ```sql theme={null} SELECT * FROM view_name WHERE date >= '{start_date}' AND date <= '{end_date}' ORDER BY date DESC ``` ### Pattern 3: Search with LIKE ```sql theme={null} SELECT * FROM view_name WHERE name LIKE '%{search_term}%' ORDER BY relevance DESC LIMIT 100 ``` ### Pattern 4: Multiple Filters ```sql theme={null} SELECT * FROM view_name WHERE category = '{category}' AND status = '{status}' AND date >= '{start_date}' ORDER BY date DESC ``` ## Next Steps Now that you understand tool structure: * [Editing MCP Tools](/learn/building-mcp-tools/editing-mcp-tools) - Learn how to modify tools * [Testing Your Tools](/learn/building-mcp-tools/testing-your-tools) - Verify tools work correctly * [Publishing Tools](/learn/publishing-tools/overview) - Make tools available to agents Learn how to refine and customize your tools # Claude Desktop Source: https://docs.pylar.ai/learn/connecting-agent-builders/claude-desktop Connect Pylar MCP tools to Claude Desktop for AI-powered data access ## Overview Claude Desktop is Anthropic's desktop AI assistant that supports MCP (Model Context Protocol) tools. Connect your Pylar tools to Claude Desktop to give Claude access to your data through governed views. ## Prerequisites * ✅ Claude Desktop app installed on your computer * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Generate your token if needed 4. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token Keep your Bearer Token secure. It provides access to your published tools. ## Step 2: Open Claude Desktop Settings 1. Open the **Claude Desktop** app 2. Go to **Settings** → **Developer** 3. Click **"Edit Config"** This will open the `claude_desktop_config.json` file on your system. ## Step 3: Add Pylar MCP Server Configuration Add the following configuration to the `claude_desktop_config.json` file: ```json theme={null} { "mcpServers": { "view-mcp-node": { "url": "https://mcp.publish.pylar.ai/mcp", "headers": { "Authorization": "Bearer xxxxx" } } } } ``` **Important**: * Replace `xxxxx` with your actual Bearer Token from Pylar * The name `"view-mcp-node"` is a local alias—you can rename it to anything you prefer * Save the file after making changes If the "headers" key is unsupported in your Claude Desktop build, you may need to omit it and use a proxy or environment variable instead. Check your Claude Desktop version for MCP support. ## Step 4: Restart Claude Desktop 1. Save the `claude_desktop_config.json` file 2. Restart Claude Desktop completely 3. Claude Desktop will connect to your Pylar MCP server on startup ## Step 5: Test the Connection 1. Open a new conversation in Claude Desktop 2. Ask Claude a question that requires using your MCP tool **Example**: *"Use the engagement score tool to get scores for login events"* Claude will: 1. Recognize it needs to use your Pylar MCP tool 2. Call the tool with appropriate parameters 3. Execute the query against your view 4. Return the results and use them to answer your question If Claude can successfully use your tools to answer questions, the connection is working correctly! ## Using Your Tools Once connected, you can ask Claude to use your Pylar tools in natural language: * *"Get customer revenue data for the last quarter"* * *"Show me engagement scores for purchase events"* * *"What's the average order value for customers in North America?"* Claude will automatically: * Identify which tool to use * Call the tool with the right parameters * Return formatted results * Use the data to provide comprehensive answers ## Troubleshooting ### Issue: Claude can't see tools **Solutions**: * Verify Bearer Token is correct (no extra spaces) * Ensure token format: `Bearer YOUR_TOKEN` (replace YOUR\_TOKEN with actual token) * Check that tools are published in Pylar * Restart Claude Desktop completely * Verify the JSON syntax in the config file is valid ### Issue: "Connection failed" error **Solutions**: * Verify MCP HTTP Stream URL is correct: `https://mcp.publish.pylar.ai/mcp` * Check network connectivity * Ensure Bearer Token is valid and not expired * Regenerate token in Pylar if needed * Check Claude Desktop version supports MCP headers ### Issue: Tools return errors **Solutions**: * Check Evals in Pylar to see detailed error information * Verify view queries are correct * Test tools in Pylar before using in Claude * Review tool parameters and ensure they're being passed correctly ### Issue: Headers not supported If your Claude Desktop build doesn't support headers in the config: **Alternative Solutions**: * Use a proxy server to add authentication headers * Set authentication via environment variables (if supported) * Check for Claude Desktop updates that add header support ## Benefits By connecting Claude Desktop to Pylar: * ✅ **Secure Access**: Claude only accesses data through your governed views * ✅ **Natural Language**: Ask Claude questions in plain English * ✅ **Centralized Control**: Update views in Pylar, Claude gets updates automatically * ✅ **Full Visibility**: Monitor Claude's usage through Pylar Evals * ✅ **No Code**: No need to write integration code * ✅ **Real-time Updates**: Changes to views and tools reflect immediately ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Learn how to publish your tools * [Evals](/learn/evals/overview) - Monitor how Claude uses your tools * [Other Agent Builders](/learn/connecting-agent-builders/overview) - Connect to other platforms See how Claude interacts with your tools through Evals # Cursor Source: https://docs.pylar.ai/learn/connecting-agent-builders/cursor Connect Pylar MCP tools to Cursor for AI-powered coding assistance with data access ## Overview Cursor is an AI-powered code editor that supports MCP tools. Connect your Pylar tools to Cursor to give the AI assistant access to your data through governed views while coding. ## Prerequisites * ✅ Cursor editor installed * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Generate your token if needed 4. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token ## Step 2: Configure Cursor 1. Open Cursor 2. Go to **Settings** → **Features** → **MCP** 3. Or open Cursor settings file directly ## Step 3: Add Pylar MCP Server Add Pylar to your MCP configuration: **Configuration Path**: `~/.cursor/mcp.json` or Cursor settings **Configuration**: ```json theme={null} { "mcpServers": { "pylar": { "url": "https://mcp.publish.pylar.ai/mcp", "headers": { "Authorization": "Bearer YOUR_BEARER_TOKEN_HERE" } } } } ``` Replace `YOUR_BEARER_TOKEN_HERE` with your actual Bearer Token. ## Step 4: Restart Cursor 1. Save the configuration 2. Restart Cursor 3. Cursor will connect to your Pylar MCP server ## Step 5: Verify Connection 1. Open a chat with Cursor's AI 2. Ask: *"What MCP tools do you have available?"* 3. Cursor should list your Pylar tools ## Using Your Tools in Cursor Once connected, you can use Pylar tools while coding: **Example**: *"Use the customer revenue tool to get data for account ID 12345"* Cursor will: 1. Call your Pylar MCP tool 2. Retrieve data from your view 3. Use the data in your code or conversation 4. Help you build applications with real data ## Benefits * ✅ **Code with Real Data**: Access your data while coding * ✅ **AI Assistance**: Cursor can use your tools to answer questions * ✅ **Secure**: Data access through governed views only * ✅ **Automatic Updates**: View changes reflect immediately * ✅ **Full Control**: Manage everything from Pylar ## Troubleshooting ### Issue: Cursor can't connect **Solutions**: * Verify configuration file location * Check Bearer Token format * Ensure tools are published * Restart Cursor ### Issue: Tools not appearing **Solutions**: * Check MCP configuration syntax * Verify token is correct * Review Cursor logs for errors * Test connection in Pylar first ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Publish your tools * [Evals](/learn/evals/overview) - Monitor tool usage * [Other Builders](/learn/connecting-agent-builders/overview) - Connect to other platforms # LangGraph Source: https://docs.pylar.ai/learn/connecting-agent-builders/langgraph Connect Pylar MCP tools to LangGraph for building stateful agent workflows with data access ## Overview LangGraph is a framework for building stateful, multi-actor applications with LLMs. Connect your Pylar MCP tools to LangGraph to give your agents access to your data through governed views. ## Prerequisites * ✅ Python environment with LangGraph installed * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Installation Install the MCP Python client: ```bash theme={null} pip install mcp ``` ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token ## Step 2: Connect to Pylar in LangGraph Create an MCP client connection: ```python theme={null} from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client import httpx # Pylar MCP server configuration PYLAR_MCP_URL = "https://mcp.publish.pylar.ai/mcp" PYLAR_BEARER_TOKEN = "YOUR_BEARER_TOKEN_HERE" # Create HTTP client with authentication async def create_pylar_client(): async with httpx.AsyncClient() as client: headers = { "Authorization": f"Bearer {PYLAR_BEARER_TOKEN}", "Content-Type": "application/json" } # Connect to Pylar MCP server response = await client.post( f"{PYLAR_MCP_URL}/tools/list", headers=headers ) if response.status_code == 200: tools = response.json() return tools else: raise Exception(f"Failed to connect: {response.status_code}") # Use in your LangGraph agent async def call_pylar_tool(tool_name, arguments): async with httpx.AsyncClient() as client: headers = { "Authorization": f"Bearer {PYLAR_BEARER_TOKEN}", "Content-Type": "application/json" } response = await client.post( f"{PYLAR_MCP_URL}/tools/call", headers=headers, json={ "name": tool_name, "arguments": arguments } ) return response.json() ``` ## Step 3: Integrate with LangGraph Agent Add Pylar tools to your LangGraph agent: ```python theme={null} from langgraph.graph import StateGraph, END from langchain_core.tools import tool # Define Pylar tools as LangChain tools @tool async def get_engagement_scores(event_type: str): """Get engagement scores for a given event type.""" result = await call_pylar_tool( "fetch_engagement_scores_by_event_type", {"event_type": event_type} ) return result # Add to your agent's tool list tools = [get_engagement_scores] # Use in LangGraph workflow def create_agent(): workflow = StateGraph(AgentState) workflow.add_node("agent", your_agent_node) workflow.add_node("tools", execute_tools) workflow.set_entry_point("agent") workflow.add_edge("agent", "tools") workflow.add_edge("tools", END) return workflow.compile() ``` ## Step 4: Use in Your Workflow Your LangGraph agent can now use Pylar tools: ```python theme={null} # Agent can call Pylar tools result = await agent.invoke({ "messages": [("user", "Get engagement scores for login events")] }) # Tools are called automatically based on agent decisions ``` ## Benefits * ✅ **Stateful Workflows**: Build complex agent workflows with data access * ✅ **Type Safety**: Use typed tools in your Python code * ✅ **Centralized Control**: Update views in Pylar, agents get updates * ✅ **Full Visibility**: Monitor agent usage through Pylar Evals * ✅ **No SQL in Code**: Keep SQL in Pylar, not in your agent code ## Best Practices ### Error Handling ```python theme={null} try: result = await call_pylar_tool(tool_name, arguments) except Exception as e: # Handle errors gracefully logger.error(f"Pylar tool error: {e}") return {"error": str(e)} ``` ### Caching Cache tool results when appropriate: ```python theme={null} from functools import lru_cache @lru_cache(maxsize=100) async def get_cached_data(tool_name, arguments): return await call_pylar_tool(tool_name, arguments) ``` ### Type Validation Validate tool arguments: ```python theme={null} from pydantic import BaseModel class EngagementScoreArgs(BaseModel): event_type: str async def get_engagement_scores(args: EngagementScoreArgs): return await call_pylar_tool( "fetch_engagement_scores_by_event_type", args.dict() ) ``` ## Troubleshooting ### Issue: Connection errors **Solutions**: * Verify Bearer Token is correct * Check network connectivity * Ensure MCP URL is correct * Test connection with curl first ### Issue: Tool not found **Solutions**: * Verify tool name matches exactly * Check tools are published in Pylar * List available tools first ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Publish your tools * [Evals](/learn/evals/overview) - Monitor LangGraph agent usage * [Other Builders](/learn/connecting-agent-builders/overview) - Connect to other platforms # Make Source: https://docs.pylar.ai/learn/connecting-agent-builders/make Connect Pylar MCP tools to Make (Integromat) for visual automation workflows with data access ## Overview Make (formerly Integromat) is a visual automation platform. Connect your Pylar MCP tools to Make to access your data in automation scenarios without writing code. ## Prerequisites * ✅ Make account * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token ## Step 2: Create HTTP Module in Make 1. In Make, create a new scenario 2. Add an **"HTTP"** module 3. Choose **"Make a Request"** ## Step 3: Configure HTTP Request **URL**: `https://mcp.publish.pylar.ai/mcp/tools/call` **Method**: `POST` **Headers**: ``` Authorization: Bearer YOUR_BEARER_TOKEN_HERE Content-Type: application/json ``` **Body Type**: `Raw` **Body Content (JSON)**: ```json theme={null} { "name": "fetch_engagement_scores_by_event_type", "arguments": { "event_type": "{{1.event_type}}" } } ``` Replace `YOUR_BEARER_TOKEN_HERE` with your token and `{{1.event_type}}` with your Make data field. ## Step 4: Parse Response 1. Use Make's JSON parser to extract data 2. Map data to subsequent modules 3. Build your automation workflow ## Example Scenario **Trigger**: New record in Google Sheets **Module 1**: HTTP - Call Pylar tool * Get customer data based on email **Module 2**: Update CRM * Use Pylar data to update customer record **Module 3**: Send notification * Alert team with customer insights ## Benefits * ✅ **Visual Workflows**: Build automations visually * ✅ **No Code**: Drag-and-drop interface * ✅ **Centralized Updates**: View changes reflect automatically * ✅ **Secure**: Data through governed views * ✅ **Monitoring**: Track usage in Pylar Evals ## Troubleshooting ### Issue: Request fails **Solutions**: * Verify Bearer Token in headers * Check JSON body format * Ensure tool name is correct * Test in Pylar first ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Publish tools * [Evals](/learn/evals/overview) - Monitor usage * [Other Builders](/learn/connecting-agent-builders/overview) - More platforms # n8n Source: https://docs.pylar.ai/learn/connecting-agent-builders/n8n Connect Pylar MCP tools to n8n for workflow automation with visual data access ## Overview n8n is an open-source workflow automation tool. Connect your Pylar MCP tools to n8n to access your data in automation workflows using visual nodes. ## Prerequisites * ✅ n8n installed (self-hosted or cloud) * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token ## Step 2: Create HTTP Request Node 1. In n8n, create a new workflow 2. Add an **"HTTP Request"** node to your canvas 3. Connect it to your workflow trigger or previous node ## Step 3: Configure HTTP Request Node ### Basic Settings 1. Click on the HTTP Request node to configure it 2. Set the following: **Method**: `POST` **URL**: Enter your MCP HTTP Stream URL ``` https://mcp.publish.pylar.ai/mcp ``` ### Authentication 1. Expand the **Authentication** section 2. Select **"Header Auth"** or **"Generic Credential Type"** 3. Configure: * **Name**: `Authorization` * **Value**: `Bearer YOUR_BEARER_TOKEN_HERE` Replace `YOUR_BEARER_TOKEN_HERE` with your actual Bearer Token. ### Headers Add additional headers if needed: * **Content-Type**: `application/json` ### Request Body 1. Set **Body Content Type** to `JSON` 2. Add the JSON body for calling your MCP tool: ```json theme={null} { "jsonrpc": "2.0", "id": "1", "method": "tools/call", "params": { "name": "fetch_engagement_scores_by_event_type", "arguments": { "event_type": "{{ $json.event_type }}" } } } ``` Use n8n expressions like `{{ $json.event_type }}` to reference data from previous nodes. ## Step 4: Select Tools Once configured, you can: 1. **Select which tools** you want the agent/workflow to have access to 2. Configure different nodes for different tools 3. Chain multiple tool calls if needed ## Step 5: Test the Connection 1. Click **"Execute Step"** to test the node 2. Review the response to verify the tool works 3. Check that data is returned correctly If the Execute Step returns data successfully, your connection is working! ## Step 6: Use in Your Workflow After testing, you can: 1. **Go to the chat** in n8n and ask questions to the AI 2. **Run the workflow** to execute automation 3. The AI or workflow will use your Pylar tools to access data ## Example Workflow **Trigger**: Webhook receives event with `event_type` **Node 1**: HTTP Request - Call Pylar Tool * Method: POST * URL: `https://mcp.publish.pylar.ai/mcp` * Auth: Bearer Token * Body: Tool call with `event_type` from trigger **Node 2**: Process Response * Parse JSON response * Extract engagement scores **Node 3**: Conditional Logic * Check if score is above threshold **Node 4**: Send Notification * Alert if score is high ## Benefits * ✅ **Visual Workflows**: Build automations visually * ✅ **No Code Required**: Use drag-and-drop interface * ✅ **Centralized Control**: Update views in Pylar, workflows get updates * ✅ **Secure Access**: Through governed views * ✅ **Full Visibility**: Monitor usage in Pylar Evals * ✅ **Open Source**: Self-host or use cloud ## Troubleshooting ### Issue: Authentication fails **Solutions**: * Verify Bearer Token format: `Bearer YOUR_TOKEN` * Check header name is exactly "Authorization" * Ensure no extra spaces in token * Test authentication separately ### Issue: Tool not found **Solutions**: * Verify tool name matches exactly * Check tools are published in Pylar * Review JSON body structure * Test tool in Pylar first ### Issue: Request format error **Solutions**: * Verify JSON-RPC format is correct * Check method name: `tools/call` * Ensure parameters match tool schema * Review n8n expression syntax ## Best Practices ### Use Expressions Use n8n expressions to dynamically set parameters: ```json theme={null} { "event_type": "{{ $json.event_type }}", "start_date": "{{ $json.start_date }}" } ``` ### Error Handling Add error handling nodes: 1. Add IF node after HTTP Request 2. Check for errors in response 3. Route to error handling or retry logic ### Data Transformation Process tool responses: 1. Use Set node to extract specific fields 2. Transform data for next steps 3. Map to other workflow nodes ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Publish your tools * [Evals](/learn/evals/overview) - Monitor n8n workflow usage * [Other Builders](/learn/connecting-agent-builders/overview) - Connect to other platforms See how your n8n workflows use Pylar tools # OpenAI Platform Source: https://docs.pylar.ai/learn/connecting-agent-builders/openai-platform Connect Pylar MCP tools to OpenAI's platform for AI agent development ## Overview OpenAI Platform provides tools for building AI agents and assistants. Connect your Pylar MCP tools to give your OpenAI agents access to your data through governed views. ## Prerequisites * ✅ OpenAI Platform account * ✅ Access to OpenAI agent builder features * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Generate your token if needed 4. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token ## Step 2: Connect Pylar to OpenAI Platform 1. In the OpenAI Platform, navigate to your agent builder 2. Look for **"Connect"** or **"Add Tool"** button 3. Click **"Connect"** to add your MCP server ## Step 3: Configure MCP Connection When you click "Connect", you'll need to provide: * **MCP Server URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Token**: Your Bearer Token from Pylar After connecting, you'll see your MCP tools appear in the platform. ## Step 4: Configure Tool Access Once your MCP tools appear, you can: 1. **Modify Approval Status**: Set which tools require approval before use 2. **Select Tools**: Choose which tools you want the agent to have access to 3. **Configure Permissions**: Set access levels for different tools Click the **"Add"** button to confirm your selections. You can selectively enable tools based on what your agent needs. Not all tools need to be available to every agent. ## Step 5: Test Your Tools 1. Click the **"Preview"** button in the top right corner 2. Ask a question that requires the agent to use your MCP tool **Example**: *"Get engagement scores for login events"* The agent will: 1. Recognize it needs to use your Pylar tool 2. Call the tool with appropriate parameters 3. Execute the query against your view 4. Return the results and use them to answer your question The Preview feature lets you test how the agent uses your MCP tools before deploying to production. ## Using Your Tools Once connected and configured, your OpenAI agents can: * Access your data through governed views * Use tools automatically when needed * Combine multiple tools for complex queries * Provide answers based on real-time data ## Tool Management ### Approval Status You can set approval requirements for tools: * **Auto-approve**: Tools run automatically * **Require approval**: Tools need manual approval before execution ### Tool Selection Select which tools are available to your agent: * Enable only tools your agent needs * Disable tools that aren't relevant * Update selections anytime ## Benefits * ✅ **OpenAI Integration**: Use OpenAI's powerful models with your data * ✅ **Selective Access**: Choose which tools agents can use * ✅ **Approval Controls**: Require approval for sensitive operations * ✅ **Centralized Updates**: Update views in Pylar, agents get updates * ✅ **Full Visibility**: Monitor usage through Pylar Evals ## Troubleshooting ### Issue: Tools not appearing after connect **Solutions**: * Verify Bearer Token is correct * Check MCP URL is correct * Ensure tools are published in Pylar * Refresh the connection ### Issue: Agent can't use tools **Solutions**: * Verify tools are selected/enabled * Check approval status settings * Review tool permissions * Test tools in Preview mode first ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Publish your tools * [Evals](/learn/evals/overview) - Monitor agent usage * [Other Builders](/learn/connecting-agent-builders/overview) - Connect to other platforms See how OpenAI agents use your tools through Evals # Overview Source: https://docs.pylar.ai/learn/connecting-agent-builders/overview Connect any agent builder to Pylar - code-driven or no-code, all controlled from one unified platform ## One Control Pane, Any Agent Builder Pylar provides a unified way to connect your data views to **any agent builder**—whether it's code-driven like LangGraph, no-code like Zapier, or AI-native like Claude Desktop. All controlled, optimized, and iterated from one place: Pylar. ```mermaid theme={null} graph TB PYLAR[Pylar
MCP Tools Published] subgraph "Code-Driven" CD1[Claude Desktop] CD2[Cursor] CD3[Windsurf] CD4[VS Code] CD5[LangGraph] CD6[OpenAI Platform] end subgraph "No-Code" NC1[Zapier] NC2[Make] NC3[n8n] end PYLAR --> CD1 PYLAR --> CD2 PYLAR --> CD3 PYLAR --> CD4 PYLAR --> CD5 PYLAR --> CD6 PYLAR --> NC1 PYLAR --> NC2 PYLAR --> NC3 style PYLAR fill:#FF4017,stroke:#CC3300,color:#fff ``` ## The Problem with Traditional Approaches Traditional data access for agents requires: * ❌ **API Development**: Building custom APIs for each agent builder * ❌ **Scattered SQL**: SQL queries scattered across different systems * ❌ **No Central Control**: Can't update queries from one place * ❌ **Complex Integration**: Different integration patterns for each builder * ❌ **Maintenance Nightmare**: Changes require updates everywhere * ❌ **No Visibility**: Hard to see how agents are using data ## The Pylar Solution With Pylar, you get: * ✅ **One MCP Server**: Single connection point for all agent builders * ✅ **Centralized Views**: Define data access once in Pylar * ✅ **One Control Pane**: Update views and tools from Pylar, changes reflect everywhere * ✅ **No API Code**: No need to build or maintain APIs * ✅ **No SQL Changes Everywhere**: Update SQL in one place, all agents get updates * ✅ **Full Visibility**: See how all agents interact with your data through Evals Pylar acts as a universal data access layer. Define your views once, connect any agent builder, and control everything from Pylar's dashboard. ## How It Works ### Step 1: Define Views in Pylar Create your data views in Pylar's SQL IDE: * Write SQL queries * Join across multiple databases * Define exactly what data agents can access ### Step 2: Build MCP Tools Create MCP tools on your views: * Use AI to generate tools from natural language * Or configure tools manually * Test before publishing ### Step 3: Publish and Get Credentials Publish your tools and receive: * **MCP HTTP Stream URL**: Connection endpoint * **Authorization Bearer Token**: Secure authentication ### Step 4: Connect Any Agent Builder Paste your credentials into any agent builder: * **Code-driven** (LangGraph, OpenAI Agents, custom code) * **No-code** (Zapier, Make, n8n) * **AI-native** (Claude Desktop, Cursor, Windsurf) ### Step 5: Control from Pylar Update views or tools anytime: * Changes reflect automatically in all connected builders * No need to update code or configurations elsewhere * Monitor everything through Evals ## Universal Compatibility ### Code-Driven Agent Builders Perfect for developers building custom agents: * **LangGraph**: Build stateful agent workflows * **OpenAI Assistants API**: Create AI assistants * **Custom Python/JavaScript**: Any MCP-compatible code * **LangChain**: Framework for LLM applications **How it works**: Use MCP client libraries to connect to Pylar's MCP server. ### No-Code Agent Builders Perfect for non-developers building automations: * **Zapier**: Connect apps and automate workflows * **Make (Integromat)**: Visual automation platform * **n8n**: Open-source workflow automation * **Any HTTP-based tool**: Tools that support HTTP requests **How it works**: Use HTTP requests to Pylar's MCP server endpoint. ### AI-Native Builders Perfect for AI agent development: * **Claude Desktop**: Anthropic's desktop AI assistant * **Cursor**: AI-powered code editor * **Windsurf**: AI coding assistant * **Any MCP-compatible tool**: Tools supporting MCP protocol **How it works**: Native MCP protocol support for seamless integration. ## Key Benefits ### For Developers * **No API Development**: Skip building custom APIs * **Standard Protocol**: Use MCP, the emerging standard * **Focus on Logic**: Build agent logic, not data access code * **Easy Updates**: Change data access without touching agent code ### For Non-Developers * **No Code Required**: Connect via HTTP requests * **Visual Interfaces**: Use familiar no-code tools * **Easy Setup**: Just paste credentials * **Automatic Updates**: Changes happen automatically ### For Organizations * **Centralized Control**: One place to manage all data access * **Security**: Views are the only access level * **Compliance**: Full audit trail of all access * **Scalability**: Add new agent builders without complexity ## The Workflow ``` ┌─────────────────┐ │ Your Views │ ← Define once in Pylar │ (Pylar IDE) │ └────────┬────────┘ │ ↓ ┌─────────────────┐ │ MCP Tools │ ← Create tools on views │ (Pylar) │ └────────┬────────┘ │ ↓ ┌─────────────────┐ │ Publish Tools │ ← Get credentials │ (Pylar) │ └────────┬────────┘ │ ├─────────────────┬─────────────────┬───────────────┐ ↓ ↓ ↓ ↓ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ LangGraph │ │ Zapier │ │ Claude │ │ Custom │ │ (Code) │ │ (No-code) │ │ (AI) │ │ (Any) │ └──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ │ │ │ │ └─────────────────┴─────────────────┴───────────────┘ ↓ ┌─────────────────┐ │ Evals (Pylar) │ ← Monitor all from one place └─────────────────┘ ``` ## Control and Iteration ### Update Views Change your SQL queries in Pylar: * All connected agents automatically get updated data * No code changes needed in agent builders * No configuration updates required ### Optimize Tools Refine MCP tools based on Evals: * See how agents actually use your tools * Identify optimization opportunities * Update tools and see improvements immediately ### Iterate Quickly Make changes and see results: * Test changes in Pylar * Publish updates * All agents get updates automatically * Monitor impact through Evals The power of Pylar is in the control pane. Make changes once, and all your agent builders benefit immediately—no matter which platform they're built on. ## Next Steps Ready to connect your agent builder? * [Claude Desktop](/learn/connecting-agent-builders/claude-desktop) - Connect to Claude Desktop * [Cursor](/learn/connecting-agent-builders/cursor) - Connect to Cursor * [LangGraph](/learn/connecting-agent-builders/langgraph) - Connect to LangGraph * [Zapier](/learn/connecting-agent-builders/zapier) - Connect to Zapier * [Make](/learn/connecting-agent-builders/make) - Connect to Make * [n8n](/learn/connecting-agent-builders/n8n) - Connect to n8n * [OpenAI Agent Builder](/learn/connecting-agent-builders/openai-agent-builder) - Connect to OpenAI Get step-by-step instructions for your agent builder # VS Code Source: https://docs.pylar.ai/learn/connecting-agent-builders/vs-code Connect Pylar MCP tools to VS Code using Python scripts for programmatic data access ## Overview VS Code can connect to Pylar MCP tools using Python scripts. This allows you to programmatically access your data views from VS Code or any Python environment. ## Prerequisites * ✅ VS Code installed * ✅ Python installed * ✅ `requests` library installed (`pip install requests`) * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token ## Step 2: Create Python Script Create a new Python file in VS Code (e.g., `mcp_jsonrpc_client.py`) and add the following code: ```python theme={null} # mcp_jsonrpc_client.py AUTH_TOKEN = "Bearer xxxx" # replace with your token import json import uuid import requests MCP_URL = "https://mcp.publish.pylar.ai/mcp" AUTH = AUTH_TOKEN HEADERS = { "Authorization": AUTH, "Content-Type": "application/json", "Accept": "application/json", } def rpc_call(method: str, params=None): payload = { "jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": method, } if params is not None: payload["params"] = params r = requests.post(MCP_URL, headers=HEADERS, data=json.dumps(payload), timeout=30) r.raise_for_status() resp = r.json() if "error" in resp: raise RuntimeError(f"RPC error {resp['error'].get('code')}: {resp['error'].get('message')}") return resp["result"] def initialize(): # Many MCP servers accept initialize but some don't strictly require it. params = { "clientInfo": {"name": "mcp-jsonrpc-python", "version": "0.1.0"}, "capabilities": {}, # add if you advertise anything specific } try: return rpc_call("initialize", params) except Exception as e: # If initialize isn't supported, it's fine to continue. print(f"(initialize skipped: {e})") def list_tools(): result = rpc_call("tools/list", {}) # Expected shape: {"tools":[{"name":"...","description":"...","inputSchema":{...}}, ...]} tools = result.get("tools", []) for i, t in enumerate(tools, 1): desc = t.get("description") or "" print(f"{i}. {t.get('name')} {('- ' + desc) if desc else ''}") return tools def get_tool_input_schema(tool): """Extract the input schema for a tool and return required parameters.""" schema = tool.get("inputSchema", {}) properties = schema.get("properties", {}) required = schema.get("required", []) return properties, required def prompt_for_tool_arguments(tool): """Prompt user for tool arguments based on the tool's input schema.""" properties, required = get_tool_input_schema(tool) if not properties: # Fallback to generic input if no schema user_text = input("Enter input for the tool: ").strip() return {"input": user_text} arguments = {} print(f"\nTool '{tool['name']}' requires the following parameters:") for param_name, param_info in properties.items(): param_type = param_info.get("type", "string") param_desc = param_info.get("description", "") is_required = param_name in required prompt = f" {param_name} ({param_type})" if is_required: prompt += " [REQUIRED]" if param_desc: prompt += f" - {param_desc}" print(prompt) if is_required: while True: value = input(f"Enter {param_name}: ").strip() if value: # Try to convert to appropriate type if param_type == "integer": try: arguments[param_name] = int(value) break except ValueError: print("Please enter a valid integer.") continue elif param_type == "number": try: arguments[param_name] = float(value) break except ValueError: print("Please enter a valid number.") continue elif param_type == "boolean": if value.lower() in ["true", "1", "yes", "y"]: arguments[param_name] = True break elif value.lower() in ["false", "0", "no", "n"]: arguments[param_name] = False break else: print("Please enter true/false, yes/no, or 1/0.") continue else: arguments[param_name] = value break else: print("This parameter is required.") else: value = input(f"Enter {param_name} (optional, press Enter to skip): ").strip() if value: # Try to convert to appropriate type if param_type == "integer": try: arguments[param_name] = int(value) except ValueError: arguments[param_name] = value elif param_type == "number": try: arguments[param_name] = float(value) except ValueError: arguments[param_name] = value elif param_type == "boolean": if value.lower() in ["true", "1", "yes", "y"]: arguments[param_name] = True elif value.lower() in ["false", "0", "no", "n"]: arguments[param_name] = False else: arguments[param_name] = value else: arguments[param_name] = value return arguments def call_tool(name: str, arguments: dict): # Arguments must match the tool's inputSchema. # If you don't know the schema, try a single-field convention like {"input": ""}. params = {"name": name, "arguments": arguments} result = rpc_call("tools/call", params) # Expected shape: {"content":[{"type":"text","text":"..."}], "isError": false} return result def main(): initialize() tools = list_tools() if not tools: print("No tools available.") return choice = input("\nSelect a tool by number or name: ").strip() if choice.isdigit(): idx = int(choice) - 1 if idx < 0 or idx >= len(tools): print("Invalid index.") return tool = tools[idx] else: matches = [t for t in tools if t.get("name","").lower() == choice.lower()] tool = matches[0] if matches else None if not tool: print("Tool not found.") return tool_name = tool["name"] print(f"Selected: {tool_name}") # Show the tool's input schema properties, required = get_tool_input_schema(tool) if properties: print(f"\nInput Schema for '{tool_name}':") print(json.dumps(tool.get("inputSchema", {}), indent=2)) # Get proper arguments based on schema arguments = prompt_for_tool_arguments(tool) print(f"\nCalling tool with arguments: {json.dumps(arguments, indent=2)}") try: result = call_tool(tool_name, arguments) print("\n=== Tool Result ===") if result.get("isError"): print("ERROR:", result) else: # Handle different content types content = result.get("content", []) for item in content: if item.get("type") == "text": print(item.get("text", "")) else: print(json.dumps(item, indent=2)) except Exception as e: print(f"Error calling tool: {e}") print("Full error details:") import traceback traceback.print_exc() if __name__ == "__main__": main() ``` ## Step 3: Add Your Bearer Token Replace `"Bearer xxxx"` on line 2 with your actual Bearer Token: ```python theme={null} AUTH_TOKEN = "Bearer YOUR_ACTUAL_TOKEN_HERE" ``` The MCP URL is already in the code. You only need to add your Authorization Bearer Token. ## Step 4: Run the Script 1. In VS Code, open the terminal 2. Run the script: ```bash theme={null} python mcp_jsonrpc_client.py ``` The script will: 1. Initialize the connection to Pylar 2. List all available tools 3. Prompt you to select a tool 4. Ask for tool parameters 5. Call the tool and display results ## Using the Script ### List Available Tools When you run the script, it will automatically list all available Pylar tools: ``` 1. fetch_engagement_scores_by_event_type - Fetches engagement scores... 2. get_customer_revenue - Gets customer revenue data... ``` ### Select and Use a Tool 1. Enter the tool number or name when prompted 2. The script will show the tool's input schema 3. Enter required parameters 4. The tool will be called and results displayed ## Example Usage ```bash theme={null} $ python mcp_jsonrpc_client.py 1. fetch_engagement_scores_by_event_type - Fetches engagement scores... 2. get_customer_revenue - Gets customer revenue... Select a tool by number or name: 1 Selected: fetch_engagement_scores_by_event_type Input Schema for 'fetch_engagement_scores_by_event_type': { "type": "object", "properties": { "event_type": { "type": "string", "description": "Event type to filter by" } }, "required": ["event_type"] } Tool 'fetch_engagement_scores_by_event_type' requires the following parameters: event_type (string) [REQUIRED] - Event type to filter by Enter event_type: login Calling tool with arguments: { "event_type": "login" } === Tool Result === [Results from your tool...] ``` ## Integrating into Your Code You can also use the functions directly in your Python code: ```python theme={null} from mcp_jsonrpc_client import rpc_call, list_tools, call_tool # List tools tools = list_tools() # Call a tool programmatically result = call_tool( "fetch_engagement_scores_by_event_type", {"event_type": "login"} ) print(result) ``` ## Benefits * ✅ **Programmatic Access**: Use Pylar tools from Python code * ✅ **Interactive Testing**: Test tools from command line * ✅ **Easy Integration**: Use functions in your projects * ✅ **Type Safety**: Automatic parameter type conversion * ✅ **Full Control**: Access all MCP protocol features ## Troubleshooting ### Issue: "Module not found" error **Solution**: Install required packages: ```bash theme={null} pip install requests ``` ### Issue: Connection errors **Solutions**: * Verify Bearer Token is correct * Check MCP URL is correct * Ensure network connectivity * Test connection with curl first ### Issue: Tool not found **Solutions**: * Verify tool name matches exactly * Check tools are published in Pylar * List tools first to see available options ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Publish your tools * [Evals](/learn/evals/overview) - Monitor tool usage * [Other Builders](/learn/connecting-agent-builders/overview) - Connect to other platforms # Windsurf Source: https://docs.pylar.ai/learn/connecting-agent-builders/windsurf Connect Pylar MCP tools to Windsurf for AI-powered coding assistance with data access ## Overview Windsurf is an AI-powered code editor that supports MCP tools. Connect your Pylar tools to Windsurf to give the AI assistant access to your data through governed views while coding. ## Prerequisites * ✅ Windsurf editor installed * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Generate your token if needed 4. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token ## Step 2: Open Windsurf Command Palette 1. Open Windsurf 2. Press the keyboard shortcut: * **Mac**: `Cmd + Shift + P` * **Windows/Linux**: `Ctrl + Shift + P` 3. Type and select: **"Windsurf: Open MCP Configuration"** This opens or creates your MCP config file, usually located at: ``` ~/.codeium/windsurf/mcp_config.json ``` ## Step 3: Add Your MCP Server Configuration Inside the JSON file, add a new entry under `"mcpServers"`: ```json theme={null} { "mcpServers": { "view-mcp-node": { "serverUrl": "https://mcp.publish.pylar.ai/mcp", "headers": { "Authorization": "Bearer xxxxx" } } } } ``` **Important**: * Replace `xxxxx` with your actual Bearer Token from Pylar * The name `"view-mcp-node"` is a local alias—you can rename it to anything you prefer * If the `"headers"` key is unsupported in your Windsurf build, omit it and use a proxy or environment variable instead The config file location may vary. Windsurf will create it if it doesn't exist when you open the MCP Configuration. ## Step 4: Save and Reload MCP Servers 1. Save the `mcp_config.json` file 2. Back in Windsurf, open the command palette again: * **Mac**: `Cmd + Shift + P` * **Windows/Linux**: `Ctrl + Shift + P` 3. Run: **"Windsurf: Reload MCP Servers"** You'll see a success toast notification, and your new MCP server will appear in the MCP sidebar under the name you used (e.g., `view-mcp-node`). If you see the success toast and your MCP server appears in the sidebar, the connection is successful! ## Step 5: Test the MCP Tools 1. Go to the chat in Windsurf 2. Write a question that requires the agent to use the MCP tool **Example**: *"Use the engagement score tool to get scores for login events"* The AI assistant will: 1. Recognize it needs to use your Pylar tool 2. Call the tool with appropriate parameters 3. Execute the query and return results 4. Use the data to answer your question ## Using Your Tools in Windsurf Once connected, you can use Pylar tools while coding: * Ask questions about your data * Have the AI use tools to retrieve information * Build applications with real data from your views * Get insights while coding ## Troubleshooting ### Issue: MCP server not appearing **Solutions**: * Verify the JSON syntax is correct * Check that you saved the config file * Ensure you ran "Reload MCP Servers" command * Verify Bearer Token is correct * Check Windsurf version supports MCP ### Issue: Headers not supported If headers are unsupported in your Windsurf build: **Alternative Solutions**: * Use a proxy server to add authentication * Set authentication via environment variables * Check for Windsurf updates ### Issue: Tools not working **Solutions**: * Verify tools are published in Pylar * Check tool names match exactly * Review error messages in Windsurf * Test tools in Pylar first ## Benefits * ✅ **AI-Powered Coding**: Access your data while coding * ✅ **Natural Language**: Ask questions in plain English * ✅ **Secure Access**: Through governed views only * ✅ **Automatic Updates**: View changes reflect immediately * ✅ **Full Control**: Manage everything from Pylar ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Publish your tools * [Evals](/learn/evals/overview) - Monitor tool usage * [Other Builders](/learn/connecting-agent-builders/overview) - Connect to other platforms # Zapier Source: https://docs.pylar.ai/learn/connecting-agent-builders/zapier Connect Pylar MCP tools to Zapier for no-code automation workflows with data access ## Overview Zapier is a no-code automation platform that connects apps and automates workflows. Connect your Pylar MCP tools to Zapier to access your data in automated workflows without writing code. ## Prerequisites * ✅ Zapier account * ✅ Pylar project with published MCP tools * ✅ MCP HTTP Stream URL and Bearer Token from Pylar ## Step 1: Get Your Pylar Credentials 1. In Pylar, navigate to your project 2. Click **"Publish"** in the right sidebar 3. Copy both: * **MCP HTTP Stream URL**: `https://mcp.publish.pylar.ai/mcp` * **Authorization Bearer Token**: Your unique token ## Step 2: Create a Webhook in Zapier Since Zapier doesn't have native MCP support, we'll use HTTP requests: 1. In Zapier, create a new Zap 2. Choose **"Webhooks by Zapier"** as your trigger or action 3. Select **"Custom Request"** ## Step 3: Configure HTTP Request Configure the HTTP request to call Pylar MCP tools: **Method**: `POST` **URL**: `https://mcp.publish.pylar.ai/mcp/tools/call` **Headers**: ``` Authorization: Bearer YOUR_BEARER_TOKEN_HERE Content-Type: application/json ``` **Data (JSON)**: ```json theme={null} { "name": "fetch_engagement_scores_by_event_type", "arguments": { "event_type": "{{trigger_field}}" } } ``` Replace `YOUR_BEARER_TOKEN_HERE` with your actual token and `{{trigger_field}}` with your Zapier field. ## Step 4: Use Response Data Use the response from Pylar in subsequent Zapier steps: 1. Parse the JSON response 2. Use data fields in other Zapier actions 3. Build your automation workflow ## Example Workflow **Trigger**: New email in Gmail **Action 1**: Call Pylar tool to get customer data * Tool: `fetch_customer_by_email` * Argument: Email from trigger **Action 2**: Use data in other apps * Send to Slack * Update CRM * Create task ## Benefits * ✅ **No Code Required**: Build automations visually * ✅ **Centralized Control**: Update views in Pylar, Zaps get updates * ✅ **Secure Access**: Data access through governed views * ✅ **Easy Integration**: Works with 6000+ Zapier apps * ✅ **Full Visibility**: Monitor usage through Pylar Evals ## Troubleshooting ### Issue: Authentication errors **Solutions**: * Verify Bearer Token is correct * Check header format: `Bearer YOUR_TOKEN` * Ensure no extra spaces in token ### Issue: Tool not found **Solutions**: * Verify tool name matches exactly * Check tools are published * Test tool in Pylar first ## Next Steps * [Publishing Tools](/learn/publishing-tools/publishing-your-tools) - Publish your tools * [Evals](/learn/evals/overview) - Monitor Zapier usage * [Other Builders](/learn/connecting-agent-builders/overview) - Connect to other platforms # Cross-Database Joins Source: https://docs.pylar.ai/learn/creating-data-views/cross-database-joins Learn how to query and join data across multiple databases and dataframes in Pylar to create unified views ## Overview Pylar allows you to work with **Local Dataframes**—data that's already loaded in your Pylar session. This enables you to query and join multiple dataframes using SQL, creating unified views without needing to connect to external databases. ## What Are Local Dataframes? Local Dataframes are: * Data tables loaded into your Pylar session * Accessible through the SQL IDE * Queryable using standard SQL syntax * Joinable across multiple dataframes ```mermaid theme={null} graph TB subgraph "Pylar Session" DF1[table0
Events Dataframe] DF2[table1
Users Dataframe] DF3[table2
Sessions Dataframe] end SQL[SQL Query
JOIN on common keys] RESULT[Unified Result
Combined View] DF1 --> SQL DF2 --> SQL DF3 --> SQL SQL --> RESULT style SQL fill:#FF4017,stroke:#CC3300,color:#fff ``` Think of dataframes as temporary tables that exist in your current Pylar session. They're perfect for combining data from multiple sources or working with intermediate results. ## Setting Up Dataframe Queries To query local dataframes: 1. **Select Dataframe Source**: In the SQL IDE, set the datasource dropdown to **"Local Dataframes"** 2. **Reference Dataframe Names**: Use the dataframe name as the table name in your SQL query 3. **Write Standard SQL**: Use familiar SQL syntax to query and join your dataframes Dataframe names are case-sensitive and must match exactly. Make sure you know the exact names of your loaded dataframes before querying. ## Basic Dataframe Queries ### Selecting from a Single Dataframe Query a specific subset of data from a dataframe: ```sql theme={null} /* Selecting a subset of events from table0 */ SELECT * FROM table0 WHERE event_type = 'login'; ``` This query: * References `table0` as a dataframe in your session * Filters rows where `event_type` equals `'login'` * Returns all columns (`*`) from matching rows ### Selecting Specific Columns ```sql theme={null} SELECT event_id, event_type, timestamp, user_id FROM table0 WHERE event_type = 'login' ORDER BY timestamp DESC; ``` ### Filtering and Sorting ```sql theme={null} SELECT user_id, event_type, COUNT(*) as event_count FROM table0 WHERE event_type IN ('login', 'logout', 'purchase') AND timestamp >= '2024-01-01' GROUP BY user_id, event_type ORDER BY event_count DESC; ``` ## Joining Multiple Dataframes One of the most powerful features is joining data from multiple dataframes to create unified views. ### Basic Join Syntax ```sql theme={null} SELECT t1.column1, t1.column2, t2.column3, t2.column4 FROM dataframe1 t1 JOIN dataframe2 t2 ON t1.common_id = t2.common_id; ``` ### Example: Joining on Common ID Join two dataframes on a common identifier: ```sql theme={null} /* Joining on a common ID field between two tables */ SELECT t1.event_id, t1.event_type, t1.timestamp, t2.user_id, t2.user_name, t2.user_email FROM table1 t1 JOIN table2 t2 ON t1.event_id = t2.event_id; ``` This query: * Joins `table1` and `table2` dataframes * Matches rows where `event_id` values are equal * Returns selected columns from both dataframes * Uses table aliases (`t1`, `t2`) for clarity Always use table aliases when joining dataframes. It makes your queries more readable and helps avoid column name conflicts. ## Advanced Join Patterns ### Multiple Dataframe Joins Join three or more dataframes: ```sql theme={null} SELECT events.event_id, events.event_type, users.user_name, users.user_email, sessions.session_id, sessions.session_duration FROM table0 events JOIN table1 users ON events.user_id = users.user_id JOIN table2 sessions ON events.session_id = sessions.session_id WHERE events.event_type = 'purchase'; ``` ### Left Join for Optional Data Include all rows from the first dataframe, with optional data from the second: ```sql theme={null} SELECT customers.customer_id, customers.customer_name, orders.order_id, orders.order_amount FROM table0 customers LEFT JOIN table1 orders ON customers.customer_id = orders.customer_id; ``` ### Full Outer Join Include all rows from both dataframes: ```sql theme={null} SELECT COALESCE(contacts.contact_id, leads.lead_id) AS unified_id, contacts.email AS contact_email, leads.email AS lead_email, contacts.engagement_score, leads.lead_score FROM table0 contacts FULL OUTER JOIN table1 leads ON contacts.email = leads.email; ``` ## Real-World Examples ### Example 1: Customer Event Analysis Combine customer events with user profiles: ```sql theme={null} SELECT -- Event data e.event_id, e.event_type, e.timestamp, e.event_data, -- User profile data u.user_id, u.user_name, u.user_email, u.signup_date, u.plan_type, -- Calculated fields DATEDIFF(day, u.signup_date, e.timestamp) AS days_since_signup FROM table0 e -- events dataframe JOIN table1 u -- users dataframe ON e.user_id = u.user_id WHERE e.event_type IN ('purchase', 'subscription_upgrade') AND e.timestamp >= '2024-01-01' ORDER BY e.timestamp DESC; ``` ### Example 2: Marketing Attribution Join campaign data with conversion events: ```sql theme={null} SELECT -- Campaign data c.campaign_id, c.campaign_name, c.channel, c.start_date, c.budget, -- Conversion data conv.conversion_id, conv.conversion_date, conv.conversion_value, conv.user_id, -- Attribution metrics DATEDIFF(day, c.start_date, conv.conversion_date) AS days_to_convert, conv.conversion_value / c.budget AS roi FROM table0 c -- campaigns dataframe LEFT JOIN table1 conv -- conversions dataframe ON c.campaign_id = conv.campaign_id AND conv.conversion_date BETWEEN c.start_date AND DATEADD(day, 30, c.start_date) WHERE c.start_date >= '2024-01-01' ORDER BY c.start_date DESC, conv.conversion_value DESC; ``` ### Example 3: Product Performance Analysis Combine product catalog with sales and reviews: ```sql theme={null} SELECT -- Product catalog p.product_id, p.product_name, p.category, p.price, p.launch_date, -- Sales data s.total_units_sold, s.total_revenue, s.avg_order_quantity, s.last_sale_date, -- Review data r.avg_rating, r.review_count, r.positive_review_pct, -- Performance metrics s.total_revenue / NULLIF(DATEDIFF(day, p.launch_date, CURRENT_DATE()), 0) AS daily_revenue_rate, s.total_units_sold * r.avg_rating AS popularity_score FROM table0 p -- products dataframe LEFT JOIN ( SELECT product_id, SUM(quantity) AS total_units_sold, SUM(amount) AS total_revenue, AVG(quantity) AS avg_order_quantity, MAX(order_date) AS last_sale_date FROM table1 -- sales dataframe GROUP BY product_id ) s ON p.product_id = s.product_id LEFT JOIN ( SELECT product_id, AVG(rating) AS avg_rating, COUNT(*) AS review_count, SUM(CASE WHEN rating >= 4 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) AS positive_review_pct FROM table2 -- reviews dataframe GROUP BY product_id ) r ON p.product_id = r.product_id WHERE p.is_active = true ORDER BY popularity_score DESC NULLS LAST; ``` ## Join Types for Dataframes ### INNER JOIN Returns only rows that have matches in both dataframes. ```sql theme={null} SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id; ``` **Use When**: You only want data that exists in both dataframes. ### LEFT JOIN Returns all rows from the left dataframe, matched rows from the right. ```sql theme={null} SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id; ``` **Use When**: You want all data from the primary dataframe, with optional data from the secondary. ### RIGHT JOIN Returns all rows from the right dataframe, matched rows from the left. ```sql theme={null} SELECT * FROM table1 t1 RIGHT JOIN table2 t2 ON t1.id = t2.id; ``` **Use When**: You want all data from the secondary dataframe, with optional data from the primary. ### FULL OUTER JOIN Returns all rows from both dataframes, with NULLs for missing matches. ```sql theme={null} SELECT * FROM table1 t1 FULL OUTER JOIN table2 t2 ON t1.id = t2.id; ``` **Use When**: You want to combine data from both dataframes regardless of matches. ## Handling Data Type Mismatches When joining dataframes, ensure join keys are compatible: ### String vs Numeric IDs ```sql theme={null} -- Convert to compatible types SELECT * FROM table1 t1 JOIN table2 t2 ON CAST(t1.id AS VARCHAR) = t2.id; ``` ### Handling NULL Values ```sql theme={null} -- Use COALESCE for unified IDs SELECT COALESCE(t1.id, t2.id) AS unified_id FROM table1 t1 FULL OUTER JOIN table2 t2 ON t1.id = t2.id; ``` ### Case-Insensitive Matching ```sql theme={null} -- Normalize case for matching SELECT * FROM table1 t1 JOIN table2 t2 ON LOWER(t1.email) = LOWER(t2.email); ``` ## Best Practices ### 1. Use Descriptive Aliases ```sql theme={null} -- Good SELECT events.event_id, users.user_name FROM table0 events JOIN table1 users -- Avoid SELECT t1.id, t2.name FROM table0 t1 JOIN table1 t2 ``` ### 2. Select Specific Columns ```sql theme={null} -- Good: Explicit columns SELECT events.event_id, events.event_type, users.user_name -- Avoid: SELECT * in production SELECT * ``` ### 3. Filter Early ```sql theme={null} -- Good: Filter in WHERE clause FROM table0 events WHERE events.event_type = 'purchase' JOIN table1 users -- Avoid: Filtering after join when possible FROM table0 events JOIN table1 users WHERE events.event_type = 'purchase' ``` ### 4. Handle NULLs Explicitly ```sql theme={null} SELECT COALESCE(column1, 0) AS column1, COALESCE(column2, 'Unknown') AS column2 FROM ... ``` ### 5. Verify Dataframe Existence Before querying, ensure your dataframes are loaded and named correctly. Test with a simple query first: ```sql theme={null} SELECT COUNT(*) FROM table0; ``` ## Common Issues and Solutions ### Issue: "Table not found" Error **Cause**: Dataframe doesn't exist or name is incorrect. **Solution**: * Verify dataframe is loaded in your session * Check dataframe name matches exactly (case-sensitive) * Ensure datasource is set to "Local Dataframes" ### Issue: Join Returns No Results **Cause**: Join keys don't match or have incompatible types. **Solution**: * Verify join keys exist in both dataframes * Check data types match (use CAST if needed) * Test join keys individually: ```sql theme={null} SELECT DISTINCT id FROM table1; SELECT DISTINCT id FROM table2; ``` ### Issue: Column Name Conflicts **Cause**: Both dataframes have columns with the same name. **Solution**: * Use table aliases and qualify column names * Use `AS` to rename columns in SELECT * Example: ```sql theme={null} SELECT t1.id AS event_id, t2.id AS user_id ``` ### Issue: Performance Issues **Cause**: Large dataframes or complex joins. **Solution**: * Filter dataframes before joining * Use LIMIT to test with smaller datasets * Consider aggregating dataframes first ## Next Steps Now that you understand cross-database joins: * [Writing Your First View](/learn/creating-data-views/writing-your-first-view) - Create comprehensive views using joins * [View Best Practices](/learn/creating-data-views/view-best-practices) - Optimize your views for performance and maintainability Learn how to combine dataframe queries with database queries # Overview Source: https://docs.pylar.ai/learn/creating-data-views/overview Introduction to data views in Pylar - understand how views provide secure, governed access to your data ## What Are Data Views? Data views in Pylar are SQL queries that define exactly what data AI agents can access. Think of views as a **window** into your data—agents can only see and query through these windows, never gaining direct access to your raw database tables. ```mermaid theme={null} graph LR DS[Data Sources
Snowflake, BigQuery, etc.] VIEW[SQL View
Governed Query] AGENT[AI Agent] DS -->|Raw Data| VIEW VIEW -->|Scoped Data| AGENT style VIEW fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Views vs Raw Database Access ### The Problem with Direct Access Giving AI agents direct database access means: * ❌ Agents can query any table or column * ❌ No control over what data is exposed * ❌ Security risks from accidental or malicious queries * ❌ Difficult to audit and monitor access * ❌ Compliance challenges ### The Pylar Solution: Views With Pylar views: * ✅ **Complete Isolation**: Agents only access data through your defined views * ✅ **Fine-Grained Control**: You decide exactly what data is available * ✅ **Security by Design**: Views are the only access level—no exceptions * ✅ **Full Audit Trail**: Every query goes through your views and is logged * ✅ **Compliance Ready**: Easy to demonstrate data governance Views are the **only** access level AI agents get. They never have direct database access, ensuring complete security and governance. ## How Views Work in Pylar ### The View Lifecycle 1. **Create**: Write SQL queries in Pylar's SQL IDE 2. **Test**: Run queries to verify results 3. **Save**: Save queries as views in your project 4. **Build Tools**: Create MCP tools on top of views 5. **Publish**: Make tools available to AI agents 6. **Monitor**: Use Evals to see how agents interact with views ### View Organization Views are organized within **projects**: * Each project contains multiple views * Views can reference different data sources * You can create views that join across multiple databases * Projects help organize views by use case or team Projects provide a logical way to group related views and tools together. For example, you might have a "Customer Analytics" project with multiple views for different analysis needs. ## Key Concepts ### Views Are Queries A view is essentially a saved SQL query: * Write standard SQL queries * Use any SQL features your database supports * Join tables, filter data, aggregate results * Cross-database joins are supported ### Views Are Secure * Agents can only query through views * You control what columns and rows are accessible * Sensitive data can be excluded or masked * Row-level security can be implemented ### Views Are Flexible * Multiple MCP tools can be created on a single view * Each tool can have different parameters or purposes * Views can be updated anytime * Changes reflect automatically in all connected agents ## Benefits of Using Views ### For Security Teams * **Complete Control**: Define exactly what data agents can access * **No Raw Access**: Eliminate the risk of direct database queries * **Audit Trail**: Every query is logged and traceable * **Compliance**: Meet regulatory requirements with clear data governance ### For Data Teams * **SQL IDE**: Built-in editor makes view creation easy * **Cross-Database Joins**: Combine data from multiple sources * **Testing**: Verify queries before saving as views * **Organization**: Keep views organized in projects ### For Developers * **No Custom Code**: Define views with SQL, no integration code needed * **Standard SQL**: Use familiar SQL syntax * **Fast Iteration**: Update views and see changes immediately * **Multiple Tools**: Create different tools on the same view ## Next Steps Ready to create your first view? * [SQL IDE Basics](/learn/creating-data-views/sql-ide-basics) - Learn how to use the SQL IDE * [Writing Your First View](/learn/creating-data-views/writing-your-first-view) - Step-by-step guide to creating a view * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Join data across multiple sources * [View Best Practices](/learn/creating-data-views/view-best-practices) - Optimize your views Learn how to use the SQL IDE to create your first view # SQL IDE Basics Source: https://docs.pylar.ai/learn/creating-data-views/sql-ide-basics Learn how to use Pylar's built-in SQL IDE to query data sources, work with dataframes, and create views ## Introduction to the SQL IDE When you create a new view in Pylar, the **SQL IDE** (Integrated Development Environment) appears in the center of your screen. This powerful editor provides everything you need to write, test, and refine SQL queries before saving them as views. ## The SQL IDE Interface The SQL IDE is designed for efficiency and ease of use: Pylar SQL IDE interface showing datasource selector, query editor, and results panel ### Key Components * **Datasource Selector**: Dropdown menu to select your data source * **SQL Query Editor**: Main editing area for writing queries * **Run Query Button**: Executes your query and displays results * **Query Results Panel**: Shows query output, row counts, and execution metadata ## Selecting a Data Source Before writing your query, you must select which data source to query. ### Step-by-Step 1. Locate the **"Select Datasource"** dropdown above the SQL IDE 2. Click the dropdown to reveal all available data sources 3. Choose your desired data source: * Connected databases (BigQuery, Snowflake, PostgreSQL, etc.) * **Local Dataframes** (for querying dataframes in your session) 4. If needed, navigate to the specific database, schema, or table within that source The dropdown dynamically shows all active connections. Ensure your database connection is established and active before selecting it. ## Writing Your Query Once you've selected a data source, replace the default query template with your SQL query. ### Basic Query Example ```sql theme={null} SELECT customer_id, customer_name, email, created_at FROM customers WHERE is_active = true ORDER BY created_at DESC; ``` ### Query Editor Features Pylar's SQL IDE includes: * **Syntax Highlighting**: Color-coded SQL keywords and identifiers * **Auto-completion**: Intelligent suggestions for table and column names * **Error Detection**: Visual indicators for syntax errors * **Query Formatting**: Clean, readable code structure ## Running Your Query Execute your query to see results and verify it works correctly. Create view button and run query button in Pylar SQL IDE ### Execution Steps 1. **Review Your Query**: Double-check your SQL for accuracy 2. **Click "Run Query"**: Located in the top right of the center screen 3. **Wait for Execution**: A loader appears in the results section below the IDE 4. **View Results**: Once complete, results appear in the Query Results section The loader indicator shows that Pylar is processing your query. For large datasets, this may take a few moments. ## Understanding Query Results When your query executes successfully, the results panel displays comprehensive information. Query results displayed in Pylar SQL IDE showing data table and execution metadata ### Results Panel Contents * **Data Table**: Tabular view of your query results * Scrollable for large result sets * Column headers for easy reference * Formatted data for readability * **Row Count**: Total number of rows returned by the query * **Last Run Time**: Timestamp showing when the query was executed * **Execution Metadata**: Additional details about query performance The results table is interactive—you can scroll, sort columns, and explore your data directly in the IDE. ## Best Practices ### Query Development * \*\*Start with SELECT \*\*\*: Begin by viewing all columns, then refine to specific columns * **Test Incrementally**: Add filters, joins, and aggregations one step at a time * **Use LIMIT**: When exploring large datasets, use `LIMIT` to speed up testing * **Verify Results**: Always check row counts and sample data before finalizing ### Performance Optimization * **Filter Early**: Apply `WHERE` clauses before joins to reduce data volume * **Select Specific Columns**: Avoid `SELECT *` in production views when possible * **Monitor Execution Time**: Pay attention to query performance during testing ## Next Steps Now that you understand the SQL IDE basics: * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Learn how to query and join data across multiple sources * [Writing Your First View](/learn/creating-data-views/writing-your-first-view) - Create a comprehensive view joining data across multiple sources * [View Best Practices](/learn/creating-data-views/view-best-practices) - Optimize your views for performance and maintainability Learn how to join data across multiple databases and dataframes # Writing Your First View Source: https://docs.pylar.ai/learn/creating-data-views/writing-your-first-view Step-by-step guide to creating your first data view in Pylar, including cross-database joins from Snowflake, HubSpot, and Salesforce ## Overview This tutorial walks you through creating your first data view in Pylar. You'll learn how to join data from multiple sources—Snowflake, HubSpot, and Salesforce—into a unified view that an AI agent can use to answer complex business questions. ## Use Case: Customer 360 View We'll create a **Customer 360 View** that combines: * **Customer transaction data** from Snowflake * **Marketing engagement data** from HubSpot * **Sales pipeline data** from Salesforce This unified view will enable an AI agent to answer questions like: * "What's the total revenue for customers who engaged with our Q4 campaign?" * "Show me customers who have deals in Salesforce but haven't made a purchase yet" * "Which HubSpot contacts have the highest lifetime value in Snowflake?" ## Prerequisites Before you begin, ensure you have: * ✅ A Pylar account with access to create views * ✅ Active connections to: * Snowflake (with transaction data) * HubSpot (with marketing engagement data) * Salesforce (with sales pipeline data) * ✅ A project created in Pylar to organize your views If you haven't connected your data sources yet, check out the [Making Connections](/learn/making-connections/overview) section to set them up first. ## Step 1: Create a New View 1. Navigate to your project in the Pylar dashboard 2. Click **"Create View"** or **"New View"** 3. The SQL IDE will appear in the center of your screen ## Step 2: Understand the Data Structure Before writing your query, understand what data you're working with: ### Snowflake Data (Transaction Database) * **Table**: `transactions` * **Key Columns**: `customer_id`, `transaction_date`, `amount`, `product_id` ### HubSpot Data (Marketing Platform) * **Table**: `contacts` * **Key Columns**: `contact_id`, `email`, `campaign_engagement`, `last_contacted` ### Salesforce Data (CRM) * **Table**: `opportunities` * **Key Columns**: `account_id`, `opportunity_name`, `stage`, `amount`, `close_date` The exact table and column names may vary based on your specific setup. Adjust the query to match your actual schema. ## Step 3: Write Your Cross-Database Query Now we'll create a query that joins data from all three sources. Here's the complete view: ```sql theme={null} -- Customer 360 View -- Combines transaction data, marketing engagement, and sales pipeline -- for a complete customer picture SELECT -- Customer identifiers COALESCE(sf.customer_id, hs.contact_id, sfdc.account_id) AS unified_customer_id, -- Transaction data from Snowflake sf.total_revenue, sf.transaction_count, sf.first_transaction_date, sf.last_transaction_date, sf.avg_transaction_value, -- Marketing data from HubSpot hs.email, hs.campaign_engagement, hs.last_contacted_date, hs.marketing_score, -- Sales data from Salesforce sfdc.active_opportunities, sfdc.total_pipeline_value, sfdc.largest_deal_amount, sfdc.deal_stage, sfdc.expected_close_date, -- Calculated fields CASE WHEN sf.total_revenue > 0 AND sfdc.total_pipeline_value > 0 THEN 'Customer with Revenue & Pipeline' WHEN sf.total_revenue > 0 THEN 'Existing Customer' WHEN sfdc.total_pipeline_value > 0 THEN 'Prospect with Pipeline' ELSE 'Lead' END AS customer_segment FROM ( -- Aggregate transaction data from Snowflake SELECT customer_id, SUM(amount) AS total_revenue, COUNT(*) AS transaction_count, MIN(transaction_date) AS first_transaction_date, MAX(transaction_date) AS last_transaction_date, AVG(amount) AS avg_transaction_value FROM snowflake.production.transactions WHERE transaction_date >= DATEADD(month, -12, CURRENT_DATE()) GROUP BY customer_id ) sf FULL OUTER JOIN ( -- Marketing engagement from HubSpot SELECT contact_id, email, campaign_engagement, last_contacted AS last_contacted_date, hs_analytics_source_data_1 AS marketing_score FROM hubspot.marketing.contacts WHERE is_active = true ) hs ON sf.customer_id = hs.contact_id FULL OUTER JOIN ( -- Sales pipeline from Salesforce SELECT account_id, COUNT(CASE WHEN stage NOT IN ('Closed Won', 'Closed Lost') THEN 1 END) AS active_opportunities, SUM(CASE WHEN stage NOT IN ('Closed Won', 'Closed Lost') THEN amount ELSE 0 END) AS total_pipeline_value, MAX(CASE WHEN stage NOT IN ('Closed Won', 'Closed Lost') THEN amount END) AS largest_deal_amount, MAX(CASE WHEN stage NOT IN ('Closed Won', 'Closed Lost') THEN stage END) AS deal_stage, MIN(CASE WHEN stage NOT IN ('Closed Won', 'Closed Lost') THEN close_date END) AS expected_close_date FROM salesforce.sales.opportunities WHERE is_deleted = false GROUP BY account_id ) sfdc ON COALESCE(sf.customer_id, hs.contact_id) = sfdc.account_id WHERE -- Filter for active customers or prospects (sf.total_revenue > 0 OR sfdc.total_pipeline_value > 0 OR hs.marketing_score > 50) ORDER BY sf.total_revenue DESC NULLS LAST, sfdc.total_pipeline_value DESC NULLS LAST; ``` ## Step 4: Understanding the Query Let's break down what this query does: ### Data Aggregation **Snowflake Subquery**: * Aggregates transaction data by customer * Calculates total revenue, transaction count, and dates * Filters to last 12 months of data **HubSpot Subquery**: * Retrieves marketing engagement data * Includes email and campaign interaction history * Filters to active contacts only **Salesforce Subquery**: * Aggregates sales pipeline data * Calculates active opportunities and pipeline value * Excludes closed deals from pipeline calculations ### Cross-Database Joins The query uses `FULL OUTER JOIN` to: * Include customers who have transactions but no marketing data * Include prospects who have sales pipeline but no transactions yet * Include contacts who have marketing engagement but no sales activity * Combine all three sources into a unified customer view ### Customer Segmentation The `CASE` statement creates a customer segment based on: * Whether they have revenue (Snowflake) * Whether they have active pipeline (Salesforce) * Combining both signals for a complete picture Using `FULL OUTER JOIN` ensures you capture all customers, prospects, and leads regardless of which systems they appear in. This is perfect for a comprehensive 360-degree view. ## Step 5: Select Your Primary Data Source 1. In the SQL IDE, locate the **"Select Datasource"** dropdown 2. Since we're joining across multiple sources, select your **primary source** (Snowflake in this example) 3. The query will execute using that connection, but can reference other sources Pylar handles cross-database joins automatically. You can reference tables from different sources using the format: `datasource.schema.table`. ## Step 6: Run and Test Your Query 1. Review your query in the SQL IDE 2. Click **"Run Query"** in the top right 3. Wait for the query to execute (you'll see a loader) 4. Review the results: * Check the row count * Verify data looks correct * Ensure joins worked as expected * Review the customer segments If your query runs successfully, you'll see a table with all the combined customer data. The row count should reflect customers from all three sources. ## Step 7: Save Your View Once you've verified the query works: 1. Click **"Save View"** or **"Save"** 2. Enter a descriptive name: `customer_360_view` 3. Add a description: ``` Unified customer view combining transaction data (Snowflake), marketing engagement (HubSpot), and sales pipeline (Salesforce). Enables 360-degree customer analysis for AI agents. ``` 4. Click **"Save"** to finalize ## How an AI Agent Uses This View Once you create MCP tools on this view and publish them, an AI agent can use it to answer complex questions: ### Example Agent Interactions **Question**: *"Show me customers who have engaged with our Q4 campaign but haven't made a purchase yet"* **Agent Process**: 1. Agent queries the view with filters: * `campaign_engagement` contains "Q4" * `total_revenue` is NULL or 0 * `customer_segment` = "Prospect with Pipeline" or "Lead" 2. Returns customers who are marketing-qualified but haven't converted 3. Can provide actionable insights for sales follow-up **Question**: *"What's the average revenue for customers with active opportunities in Salesforce?"* **Agent Process**: 1. Agent queries the view filtering for: * `active_opportunities` > 0 * `total_revenue` is not NULL 2. Calculates average revenue from the results 3. Provides both the average and context about pipeline value **Question**: *"Find customers with high lifetime value who haven't been contacted recently"* **Agent Process**: 1. Agent queries the view with: * `total_revenue` > threshold (high value) * `last_contacted_date` is old or NULL 2. Identifies high-value customers needing re-engagement 3. Can suggest next steps for marketing team ### Why This Works The unified view enables the agent to: * **Answer Complex Questions**: Questions requiring data from multiple sources can be answered in a single query * **Understand Context**: Customer segments provide context for better responses * **Make Connections**: The agent can see relationships between transactions, marketing, and sales * **Provide Insights**: Combined data enables more sophisticated analysis This view becomes a single source of truth for customer data. The AI agent doesn't need to know about Snowflake, HubSpot, or Salesforce—it just queries this unified view. ## Next Steps Now that you've created your first view: 1. **Create MCP Tools**: Build tools on this view that agents can use * [Building MCP Tools Overview](/learn/building-mcp-tools/overview) * [Creating Tools with AI](/learn/building-mcp-tools/creating-tools-with-ai) 2. **Test Your View**: Use Evals to see how agents interact with it * [Evals Overview](/learn/evals/overview) 3. **Optimize**: Refine based on agent usage patterns * [View Best Practices](/learn/creating-data-views/view-best-practices) ## Common Issues and Solutions ### Issue: Query Fails with "Table Not Found" **Solution**: Verify your table references are correct: * Check datasource names match your connections * Verify schema and table names are exact * Ensure you have access permissions ### Issue: Join Returns Unexpected Results **Solution**: * Verify join keys match across sources * Check for NULL values that might affect joins * Use `COALESCE` to handle mismatched identifiers * Test joins incrementally (start with two sources) ### Issue: Query Runs Slowly **Solution**: * Add filters to reduce data volume early * Use aggregated subqueries (as in our example) * Limit date ranges to recent data * Consider materializing frequently-used views ## Best Practices Recap * **Use Descriptive Names**: `customer_360_view` is clear and specific * **Add Comments**: Document your query logic * **Test Incrementally**: Start with one source, then add joins * **Aggregate When Possible**: Pre-calculate metrics in subqueries * **Handle NULLs**: Use `COALESCE` for unified identifiers * **Filter Early**: Apply WHERE clauses in subqueries Next: Create MCP tools so agents can query this view # Analyzing Errors Source: https://docs.pylar.ai/learn/evals/analyzing-errors Learn how to identify, understand, and fix errors in your MCP tools using Evals ## Overview The Error Analysis section of Evals helps you understand what's going wrong with your tools. It shows error codes, frequencies, and patterns that help you diagnose and fix issues. ## Accessing Error Analysis In the Evaluation Dashboard: 1. Select the tool you want to analyze (using filters) 2. Scroll to the **Error Analysis** section 3. Review error codes and frequencies ## Error Explorer The Error Explorer lists all error codes that occurred and how often each one happened. ### Understanding Error Codes Error codes indicate different types of failures: * **400**: Bad Request - Invalid parameters or query syntax * **404**: Not Found - Resource doesn't exist * **500**: Internal Server Error - Server-side issues * **Timeout**: Query execution exceeded time limit * **Permission**: Access denied or insufficient permissions ### Example Error Explorer ``` Error Code Frequency 400 3 500 1 Timeout 2 ``` This shows: * Error code 400 occurred 3 times * Error code 500 occurred 1 time * Timeout errors occurred 2 times The Error Explorer shows the most common errors first. Focus on fixing high-frequency errors first, as they have the biggest impact. ## Understanding Error Types ### Error Code 400: Bad Request **What it means**: The request was invalid. **Common causes**: * Invalid parameter values * SQL syntax errors in query * Parameter type mismatches * Missing required parameters **How to fix**: 1. Check parameter definitions match query placeholders 2. Verify parameter types are correct 3. Test with valid parameter values 4. Review SQL query syntax ### Error Code 500: Internal Server Error **What it means**: Server-side error occurred. **Common causes**: * Database connection issues * Query execution failures * View definition problems * Data type mismatches **How to fix**: 1. Verify view queries are correct 2. Check database connections are active 3. Test queries manually in SQL IDE 4. Review error messages in raw logs ### Timeout Errors **What it means**: Query took too long to execute. **Common causes**: * Large result sets * Complex joins * Missing indexes * Inefficient queries **How to fix**: 1. Add LIMIT to restrict result size 2. Optimize query performance 3. Add indexes to source views 4. Refine WHERE conditions ### Permission Errors **What it means**: Access denied. **Common causes**: * Insufficient database permissions * View access restrictions * Token authentication issues **How to fix**: 1. Verify database connection permissions 2. Check view access controls 3. Regenerate authentication tokens if needed ## Error Frequency Analysis ### High-Frequency Errors Errors that occur frequently need immediate attention: * **High impact**: Affect many agent interactions * **User experience**: Cause frustration for agents * **Priority**: Fix these first **Example**: If error 400 occurs 50 times out of 100 calls, that's a 50% error rate—critical issue. ### Low-Frequency Errors Errors that occur occasionally: * **Lower priority**: But still worth fixing * **Edge cases**: May indicate boundary conditions * **Monitor**: Track to see if frequency increases **Example**: If error 500 occurs 2 times out of 1000 calls, investigate but lower priority. ### Error Patterns Look for patterns in errors: * **Time-based**: Do errors occur at specific times? * **Parameter-based**: Do certain parameter values cause errors? * **Tool-based**: Do errors affect specific tools more? Use the time-series graphs to see when errors spike. This can help identify patterns like specific times of day, after deployments, or related to usage volume. ## Using Raw Logs for Error Analysis Raw logs provide detailed error information: 1. Scroll to **Raw Logs** at the bottom of the dashboard 2. Filter for errors (look for non-empty error messages) 3. Review error messages for each failed invocation 4. Identify common patterns ### What to Look For In raw logs, check: * **Error messages**: Detailed descriptions of what went wrong * **Query executed**: See the exact query that failed * **Parameters used**: What values caused the error * **Timestamp**: When the error occurred Error messages in raw logs are your best source of information for understanding what went wrong. Always review them when investigating errors. ## Fixing Common Errors ### Fix 1: Parameter Mismatch **Error**: Parameter placeholder doesn't match parameter name **Solution**: ```sql theme={null} -- Wrong WHERE event_type = '{event_type_param}' -- Correct (matches parameter name) WHERE event_type = '{event_type}' ``` ### Fix 2: SQL Syntax Error **Error**: Invalid SQL in query **Solution**: 1. Test query manually in SQL IDE 2. Replace placeholders with actual values 3. Fix syntax errors 4. Update tool query ### Fix 3: Type Mismatch **Error**: Parameter type doesn't match query expectations **Solution**: 1. Check parameter type definition 2. Ensure query handles type correctly 3. Use CAST if needed for type conversion ### Fix 4: Timeout **Error**: Query execution timeout **Solution**: ```sql theme={null} -- Add LIMIT to reduce result size SELECT * FROM view_name WHERE conditions ORDER BY column LIMIT 100 ``` ## Monitoring Error Improvements After fixing errors: 1. **Monitor Evals**: Check if error rates decrease 2. **Verify Fixes**: Confirm specific error codes disappear 3. **Track Trends**: Watch graphs to see improvement 4. **Iterate**: Continue improving based on new errors After fixing errors, monitor Evals for a few days to confirm the fixes work and no new errors appear. ## Best Practices ### Regular Monitoring * ✅ Check Evals regularly (daily or weekly) * ✅ Set alerts for high error rates * ✅ Review error trends over time * ✅ Investigate spikes immediately ### Error Prioritization 1. **High-frequency errors**: Fix first (biggest impact) 2. **Critical errors**: Address quickly (data loss, security) 3. **Low-frequency errors**: Fix when convenient 4. **Edge cases**: Document and monitor ### Documentation * Document common errors and fixes * Share learnings with team * Update tool documentation based on errors * Create runbooks for frequent issues ## Next Steps Now that you understand error analysis: * [Understanding Query Shapes](/learn/evals/understanding-query-shapes) - Learn about query patterns * [Understanding Query Logs](/learn/evals/understanding-query-logs) - Dive into detailed logs * [Improving Tools with Evals](/learn/evals/improving-tools-with-evals) - Use error insights to improve tools Learn how to analyze query patterns from Evals # Evals Dashboard Source: https://docs.pylar.ai/learn/evals/evals-dashboard Navigate the Evals dashboard and understand evaluation metrics, visual insights, and filters ## Opening the Dashboard To access the Evaluation Dashboard: 1. Navigate to your project in Pylar 2. Click the **"Eval"** button in the top-right corner of the screen 3. The Evaluation Dashboard opens You'll see a comprehensive view of your MCP tool performance metrics. ## Dashboard Overview The Evaluation Dashboard is organized into several sections: * **Filters**: Select which MCP tool to review * **Summary Metrics**: High-level performance indicators * **Visual Insights**: Time-series graphs showing trends * **Error Analysis**: Detailed error breakdown * **Raw Logs**: Complete records of all tool calls ## Filters ### Selecting a Tool At the top of the dashboard, you'll find filters to select which MCP tool you want to review. **How to use**: 1. Click the filter dropdown 2. Select the MCP tool you want to analyze 3. The dashboard updates to show metrics for that tool only Use filters to focus on specific tools. This is especially useful when you have multiple tools and want to analyze them individually. ## Evaluation Metrics The dashboard displays key metrics that summarize tool performance: ### Total Count **What it is**: The total number of times the selected MCP tool was invoked. **What it tells you**: Overall usage volume—how frequently agents are using this tool. Total Count includes both successful and failed invocations. It's the baseline for all other metrics. ### Success Count **What it is**: How many invocations returned a valid result. **What it tells you**: The absolute number of successful tool calls. Higher is better. ### Error Count **What it is**: How many invocations failed to return a result. **What it tells you**: The absolute number of failed tool calls. Lower is better. ### Success Rate **Calculation**: ``` Success Rate = (Success Count ÷ Total Count) × 100 ``` **What it is**: Percentage of successful tool invocations. **What it tells you**: * High success rate (90%+) = Tool is working well * Medium success rate (70-90%) = Some issues, needs attention * Low success rate (less than 70%) = Significant problems, needs immediate attention Aim for success rates above 90%. If your success rate is below this threshold, investigate errors to understand what's going wrong. ### Error Rate **Calculation**: ``` Error Rate = (Error Count ÷ Total Count) × 100 ``` **What it is**: Percentage of failed tool invocations. **What it tells you**: * Low error rate (less than 10%) = Tool is reliable * Medium error rate (10-30%) = Some reliability issues * High error rate (greater than 30%) = Major problems, needs fixing High error rates indicate problems that are affecting agent performance. Address these issues promptly to improve agent experience. ## Visual Insights The dashboard includes time-series graphs that show how metrics change over time. ### Calls/Success/Errors Graph **What it shows**: A time-series plot displaying: * **Total Calls**: How many times the tool was invoked over time * **Successes**: Successful invocations over time * **Errors**: Failed invocations over time **What it tells you**: * Usage trends (increasing/decreasing usage) * Performance trends (improving/declining success rates) * Error patterns (when errors occur most frequently) **How to use it**: * Look for trends: Are errors increasing or decreasing? * Identify patterns: Do errors spike at certain times? * Compare periods: How does current performance compare to past performance? ### Success/Error Rate (%) Graph **What it shows**: Displays success and error percentages as a time-series trend. **What it tells you**: * Performance stability over time * Whether your tool is improving or degrading * Correlation between changes and performance **How to use it**: * Monitor trends: Is success rate improving? * Spot anomalies: Are there sudden drops in performance? * Track improvements: Did your changes improve performance? Use these graphs to understand not just current performance, but also trends and patterns. This helps you identify issues before they become critical. ## Interpreting the Metrics ### Healthy Tool Performance A healthy tool shows: * ✅ High success rate (90%+) * ✅ Low error rate (less than 10%) * ✅ Stable or improving trends over time * ✅ Consistent performance across time periods ### Tool Needs Attention A tool that needs attention shows: * ⚠️ Success rate below 90% * ⚠️ Error rate above 10% * ⚠️ Declining trends in graphs * ⚠️ Inconsistent performance ### Tool Needs Immediate Fix A tool that needs immediate attention shows: * ❌ Success rate below 70% * ❌ Error rate above 30% * ❌ Sharp drops in performance graphs * ❌ Frequent errors in logs ## Using Filters Effectively ### Analyzing Individual Tools 1. Select a specific tool from the filter 2. Review its metrics 3. Check if it meets performance thresholds 4. Investigate if it needs improvement ### Comparing Tools 1. Select different tools one at a time 2. Compare their metrics 3. Identify which tools perform best 4. Learn from high-performing tools to improve others ### Time Period Analysis Use time filters (if available) to: * Compare different time periods * See impact of tool changes * Identify seasonal patterns * Track improvement over time ## Next Steps Now that you understand the dashboard: * [Analyzing Errors](/learn/evals/analyzing-errors) - Dive deeper into error patterns * [Understanding Query Shapes](/learn/evals/understanding-query-shapes) - Learn about query patterns * [Raw Logs](/learn/evals/understanding-query-logs) - Explore detailed execution logs Learn how to identify and fix errors in your tools # Overview Source: https://docs.pylar.ai/learn/evals/overview Introduction to Evals in Pylar - monitor and analyze how AI agents interact with your MCP tools ## What Are Evals? Evals in Pylar provide comprehensive insights into how AI agents interact with your MCP tools. They give you visibility into tool usage, performance, errors, and query patterns—helping you optimize your tools and views for better agent performance. ```mermaid theme={null} graph LR AGENTS[AI Agents] TOOLS[MCP Tools] EVALS[Evals Dashboard] INSIGHTS[Insights
Success Rates, Errors,
Query Shapes, Logs] OPTIMIZE[Optimize] AGENTS --> TOOLS TOOLS --> EVALS EVALS --> INSIGHTS INSIGHTS --> OPTIMIZE OPTIMIZE --> TOOLS style EVALS fill:#FF4017,stroke:#CC3300,color:#fff style OPTIMIZE fill:#FF4017,stroke:#CC3300,color:#fff ``` ## Why Use Evals? Evals help you: * ✅ **Monitor Performance**: Track success rates and error patterns * ✅ **Identify Issues**: Find tools that fail frequently or have problems * ✅ **Understand Usage**: See how agents are using your tools * ✅ **Optimize Queries**: Identify slow or inefficient queries * ✅ **Improve Tools**: Refine tools based on real agent behavior * ✅ **Track Trends**: See how usage changes over time Evals are your window into production agent behavior. They show you exactly what's happening when agents use your tools. ## Accessing Evals To open the Evaluation Dashboard: 1. Navigate to your project in Pylar 2. Click the **"Eval"** button in the top-right corner of the screen 3. The Evaluation Dashboard opens The dashboard provides a comprehensive view of all your MCP tool performance metrics. ## What You'll See The Evaluation Dashboard shows: ### Summary Metrics * **Total Count**: How many times tools were invoked * **Success Count**: Successful invocations * **Error Count**: Failed invocations * **Success Rate**: Percentage of successful calls * **Error Rate**: Percentage of failed calls ### Visual Insights * **Time-Series Graphs**: See how usage, successes, and errors change over time * **Trend Analysis**: Understand patterns in tool performance ### Error Analysis * **Error Explorer**: See what errors occurred and how often * **Query Shape**: Understand patterns in query types ### Raw Logs * **Detailed Records**: Every tool call with full context * **Query Details**: See exactly what queries were executed * **Error Messages**: Understand why failures occurred ## Key Concepts ### Success vs. Error * **Success**: Tool invocation returned a valid result * **Error**: Tool invocation failed to return a result ### Success Rate ``` Success Rate = (Success Count ÷ Total Count) × 100 ``` A higher success rate indicates better tool performance. ### Error Rate ``` Error Rate = (Error Count ÷ Total Count) × 100 ``` A lower error rate is better. High error rates indicate problems that need attention. ## Using Evals to Improve ### Iterative Improvement Process 1. **Monitor**: Use Evals to see how tools perform 2. **Identify Issues**: Find errors, slow queries, or patterns 3. **Refine**: Update tools or views based on insights 4. **Verify**: Check Evals again to confirm improvements 5. **Repeat**: Continuously improve based on real usage Use Evals regularly to catch issues early and continuously improve your tools. Don't wait for problems to be reported—monitor proactively. ## Next Steps Ready to explore your Evals? * [Evals Dashboard](/learn/evals/evals-dashboard) - Navigate the dashboard and understand metrics * [Analyzing Errors](/learn/evals/analyzing-errors) - Understand error patterns and how to fix them * [Understanding Query Shapes](/learn/evals/understanding-query-shapes) - Learn about query patterns * [Improving Tools with Evals](/learn/evals/improving-tools-with-evals) - Use insights to optimize your tools Learn how to navigate and understand the Evals dashboard # Understanding Query Logs Source: https://docs.pylar.ai/learn/evals/understanding-query-logs Learn how to read and analyze raw query logs from Evals to understand tool execution details ## Overview Raw Logs provide detailed records of every MCP tool call. They show you exactly what happened—which tools were called, what queries were executed, whether they succeeded, and any errors that occurred. ## Accessing Raw Logs In the Evaluation Dashboard: 1. Scroll to the bottom of the page 2. Find the **Raw Logs** section 3. Review the detailed records You can scroll through the logs to see all tool invocations. ## Log Structure Each log entry contains: * **Tool Name**: Which MCP tool was invoked * **Query Executed**: The actual SQL query that ran * **Invocation Status**: Success or failure * **Timestamp**: When the invocation occurred * **Error Message**: Error details (empty when successful) ## Understanding Log Fields ### Tool Name **What it shows**: The name of the MCP tool that was invoked. **Example**: `fetch_engagement_scores_by_event_type` **What it tells you**: Which tool agents are using most frequently. ### Query Executed **What it shows**: The actual SQL query that was executed, with parameter values injected. **Example**: ```sql theme={null} SELECT engagement_score FROM table0 WHERE event_type LIKE '%login%' ORDER BY engagement_score DESC ``` **What it tells you**: * Exact query that ran * Parameter values that were used * How parameters were injected into the query The Query Executed field shows the query after parameter injection. This is the actual query that ran against your database. ### Invocation Status **What it shows**: Whether the tool call succeeded or failed. **Values**: * **Success**: Tool executed successfully * **Error**: Tool execution failed **What it tells you**: Overall success/failure for each invocation. ### Timestamp **What it shows**: When the tool invocation occurred. **Example**: `2024-11-05 14:23:45` **What it tells you**: * When tools are being used * Time patterns in usage * Correlation with errors or performance issues ### Error Message **What it shows**: Detailed error information if the invocation failed. Empty when successful. **Example**: `Error: Parameter 'event_type' not found in query` **What it tells you**: * Why the invocation failed * What needs to be fixed * Common error patterns Error messages are your best source of information for understanding failures. Always review them when investigating issues. ## Analyzing Logs ### Finding Successful Invocations Look for entries with: * Status: **Success** * Empty error message field * Valid query results These show what's working correctly. ### Finding Failed Invocations Look for entries with: * Status: **Error** * Non-empty error message * Failed query execution These show what needs to be fixed. ### Pattern Analysis Review logs to identify patterns: * **Time Patterns**: Do errors occur at specific times? * **Query Patterns**: Do certain queries fail more often? * **Parameter Patterns**: Do certain parameter values cause errors? * **Tool Patterns**: Do specific tools fail more than others? ## Using Logs for Debugging ### Step 1: Identify the Problem 1. Find failed invocations in logs 2. Review error messages 3. Note which tool failed 4. Check what parameters were used ### Step 2: Understand the Context 1. Look at the query that was executed 2. Review parameter values 3. Check timestamp (when did it fail?) 4. Compare with successful invocations ### Step 3: Reproduce the Issue 1. Copy the query from the log 2. Test it manually in SQL IDE 3. Use the same parameter values 4. See if you can reproduce the error ### Step 4: Fix the Issue 1. Identify the root cause 2. Fix the tool or query 3. Test the fix 4. Monitor logs to confirm it's resolved ## Common Log Patterns ### Pattern 1: Parameter Mismatch **Log Entry**: ``` Tool: fetch_engagement_scores_by_event_type Query: SELECT engagement_score FROM table0 WHERE event_type = '{event_type_param}' Status: Error Error: Parameter 'event_type_param' not found ``` **Issue**: Parameter placeholder doesn't match parameter name **Fix**: Update query to use correct parameter name ### Pattern 2: SQL Syntax Error **Log Entry**: ``` Tool: fetch_engagement_scores_by_event_type Query: SELECT engagement_score FROM table0 WHERE event_type LIKE '%login%' ORDER BY Status: Error Error: SQL syntax error near 'ORDER BY' ``` **Issue**: Incomplete or invalid SQL **Fix**: Complete the SQL query properly ### Pattern 3: Timeout **Log Entry**: ``` Tool: fetch_engagement_scores_by_event_type Query: SELECT * FROM table0 WHERE event_type LIKE '%login%' Status: Error Error: Query execution timeout ``` **Issue**: Query takes too long **Fix**: Add LIMIT, optimize query, or refine filters ## Best Practices ### Regular Review * ✅ Review logs regularly (weekly or daily) * ✅ Focus on errors first * ✅ Look for patterns over time * ✅ Track improvements ### Log Analysis * Use filters to find specific issues * Sort by timestamp to see recent activity * Filter by status to focus on errors * Search for specific error messages ### Documentation * Document common errors and fixes * Note patterns you discover * Share findings with team * Create runbooks for frequent issues ## Navigating Large Logs ### Scrolling * Scroll down to see older entries * New entries appear at the top * Use browser find/search to locate specific entries ### Filtering If filters are available: * Filter by tool name * Filter by status (success/error) * Filter by date range * Filter by error message ### Searching Use browser search (Cmd+F or Ctrl+F) to: * Find specific tool names * Search for error messages * Locate specific timestamps * Find parameter values For large log files, use browser search to quickly find specific entries. This is much faster than scrolling through everything. ## Next Steps Now that you understand query logs: * [Analyzing Errors](/learn/evals/analyzing-errors) - Use logs to identify and fix errors * [Improving Tools with Evals](/learn/evals/improving-tools-with-evals) - Use log insights to optimize tools * [Evals Best Practices](/learn/evals/evals-best-practices) - Learn best practices for using Evals Use log insights to optimize your MCP tools # Understanding Query Shapes Source: https://docs.pylar.ai/learn/evals/understanding-query-shapes Learn how to analyze query patterns and shapes from Evals to understand how agents use your tools ## What Are Query Shapes? Query shapes represent patterns in the types of queries executed by your MCP tools. They show you how agents are interacting with your data—what filters they use, what parameters they pass, and what patterns emerge. ## Why Query Shapes Matter Understanding query shapes helps you: * ✅ **Optimize Queries**: See what queries are most common * ✅ **Improve Tools**: Understand how agents actually use your tools * ✅ **Identify Patterns**: Find common query patterns * ✅ **Optimize Performance**: Focus optimization on frequent patterns * ✅ **Enhance Tools**: Add tools for common query patterns Query shapes reveal the real-world usage patterns of your tools. They show you what agents actually need, not just what you thought they would need. ## Accessing Query Shapes In the Evaluation Dashboard: 1. Select the tool you want to analyze 2. Scroll to the **Error Analysis** section 3. Find the **Query Shape** section 4. Review the query patterns displayed ## Understanding Query Patterns ### Common Query Patterns Query shapes show patterns like: * **Simple Filters**: Queries with single WHERE conditions * **Date Ranges**: Queries filtering by date ranges * **Multiple Filters**: Queries with multiple WHERE conditions * **Aggregations**: Queries with GROUP BY or aggregations * **Sorting Patterns**: How results are ordered ### Example Query Shapes **Pattern 1: Single Filter** ``` Most common: WHERE event_type = '{value}' Frequency: 45% of queries ``` **Pattern 2: Date Range** ``` Most common: WHERE date >= '{start}' AND date <= '{end}' Frequency: 30% of queries ``` **Pattern 3: Multiple Filters** ``` Most common: WHERE type = '{type}' AND status = '{status}' Frequency: 15% of queries ``` ## Analyzing Query Shapes ### What to Look For 1. **Most Common Patterns**: What queries are executed most frequently? 2. **Parameter Usage**: Which parameters are used most often? 3. **Filter Combinations**: What combinations of filters appear? 4. **Sort Patterns**: How are results typically ordered? ### Identifying Optimization Opportunities High-frequency patterns indicate optimization opportunities: * **Add Indexes**: If certain filters are common, ensure indexes exist * **Create Specialized Tools**: If a pattern is frequent, consider a dedicated tool * **Optimize Queries**: Focus performance improvements on common patterns * **Simplify Tools**: If agents always use specific parameters, make them defaults If a query pattern appears frequently (30%+ of queries), consider creating a dedicated tool optimized for that pattern. This can improve performance and agent experience. ## Using Query Shapes to Improve Tools ### Scenario 1: Common Filter Pattern **Observation**: 60% of queries filter by `event_type` **Action**: * Ensure `event_type` filtering is optimized * Consider making `event_type` a required parameter * Add tool description emphasizing event\_type filtering ### Scenario 2: Date Range Pattern **Observation**: Many queries use date ranges **Action**: * Create a dedicated tool for date range queries * Add date range parameters to existing tools * Optimize date filtering in queries ### Scenario 3: Multiple Parameter Combinations **Observation**: Agents frequently combine specific parameters **Action**: * Create tools optimized for common combinations * Add default values for frequently used parameters * Update tool descriptions to highlight common use cases ## Query Shape Examples ### Example 1: Engagement Score Queries **Common Pattern**: ```sql theme={null} SELECT engagement_score FROM table0 WHERE event_type LIKE '%{event_type}%' ORDER BY engagement_score DESC ``` **Insights**: * Agents always filter by event\_type * Always sorted by engagement\_score descending * Uses LIKE pattern matching **Optimization**: * Make event\_type a required parameter * Consider exact match instead of LIKE if pattern is consistent * Add LIMIT if results are always large ### Example 2: Date Range Queries **Common Pattern**: ```sql theme={null} SELECT * FROM transactions WHERE date >= '{start_date}' AND date <= '{end_date}' ORDER BY date DESC ``` **Insights**: * Always uses date range filtering * Always sorted by date * Returns all columns **Optimization**: * Create dedicated date range tool * Add default date range (e.g., last 30 days) * Consider selecting specific columns instead of \* ### Example 3: Multi-Filter Queries **Common Pattern**: ```sql theme={null} SELECT * FROM customers WHERE region = '{region}' AND status = '{status}' AND revenue > {min_revenue} ``` **Insights**: * Always combines region, status, and revenue filters * Revenue threshold is common **Optimization**: * Create tool specifically for this combination * Make min\_revenue optional with default * Add indexes on region, status, revenue columns ## Best Practices ### Regular Review * ✅ Review query shapes weekly * ✅ Look for new patterns emerging * ✅ Identify optimization opportunities * ✅ Track changes over time ### Pattern Documentation * Document common query patterns * Note which patterns are most frequent * Track how patterns change over time * Share insights with team ### Optimization Strategy 1. **Identify** high-frequency patterns (30%+ of queries) 2. **Analyze** if patterns can be optimized 3. **Create** specialized tools for common patterns 4. **Monitor** if optimizations improve performance ## Using Query Shapes with Raw Logs Combine query shapes with raw logs for deeper insights: 1. Identify a pattern from Query Shapes 2. Go to Raw Logs 3. Filter for queries matching that pattern 4. Analyze specific examples 5. Understand how agents use that pattern Query shapes give you the big picture, while raw logs give you the details. Use both together for comprehensive analysis. ## Next Steps Now that you understand query shapes: * [Understanding Query Logs](/learn/evals/understanding-query-logs) - Dive into detailed execution logs * [Improving Tools with Evals](/learn/evals/improving-tools-with-evals) - Use query shape insights to optimize tools * [Improving Views with Evals](/learn/evals/improving-views-with-evals) - Optimize views based on query patterns Learn how to analyze detailed query logs # Connecting BigQuery Source: https://docs.pylar.ai/learn/making-connections/connecting-bigquery Step-by-step guide to connecting your Google Cloud BigQuery data warehouse to Pylar ## Overview Connecting Pylar to BigQuery allows you to access and analyze your data stored in BigQuery directly from Pylar. Your data remains in BigQuery—Pylar indexes it for easier querying and executes queries on your BigQuery infrastructure. ## Prerequisites * ✅ Pylar account with Analyst role or higher * ✅ Google Cloud Project with BigQuery enabled * ✅ Service account with BigQuery access permissions * ✅ Service account JSON key file ## Step 1: Access Connections 1. Navigate to the **"Connections"** tab on the left side of your Pylar interface 2. You'll see different sections for connection types ## Step 2: Find BigQuery 1. In the **"Databases"** section, find and click on the **BigQuery** icon 2. The connection setup screen will open ## Step 3: Configure Connection Fill in the connection details: BigQuery connection setup screen in Pylar ### Name Enter a unique name for this connection to help identify it later. **Naming Rules**: * Lowercase letters only * Numbers and underscores allowed * No spaces or special characters **Example**: `bigquery_production` or `analytics_warehouse` ### Description (Optional) Provide a description of what this connection will be used for. **Example**: "Production BigQuery warehouse for customer analytics" ### Project ID Enter the **Google Cloud Project ID** where your BigQuery dataset is hosted. **How to find it**: * In Google Cloud Console, go to your project * The Project ID is displayed at the top of the dashboard * Format: `my-project-id-12345` ### Service Account JSON Provide the **JSON key file** associated with your service account. **How to create**: 1. In Google Cloud Console, go to **IAM & Admin** → **Service Accounts** 2. Create a new service account or select an existing one 3. Grant necessary BigQuery permissions: * `BigQuery Data Viewer` (to read data) * `BigQuery Job User` (to run queries) 4. Create a JSON key: * Click on the service account * Go to **Keys** tab * Click **Add Key** → **Create new key** * Select **JSON** format * Download the JSON file 5. Copy the contents of the JSON file and paste it into the Pylar field Keep your service account JSON key secure. It provides access to your BigQuery data. Never share it publicly or commit it to version control. ## Step 4: Whitelist Pylar IP Address To ensure seamless connectivity, whitelist Pylar's IP address in your Google Cloud settings: **Pylar IP Address**: `34.122.205.142` **How to whitelist**: 1. In Google Cloud Console, go to **VPC Network** → **Firewall Rules** 2. Create a new firewall rule or modify existing rules 3. Add `34.122.205.142` to the allowed IP addresses 4. Or configure your BigQuery dataset access settings to allow this IP Whitelisting the IP address helps avoid permissions-related issues and ensures stable connectivity. ## Step 5: Submit Connection 1. Review all the information you've entered 2. Click **"Submit"** to establish the connection ## Step 6: Connection Validation Once submitted, Pylar will: 1. Validate the connection details 2. Test the connection to BigQuery 3. Begin indexing your BigQuery data If everything is correct, your BigQuery database will be connected. ## Step 7: Wait for Indexing After the connection is established: * **Data indexing begins**: Pylar indexes your BigQuery data for easier querying * **Processing time**: May take a while depending on data volume * **Notification**: You'll receive an email and in-app notification when indexing is complete Your data remains in BigQuery. Pylar only indexes metadata for autocompletion and query optimization—no data is copied. ## Using Your BigQuery Connection Once connected and indexed: ### Query BigQuery Data 1. Go to the SQL IDE in Pylar 2. Reference your BigQuery connection by name: ```sql theme={null} SELECT * FROM bigquery_production.dataset.table_name; ``` 3. Run queries that execute on your BigQuery infrastructure ### Join with Other Sources You can join BigQuery data with other connected sources: ```sql theme={null} SELECT bq.customer_id, bq.revenue, hs.email, sf.opportunity_value FROM bigquery_production.customers bq JOIN hubspot.contacts hs ON bq.email = hs.email JOIN snowflake.opportunities sf ON bq.customer_id = sf.account_id; ``` ## Troubleshooting ### Issue: Connection test fails **Solutions**: * Verify Project ID is correct * Check service account JSON is valid * Ensure service account has proper permissions * Verify IP address is whitelisted ### Issue: "Permission denied" errors **Solutions**: * Ensure service account has `BigQuery Data Viewer` and `BigQuery Job User` roles * Check dataset-level permissions * Verify IP address `34.122.205.142` is whitelisted * Review Google Cloud IAM settings ### Issue: Data not appearing **Solutions**: * Wait for indexing to complete (check email notification) * Verify dataset and table names are correct * Check service account has access to the datasets * Review BigQuery query logs for errors ### Issue: Slow queries **Solutions**: * This is normal for large datasets—queries run on your BigQuery infrastructure * Optimize your queries (add filters, use LIMIT) * Check BigQuery query performance in Google Cloud Console ## Best Practices ### Service Account Security * ✅ Create a dedicated service account for Pylar * ✅ Grant only necessary permissions (read-only if possible) * ✅ Regularly rotate service account keys * ✅ Monitor service account usage in Google Cloud ### Connection Naming * ✅ Use descriptive names: `bigquery_prod`, `bigquery_staging` * ✅ Include environment: `bigquery_production`, `bigquery_development` * ✅ Be consistent with naming conventions ### Data Access * ✅ Grant access only to necessary datasets * ✅ Use dataset-level permissions when possible * ✅ Monitor query usage through BigQuery logs ## Next Steps Now that BigQuery is connected: * [Creating Data Views](/learn/creating-data-views/overview) - Create views using your BigQuery data * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Join BigQuery with other sources * [Connection Security](/learn/making-connections/connection-security) - Secure your connections Use your BigQuery connection to create data views # Connecting MotherDuck Source: https://docs.pylar.ai/learn/making-connections/connecting-motherduck Step-by-step guide to connecting your MotherDuck serverless analytics platform to Pylar ## Overview Connecting Pylar to MotherDuck allows you to access and analyze your MotherDuck data directly from Pylar. MotherDuck is a serverless analytics platform, and connecting it to Pylar enables seamless data querying and analysis. ## Prerequisites * ✅ Pylar account with Analyst role or higher * ✅ MotherDuck account * ✅ Access to MotherDuck service token ## Step 1: Log in to MotherDuck 1. Start by logging into your **MotherDuck account** 2. Ensure you have access to account settings ## Step 2: Retrieve Service Token 1. Once logged in, click on your **username** in the upper right corner 2. Go to **"Settings"** 3. You will see a **service token** displayed 4. **Copy this token**—you'll need it to authenticate the connection with Pylar Keep your service token secure. It provides access to your MotherDuck data. Never share it publicly or commit it to version control. ## Step 3: Navigate to Pylar Connections 1. Switch to your Pylar workspace 2. Click on the **"Connections"** tab located in the sidebar 3. You'll see the list of available data sources ## Step 4: Select MotherDuck Connector From the list of available data sources, select **"MotherDuck"**. The connection setup screen will open. ## Step 5: Paste the Service Token MotherDuck connection setup screen in Pylar 1. You will be prompted to enter your service token 2. **Paste the token** you copied from MotherDuck into the provided field 3. Double-check that the token is complete and correct The service token is a long string. Make sure you copy the entire token without any truncation. ## Step 6: Confirm the Connection 1. After pasting the service token, click on the **"Confirm"** button 2. Pylar will validate the token and establish the connection ## Step 7: Verify Connection 1. You should now see that your MotherDuck account is connected to Pylar 2. The connection will appear in your connections list ## Querying Data from MotherDuck Once connected, querying data is simple: ### Step 1: Go to Query Section 1. Navigate to the query section in your Pylar workspace 2. Open the SQL IDE ### Step 2: Run a Query Enter your SQL query to fetch data from MotherDuck: ```sql theme={null} SELECT * FROM motherduck_connection.database.table_name WHERE condition = 'value'; ``` Reference your connection using the schema name you provided during setup. ### Step 3: View Results Your query results will be displayed, showing how easy it is to access and analyze data from MotherDuck within Pylar. ## Troubleshooting ### Issue: "Invalid token" error **Solutions**: * Verify you copied the complete service token * Check for any extra spaces or characters * Ensure token hasn't expired (regenerate if needed) * Verify token has necessary permissions ### Issue: Connection fails **Solutions**: * Double-check service token is correct * Regenerate token in MotherDuck if needed * Verify MotherDuck account is active * Check network connectivity ### Issue: Data not appearing **Solutions**: * Wait for indexing to complete * Verify database and table names are correct * Check service token has access to the data * Review MotherDuck permissions ## Best Practices ### Token Security * ✅ Keep service token secure * ✅ Regenerate token if compromised * ✅ Use dedicated tokens for Pylar * ✅ Monitor token usage in MotherDuck ### Connection Naming * ✅ Use descriptive names: `motherduck_prod`, `motherduck_analytics` * ✅ Include environment information * ✅ Be consistent across your workspace ## Next Steps Now that MotherDuck is connected: * [Creating Data Views](/learn/creating-data-views/overview) - Create views using MotherDuck data * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Join MotherDuck with other sources * [Connection Security](/learn/making-connections/connection-security) - Secure your connections Use your MotherDuck connection to create data views # Connecting MySQL Source: https://docs.pylar.ai/learn/making-connections/connecting-mysql Step-by-step guide to connecting your MySQL database to Pylar ## Overview Connecting MySQL to Pylar allows you to query and analyze your MySQL data directly from Pylar. Your data remains in MySQL—Pylar indexes it for easier querying and executes queries on your MySQL infrastructure. ## Prerequisites * ✅ Pylar account with Analyst role or higher * ✅ MySQL database access * ✅ Database credentials (host, port, database name, username, password) * ✅ Ability to whitelist IP addresses in MySQL firewall ## Step 1: Navigate to Connections 1. In your Pylar workspace, click on the **"Connections"** tab located in the sidebar 2. You'll see the list of available data sources ## Step 2: Select MySQL From the list of available data sources, select **"MySQL"**. The connection setup screen will open. ## Step 3: Enter Connection Details You'll need the following information to connect: ### Host The hostname or IP address of your MySQL server. **Examples**: * `mysql.example.com` * `192.168.1.100` * `db.example.com` ### Port The port number for MySQL. **Default**: `3306` **Note**: If your MySQL server uses a non-standard port, enter that port number. ### Database Name The name of the database you want to connect to. **Example**: `production`, `analytics`, `customer_data` ### Username Your MySQL username that has access to the database. **Best Practice**: Create a dedicated user for Pylar with read-only permissions. ### Password The corresponding password for your MySQL username. Use a dedicated MySQL user account for Pylar with read-only permissions when possible. This enhances security and allows for better access control. ## Step 4: Whitelist Pylar IP Address **Critical Step**: Whitelist Pylar's IP address to ensure seamless connectivity. **Pylar IP Address**: `34.122.205.142` **How to whitelist**: ### Option 1: MySQL User Host Restrictions 1. Connect to MySQL as administrator 2. Create or modify user to allow connections from Pylar's IP: ```sql theme={null} CREATE USER 'pylar_user'@'34.122.205.142' IDENTIFIED BY 'password'; GRANT SELECT ON database_name.* TO 'pylar_user'@'34.122.205.142'; ``` ### Option 2: Cloud Provider Firewall If using a cloud-hosted MySQL (AWS RDS, Google Cloud SQL, Azure Database): **AWS RDS**: 1. Go to RDS Security Groups 2. Add inbound rule: Allow MySQL (port 3306) from IP `34.122.205.142` **Google Cloud SQL**: 1. Go to Cloud SQL instance 2. Add authorized network: `34.122.205.142/32` **Azure Database**: 1. Go to Azure Portal → Firewall settings 2. Add client IP: `34.122.205.142` ### Option 3: Server Firewall If hosting MySQL yourself: 1. Configure your server's firewall (iptables, ufw, etc.) 2. Allow port 3306 from IP `34.122.205.142` Whitelisting the IP address is crucial for establishing a secure and stable connection. Without it, Pylar will not be able to connect to your MySQL database, and you may encounter network or security blocks. ## Step 5: Test Connection 1. Click the **"Submit"** button 2. Pylar will test the connection to your MySQL database 3. If successful, you'll see a success message 4. If it fails, you'll be prompted to make corrections to your database credentials A successful connection test means Pylar can reach your MySQL server and authenticate. Verify all details are correct before proceeding. ## Step 6: Save and Connect Once the connection test is successful: 1. Click **"Save"** to save your configuration 2. You'll be prompted to give the connection a **schema name** 3. Enter a descriptive name (e.g., `mysql_production` or `analytics_db`) 4. Save the configuration **Naming Rules**: * Lowercase letters only * Numbers and underscores allowed * No spaces or special characters ## Using Your MySQL Connection ### Query MySQL Data Reference your connection by the schema name you provided: ```sql theme={null} SELECT * FROM mysql_production.customers WHERE is_active = 1; ``` ### Join with Other Sources Join MySQL data with other connected sources: ```sql theme={null} SELECT mysql.customer_id, mysql.customer_name, hs.email, sf.revenue FROM mysql_production.customers mysql JOIN hubspot.contacts hs ON mysql.email = hs.email JOIN snowflake.transactions sf ON mysql.customer_id = sf.customer_id; ``` ## Troubleshooting ### Issue: Connection test fails **Solutions**: * Verify host and port are correct * Check username and password * Ensure IP address `34.122.205.142` is whitelisted * Verify database name exists * Check MySQL is accessible from the internet ### Issue: "Access denied" error **Solutions**: * Verify username and password are correct * Check user has permissions to access the database * Ensure user host is configured correctly (allow `34.122.205.142`) * Review MySQL user privileges ### Issue: "Network or security block" error **Solutions**: * Confirm IP address `34.122.205.142` is whitelisted * Check firewall rules allow MySQL port (3306) * Review network security group settings * Verify MySQL `bind-address` allows remote connections ### Issue: "Connection timeout" error **Solutions**: * Verify MySQL server is running * Check network connectivity * Ensure firewall allows connections * Verify port number is correct ## Best Practices ### User Account Security * ✅ Create a dedicated MySQL user for Pylar * ✅ Grant only SELECT permissions (read-only) * ✅ Restrict user to specific databases * ✅ Regularly audit user permissions ### Network Security * ✅ Whitelist only Pylar's IP address * ✅ Use SSL connections when possible * ✅ Monitor connection logs * ✅ Review failed connection attempts ## Next Steps Now that MySQL is connected: * [Creating Data Views](/learn/creating-data-views/overview) - Create views using MySQL data * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Join MySQL with other sources * [Connection Security](/learn/making-connections/connection-security) - Secure your connections Use your MySQL connection to create data views # Connecting PostgreSQL Source: https://docs.pylar.ai/learn/making-connections/connecting-postgresql Step-by-step guide to connecting your PostgreSQL database to Pylar ## Overview Connecting PostgreSQL to Pylar allows you to query and analyze your PostgreSQL data directly from Pylar. Your data remains in PostgreSQL—Pylar indexes it for easier querying and executes queries on your PostgreSQL infrastructure. ## Prerequisites * ✅ Pylar account with Analyst role or higher * ✅ PostgreSQL database access * ✅ Database credentials (host, port, database name, username, password) * ✅ Ability to whitelist IP addresses in PostgreSQL firewall ## Step 1: Navigate to Connections 1. In your Pylar workspace, click on the **"Connections"** tab located in the sidebar 2. You'll see the list of available data sources ## Step 2: Select PostgreSQL From the list of available data sources, select **"PostgreSQL"**. The connection setup screen will open. ## Step 3: Enter Connection Details You'll need the following information to connect: ### Host The hostname or IP address of your PostgreSQL server. **Examples**: * `db.example.com` * `192.168.1.100` * `postgres.example.com` ### Port The port number for PostgreSQL. **Default**: `5432` **Note**: If your PostgreSQL server uses a non-standard port, enter that port number. ### Database Name The name of the database you want to connect to. **Example**: `production`, `analytics`, `customer_data` ### Username Your PostgreSQL username that has access to the database. **Best Practice**: Create a dedicated user for Pylar with read-only permissions. ### Password The corresponding password for your PostgreSQL username. Use a dedicated PostgreSQL user account for Pylar with read-only permissions when possible. This enhances security and allows for better access control. ## Step 4: Whitelist Pylar IP Address **Critical Step**: Whitelist Pylar's IP address to ensure seamless connectivity. **Pylar IP Address**: `34.122.205.142` **How to whitelist**: ### Option 1: PostgreSQL `pg_hba.conf` 1. Edit the `pg_hba.conf` file on your PostgreSQL server 2. Add a line allowing connections from Pylar's IP: ``` host all all 34.122.205.142/32 md5 ``` 3. Reload PostgreSQL configuration: ```bash theme={null} sudo systemctl reload postgresql ``` ### Option 2: Cloud Provider Firewall If using a cloud-hosted PostgreSQL (AWS RDS, Google Cloud SQL, Azure Database): **AWS RDS**: 1. Go to RDS Security Groups 2. Add inbound rule: Allow PostgreSQL (port 5432) from IP `34.122.205.142` **Google Cloud SQL**: 1. Go to Cloud SQL instance 2. Add authorized network: `34.122.205.142/32` **Azure Database**: 1. Go to Azure Portal → Firewall settings 2. Add client IP: `34.122.205.142` Whitelisting the IP address is crucial for establishing a secure and stable connection. Without it, Pylar will not be able to connect to your PostgreSQL database. ## Step 5: Test Connection 1. Click the **"Submit"** button 2. Pylar will test the connection to your PostgreSQL database 3. If successful, you'll see a success message 4. If it fails, you'll be prompted to make corrections to your database credentials A successful connection test means Pylar can reach your PostgreSQL server and authenticate. Verify all details are correct before proceeding. ## Step 6: Save and Connect Once the connection test is successful: 1. Click **"Save"** to save your configuration 2. You'll be prompted to give the connection a **schema name** 3. Enter a descriptive name (e.g., `postgres_production` or `analytics_db`) 4. Save the configuration **Naming Rules**: * Lowercase letters only * Numbers and underscores allowed * No spaces or special characters ## Step 7: Start Exploring Your PostgreSQL database is now connected to Pylar. You can: * **Query your data**: Use the SQL IDE to query PostgreSQL tables * **Create views**: Build views on your PostgreSQL data * **Join with other sources**: Combine PostgreSQL data with other connected sources ## Using Your PostgreSQL Connection ### Query PostgreSQL Data Reference your connection by the schema name you provided: ```sql theme={null} SELECT * FROM postgres_production.public.customers WHERE is_active = true; ``` ### Join with Other Sources Join PostgreSQL data with other connected sources: ```sql theme={null} SELECT pg.customer_id, pg.customer_name, hs.email, sf.opportunity_value FROM postgres_production.customers pg JOIN hubspot.contacts hs ON pg.email = hs.email JOIN snowflake.opportunities sf ON pg.customer_id = sf.account_id; ``` ## Troubleshooting ### Issue: Connection test fails **Solutions**: * Verify host and port are correct * Check username and password * Ensure IP address `34.122.205.142` is whitelisted * Verify database name exists * Check PostgreSQL is accessible from the internet ### Issue: "Connection refused" error **Solutions**: * Verify PostgreSQL is running * Check port number is correct (default 5432) * Ensure firewall allows connections from Pylar's IP * Verify PostgreSQL is configured to accept remote connections ### Issue: "Authentication failed" error **Solutions**: * Verify username and password are correct * Check user has permissions to access the database * Review PostgreSQL authentication settings * Ensure user is not locked or disabled ### Issue: "Network or security block" error **Solutions**: * Confirm IP address `34.122.205.142` is whitelisted * Check firewall rules allow PostgreSQL port (5432) * Review network security group settings * Verify PostgreSQL `listen_addresses` includes the network interface ## Best Practices ### User Account Security * ✅ Create a dedicated PostgreSQL user for Pylar * ✅ Grant only necessary permissions (read-only if possible) * ✅ Use role-based access control * ✅ Regularly audit user permissions ### Network Security * ✅ Whitelist only Pylar's IP address * ✅ Use SSL/TLS connections when possible * ✅ Monitor connection logs * ✅ Review failed connection attempts ### Connection Naming * ✅ Use descriptive names: `postgres_prod`, `postgres_analytics` * ✅ Include environment information * ✅ Be consistent across your workspace ## Next Steps Now that PostgreSQL is connected: * [Creating Data Views](/learn/creating-data-views/overview) - Create views using PostgreSQL data * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Join PostgreSQL with other sources * [Connection Security](/learn/making-connections/connection-security) - Secure your connections Use your PostgreSQL connection to create data views # Connecting Redshift Source: https://docs.pylar.ai/learn/making-connections/connecting-redshift Step-by-step guide to connecting your Amazon Redshift data warehouse to Pylar ## Overview Connecting Pylar to Redshift allows you to harness the power of your Redshift data for analysis and insights. Your data remains in Redshift—Pylar indexes it for easier querying and executes queries on your Redshift infrastructure. ## Prerequisites * ✅ Pylar account with Analyst role or higher * ✅ Amazon Redshift cluster access * ✅ Redshift endpoint URL * ✅ AWS username and password for Redshift * ✅ Ability to modify security group settings (for IP whitelisting) ## Step 1: Prepare Your Redshift Database Before connecting, ensure: 1. Your Redshift database is **accessible from outside your VPC network** 2. You have the Redshift endpoint URL 3. You have AWS credentials (username and password) for Redshift 4. You can modify security groups to whitelist IP addresses This is crucial for allowing Pylar to query your data. If your Redshift cluster is in a private VPC, you may need to configure network access or use an SSH tunnel. ## Step 2: Retrieve Endpoint Information 1. Open your **Redshift application** or AWS Console 2. Navigate to your Redshift cluster 3. Copy the **endpoint URL** **Format**: The endpoint typically looks like: ``` my-cluster.abc123.us-east-1.redshift.amazonaws.com:5439 ``` ## Step 3: Navigate to Pylar Connections 1. Switch to your Pylar workspace 2. Click on the **"Connections"** tab located in the sidebar 3. You'll see the list of available data sources ## Step 4: Select Redshift Connector From the list of available data sources, select **"Redshift"**. The connection setup screen will open. ## Step 5: Enter Connection Details Redshift connection setup screen in Pylar ### Endpoint URL 1. Paste your Redshift endpoint URL into the endpoint field 2. **Remove everything after the colon (`:`)** in the URL The part after the colon represents the port number. You'll enter the port separately. **Example**: * Full endpoint: `my-cluster.abc123.us-east-1.redshift.amazonaws.com:5439` * After removing port: `my-cluster.abc123.us-east-1.redshift.amazonaws.com` ### Port Enter the port number for Redshift. **Default**: `5439` **Note**: If your endpoint URL had a different port, use that. Otherwise, use the default `5439`. ### Database Name Enter the name of your Redshift database. **Example**: `dev`, `production`, `analytics` ### Username Enter your **AWS username** associated with the Redshift database. **Note**: This should be a user with appropriate permissions to query the database. ### Password Enter the **AWS password** corresponding to your Redshift username. Use a dedicated Redshift user account for Pylar with read-only permissions when possible. This enhances security and allows for better access control. ## Step 6: Whitelist Pylar IP Address **Critical Step**: Whitelist Pylar's IP address to ensure seamless connectivity. **Pylar IP Address**: `34.122.205.142` **How to whitelist in Redshift**: 1. In AWS Console, go to **Redshift** → **Clusters** 2. Select your cluster 3. Go to **Properties** → **Network and security** 4. Click on the **VPC security group** associated with your cluster 5. In the security group, add an **Inbound Rule**: * **Type**: Redshift * **Protocol**: TCP * **Port**: 5439 (or your custom port) * **Source**: `34.122.205.142/32` 6. Save the security group rules Without whitelisting the IP address, Pylar will not be able to connect to your Redshift database. This step is crucial for establishing a secure and stable connection. ## Step 7: Test Connection 1. Click the **"Test Connection"** button 2. Pylar will attempt to connect to your Redshift database 3. If successful, you'll see a success message 4. If it fails, you'll be prompted to make corrections to your database credentials A successful connection test means Pylar can reach your Redshift cluster and authenticate. Verify all details are correct before proceeding. ## Step 8: Save and Connect Once the connection test is successful: 1. Click **"Save"** to save your configuration 2. You'll be prompted to give the connection a **schema name** 3. Enter a descriptive name (e.g., `redshift_production` or `analytics_warehouse`) 4. Save the configuration **Naming Rules**: * Lowercase letters only * Numbers and underscores allowed * No spaces or special characters ## Step 9: Wait for Ingestion After saving: 1. **Data indexing begins**: Pylar starts indexing your Redshift data 2. **Processing time**: This may take a while depending on the volume of data 3. **Notification**: You'll receive an email notification once data ingestion is complete If your Redshift data doesn't show up immediately, give it a few minutes. Large databases can take time to index. You'll receive an email when the process is complete. ## Using Your Redshift Connection Once indexing is complete: ### Query Redshift Data Reference your connection by the schema name you provided: ```sql theme={null} SELECT * FROM redshift_production.public.customers WHERE region = 'us-east'; ``` ### Join with Other Sources Join Redshift data with other connected sources: ```sql theme={null} SELECT rs.customer_id, rs.total_revenue, hs.email, sf.opportunity_value FROM redshift_production.customers rs JOIN hubspot.contacts hs ON rs.email = hs.email JOIN snowflake.opportunities sf ON rs.customer_id = sf.account_id; ``` ## Troubleshooting ### Issue: Connection test fails **Solutions**: * Verify endpoint URL is correct (without port) * Check port number (default 5439) * Ensure IP address `34.122.205.142` is whitelisted in security group * Verify database name exists * Check username and password are correct ### Issue: "Connection timeout" error **Solutions**: * Verify Redshift cluster is publicly accessible * Check security group allows inbound connections on port 5439 * Ensure IP address is whitelisted * Review VPC network configuration ### Issue: "Authentication failed" error **Solutions**: * Verify AWS username and password are correct * Check user has necessary permissions * Ensure user is not locked * Review Redshift user permissions ### Issue: "Network or security block" error **Solutions**: * Confirm IP address `34.122.205.142` is whitelisted in security group * Check security group rules allow Redshift protocol * Verify cluster is publicly accessible * Review VPC and subnet configurations ## Best Practices ### User Account Security * ✅ Create a dedicated Redshift user for Pylar * ✅ Grant only SELECT permissions (read-only) * ✅ Use IAM roles when possible * ✅ Regularly audit user permissions ### Network Security * ✅ Whitelist only Pylar's IP address * ✅ Use VPC security groups for access control * ✅ Monitor connection logs * ✅ Review failed connection attempts ## Next Steps Now that Redshift is connected: * [Creating Data Views](/learn/creating-data-views/overview) - Create views using Redshift data * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Join Redshift with other sources * [Connection Security](/learn/making-connections/connection-security) - Secure your connections Use your Redshift connection to create data views # Connecting Snowflake Source: https://docs.pylar.ai/learn/making-connections/connecting-snowflake Step-by-step guide to connecting your Snowflake data warehouse to Pylar ## Overview Connecting Pylar to Snowflake allows you to leverage your Snowflake data for analysis and insights. Your data remains in Snowflake—Pylar indexes it for easier querying and executes queries on your Snowflake infrastructure. ## Prerequisites * ✅ Pylar account with Analyst role or higher * ✅ Snowflake account with access credentials * ✅ Database access permissions in Snowflake * ✅ Ability to whitelist IP addresses in Snowflake ## Step 1: Prepare Your Snowflake Account Before connecting, ensure you have: 1. Access to your Snowflake account 2. Database credentials (username and password) 3. Knowledge of which database you want to connect 4. Ability to modify network policies (for IP whitelisting) ## Step 2: Retrieve Snowflake Account URL 1. Open your **Snowflake UI** in a new tab 2. Log in to your Snowflake account 3. Locate your **account URL** **Format**: The URL is typically displayed as: ``` https://.snowflakecomputing.com ``` **Example**: `https://abc12345.us-east-1.snowflakecomputing.com` ## Step 3: Trim the URL Copy your Snowflake account URL and prepare it for Pylar: 1. **Remove the `https://` prefix** 2. **Remove everything after `.snowflakecomputing.com`** **Result**: You should be left with just: ``` .snowflakecomputing.com ``` **Example**: * Original: `https://abc12345.us-east-1.snowflakecomputing.com` * Trimmed: `abc12345.us-east-1.snowflakecomputing.com` The trimmed URL is what you'll paste into Pylar. Make sure to include the full account identifier including the region (e.g., `.us-east-1`). ## Step 4: Navigate to Pylar Connections 1. Switch to your Pylar workspace 2. Click on the **"Connections"** tab located in the sidebar 3. You'll see the list of available data sources ## Step 5: Select Snowflake Connector From the list of available data sources, select **"Snowflake"**. The connection setup screen will open. ## Step 6: Enter Connection Details Fill in the following information: Snowflake connection setup screen in Pylar ### Account URL Paste the **trimmed Snowflake account URL** you prepared in Step 3. **Format**: `.snowflakecomputing.com` **Example**: `abc12345.us-east-1.snowflakecomputing.com` ### Database Name Enter the name of the database you want to use. **Examples**: * `SNOWFLAKE_SAMPLE_DATA` (if using sample data) * `PRODUCTION` (your production database) * `ANALYTICS` (your analytics database) ### Username Enter the **username** you use to log into your Snowflake account. **Note**: This should be a user with appropriate permissions to query the database. ### Password Enter the **corresponding password** for your Snowflake account. Use a dedicated Snowflake user account for Pylar with read-only permissions when possible. This enhances security and allows for better access control. ## Step 7: Whitelist Pylar IP Address **Critical Step**: Whitelist Pylar's IP address to ensure seamless connectivity. **Pylar IP Address**: `34.122.205.142` **How to whitelist in Snowflake**: 1. Log in to Snowflake as an administrator 2. Go to **Admin** → **Security** → **Network Policies** 3. Create a new network policy or modify an existing one 4. Add `34.122.205.142` to the allowed IP addresses 5. Apply the network policy to your account or user **Alternative** (if network policies aren't available): * Contact your Snowflake administrator to whitelist the IP * Or configure at the account level if you have admin access Without whitelisting the IP address, Pylar will not be able to connect to your Snowflake database. This step is crucial for establishing a secure and stable connection. ## Step 8: Test Connection 1. Click the **"Test Connection"** button 2. Pylar will attempt to connect to your Snowflake database 3. If successful, you'll see a success message 4. If it fails, you'll be prompted to correct your credentials A successful test connection means Pylar can reach your Snowflake database and authenticate. This is a good sign that everything is configured correctly. ## Step 9: Save and Connect Once the connection test is successful: 1. Click **"Save"** or **"Connect"** 2. You'll be prompted to give the connection a **schema name** 3. Enter a descriptive name (e.g., `snowflake_production` or `analytics_warehouse`) 4. Save the configuration **Naming Rules**: * Lowercase letters only * Numbers and underscores allowed * No spaces or special characters ## Step 10: Wait for Ingestion After saving: 1. **Data indexing begins**: Pylar starts indexing your Snowflake data 2. **Processing time**: This may take a while depending on the volume of data 3. **Notification**: You'll receive an email notification once data ingestion is complete If your Snowflake data doesn't show up immediately, give it a few minutes. Large databases can take time to index. You'll receive an email when the process is complete. ## Querying Data from Snowflake Once indexing is complete, querying data is simple: ### Step 1: Go to Query Section 1. Navigate to the query section in your Pylar workspace 2. Open the SQL IDE ### Step 2: Run a Query Enter your SQL query to fetch data from Snowflake: ```sql theme={null} SELECT * FROM snowflake_production.public.customers WHERE region = 'North America'; ``` Reference your connection using the schema name you provided. ### Step 3: View Results Your query results will be displayed, showing how easy it is to access and analyze data from Snowflake within Pylar. ## Troubleshooting ### Issue: Connection test fails **Solutions**: * Verify account URL is trimmed correctly (no `https://`, nothing after `.snowflakecomputing.com`) * Check username and password are correct * Ensure IP address `34.122.205.142` is whitelisted * Verify database name exists and is accessible ### Issue: "Network policy" error **Solutions**: * Confirm IP address `34.122.205.142` is whitelisted * Check network policy is applied to your user or account * Verify network policy allows outbound connections * Contact Snowflake administrator if needed ### Issue: "Authentication failed" **Solutions**: * Verify username and password are correct * Check if account is locked or disabled * Ensure user has necessary permissions * Try resetting password in Snowflake ### Issue: Data not appearing after connection **Solutions**: * Wait for indexing to complete (check email notification) * Verify database name is correct * Check user has SELECT permissions on tables * Review Snowflake query history for errors ## Best Practices ### User Account Security * ✅ Create a dedicated Snowflake user for Pylar * ✅ Grant only read permissions (SELECT on necessary databases/tables) * ✅ Use role-based access control (RBAC) in Snowflake * ✅ Regularly review and audit user permissions ### Network Security * ✅ Whitelist only Pylar's IP address * ✅ Use network policies for additional security * ✅ Monitor connection logs in Snowflake * ✅ Review failed login attempts ### Connection Naming * ✅ Use descriptive names: `snowflake_prod`, `snowflake_analytics` * ✅ Include environment: `snowflake_production`, `snowflake_staging` * ✅ Be consistent across your workspace ## Next Steps Now that Snowflake is connected: * [Creating Data Views](/learn/creating-data-views/overview) - Create views using Snowflake data * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Join Snowflake with other sources * [Connection Security](/learn/making-connections/connection-security) - Secure your connections Use your Snowflake connection to create data views # Connecting Supabase Source: https://docs.pylar.ai/learn/making-connections/connecting-supabase Step-by-step guide to connecting your Supabase (hosted PostgreSQL) database to Pylar ## Overview Supabase is a hosted PostgreSQL service. Connecting your Supabase database to Pylar allows you to query and analyze your Supabase data directly from Pylar, just like any PostgreSQL database. ## Prerequisites * ✅ Pylar account with Analyst role or higher * ✅ Supabase account with an active project * ✅ Database password (Supabase does not provide this in connection details) ## Step 1: Log into Supabase 1. Log into your **Supabase** account 2. Open the **project** you want to connect to Pylar ## Step 2: Get Connection Details 1. At the top of your Supabase project, click the **"Connect"** button 2. You'll see connection options: * **Direct Connection** (for direct access) * **Transaction Pooler** (for pooled connections) 3. **Ignore the URI**—instead, click **"View Parameters"** to reveal the necessary connection details Supabase provides connection parameters rather than a single URI. You'll need to copy these individual parameters. ## Step 3: Copy Connection Parameters From the "View Parameters" view, copy the following details: * **Host**: The Supabase database host * **Port**: The database port (usually 5432) * **Database Name**: The database name * **User**: The database user **Important**: Supabase does **not** provide the password in the connection details. You'll need to enter it manually in Pylar. You'll need to know your Supabase database password. If you don't have it, you may need to reset it in Supabase settings. ## Step 4: Configure Pylar Connection 1. Open Pylar's **Connections** page 2. Select **PostgreSQL** as the database type (since Supabase is PostgreSQL-based) 3. Enter the connection details: ### Host Paste the **Host** parameter from Supabase. ### Port Enter the **Port** parameter (usually `5432`). ### Database Name Enter the **Database Name** from Supabase. ### Username Enter the **User** parameter from Supabase. ### Password **Manually enter** your Supabase database password. Since Supabase doesn't provide the password in connection details, you must enter it manually. This is the password you set when creating your Supabase project or the one you've configured. ## Step 5: Whitelist Pylar IP Address **Critical Step**: Whitelist Pylar's IP address in Supabase. **Pylar IP Address**: `34.122.205.142` **How to whitelist in Supabase**: 1. In Supabase, go to **Project Settings** → **Database** 2. Scroll to **Connection Pooling** or **Network Restrictions** 3. Add `34.122.205.142` to the allowed IP addresses 4. Or configure your Supabase project's network access settings Without whitelisting the IP address, Pylar will not be able to connect to your Supabase database. This step is crucial for establishing a secure connection. ## Step 6: Test and Connect 1. Click **"Connect"** or **"Submit"** in Pylar 2. Pylar will test the connection to your Supabase database 3. If successful, the connection will be established ## Step 7: Wait for Data Sync After connecting: 1. **Data will begin syncing automatically** 2. You don't need to wait—Pylar will notify you via **email** once the data is available for querying 3. The sync process may take some time depending on data volume You'll receive an email notification when your Supabase data is ready to query. You can continue working while the sync happens in the background. ## Using Your Supabase Connection Once synced, you can query Supabase data just like any PostgreSQL database: ```sql theme={null} SELECT * FROM supabase_connection.public.customers WHERE is_active = true; ``` ## Connection Type Options ### Direct Connection * **Use when**: You want direct database access * **Best for**: Production workloads * **Note**: May have connection limits ### Transaction Pooler * **Use when**: You want pooled connections * **Best for**: High-concurrency scenarios * **Note**: Uses a different port (usually 6543) Choose the connection type based on your needs. Direct Connection is simpler for most use cases, while Transaction Pooler helps with connection management. ## Troubleshooting ### Issue: Connection test fails **Solutions**: * Verify all parameters are copied correctly from Supabase * Check database password is correct * Ensure IP address `34.122.205.142` is whitelisted * Verify Supabase project is active ### Issue: "Authentication failed" error **Solutions**: * Double-check database password * Verify username matches Supabase user * Check if password was reset recently * Review Supabase user permissions ### Issue: "Connection refused" error **Solutions**: * Verify IP address is whitelisted in Supabase * Check network restrictions in Supabase settings * Ensure project is not paused * Review Supabase project status ## Best Practices ### Password Security * ✅ Use a strong database password * ✅ Store password securely (password manager) * ✅ Never share password publicly * ✅ Rotate password periodically ### Connection Naming * ✅ Use descriptive names: `supabase_prod`, `supabase_staging` * ✅ Include environment information * ✅ Be consistent across your workspace ## Next Steps Now that Supabase is connected: * [Creating Data Views](/learn/creating-data-views/overview) - Create views using Supabase data * [Cross-Database Joins](/learn/creating-data-views/cross-database-joins) - Join Supabase with other sources * [Connection Security](/learn/making-connections/connection-security) - Secure your connections Use your Supabase connection to create data views # Connecting via SSH Source: https://docs.pylar.ai/learn/making-connections/connecting-via-ssh Enhanced security option: Connect databases to Pylar using SSH tunnels for maximum data privacy ## Overview For enhanced data privacy and security, you can connect databases to Pylar using SSH tunnels. This approach provides an additional layer of security by routing database connections through a secure SSH tunnel. ## When to Use SSH Connections SSH connections are ideal when: * ✅ You want maximum security for sensitive databases * ✅ Your database is in a private VPC or network * ✅ You need additional access control layers * ✅ Compliance requirements demand enhanced security * ✅ You want to use a dedicated user account approach SSH connections provide the highest level of security by routing all database traffic through an encrypted SSH tunnel. ## How SSH Connections Work ### Architecture ``` Pylar → SSH Tunnel (Bastion VM) → Database Auth Proxy → Your Database ``` 1. **Pylar** connects to your **Bastion VM** via SSH 2. **Bastion VM** runs the **Database Auth Proxy** 3. **Auth Proxy** connects to your **database** 4. All traffic is encrypted through the SSH tunnel ### Benefits * ✅ **Enhanced Security**: All traffic encrypted through SSH * ✅ **Network Isolation**: Database stays in private network * ✅ **Access Control**: Additional layer of authentication * ✅ **Audit Trail**: Monitor SSH connections separately ## Prerequisites Before setting up SSH connections: * ✅ Access to create a Virtual Machine (VM) * ✅ Ability to install software on the VM * ✅ Database in private VPC or network * ✅ Admin access to configure network settings * ✅ Understanding of SSH key management ## Step-by-Step Setup ### Step 1: Create a Bastion VM Set up a Virtual Machine to act as your bastion: 1. **Create VM in GCP** (or your cloud provider): * Choose appropriate VM size * Place VM in same VPC as database (or network-connected) * Configure VM with public IP or VPN access * Install operating system (Linux recommended) 2. **Configure Network**: * Open port 22 (SSH) for Pylar's IP (`34.122.205.142`) * Ensure VM can reach your database * Configure firewall rules appropriately ### Step 2: Install Database Auth Proxy On the bastion VM, install the **AlloyDB Auth Proxy** (or appropriate database proxy): 1. **Download and Install**: ```bash theme={null} # Example for AlloyDB wget https://alloydb-auth-proxy-release.s3.amazonaws.com/alloydb-auth-proxy chmod +x alloydb-auth-proxy ``` 2. **Configure Proxy**: * Set up proxy to connect to your database * Configure proxy to listen on localhost * Test proxy connection to database The database auth proxy handles authentication and provides an additional security layer between the SSH tunnel and your database. ### Step 3: Generate SSH Keypair Pylar will generate an SSH keypair for your workspace: 1. In Pylar, go to **Connections** → **SSH Configuration** 2. Pylar generates a public/private keypair 3. **Copy the public key** from your integrations page 4. Save it for use in the next step Keep your private key secure. Pylar manages it, but ensure you have backups if needed. ### Step 4: Set Up Service Account and User on Bastion 1. **Create Service Account in GCP**: * Create a service account for Pylar * Grant necessary permissions * Note the service account details 2. **Create User on Bastion**: * Create a new user on the bastion VM * Link user to the service account * Log in as this user 3. **Add SSH Public Key**: * Add the public key you copied from Pylar * Add it to `~/.ssh/authorized_keys`: ```bash theme={null} echo "YOUR_PUBLIC_KEY_HERE" >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys ``` * Verify SSH access works ### Step 5: Configure Database in Pylar AlloyDB SSH connection setup screen in Pylar In Pylar's connection setup: #### SSH Section 1. **Host**: Enter the hostname or IP of your bastion VM 2. **Port**: SSH port (usually `22`) 3. **Username**: The user name under which you added the SSH key #### Database Section 1. **Host**: Enter `127.0.0.1` (localhost on the bastion) 2. **Port**: Port of the AlloyDB Auth Proxy (usually `5432`) 3. **Database Name**: Name of your AlloyDB database 4. **Username**: Username for the AlloyDB user you created for Pylar 5. **Password**: Password for the AlloyDB user The database host is `127.0.0.1` because the proxy runs on the bastion VM itself. The proxy connects to your actual database. ## Security Considerations ### SSH Key Management * ✅ **Secure Storage**: Keys are stored securely in Pylar * ✅ **Key Rotation**: Rotate SSH keys periodically * ✅ **Access Control**: Limit who can access SSH keys * ✅ **Monitoring**: Monitor SSH access logs ### Bastion VM Security * ✅ **Hardening**: Apply security hardening to the VM * ✅ **Updates**: Keep VM and software updated * ✅ **Monitoring**: Monitor VM access and activity * ✅ **Backup**: Have backup/recovery procedures ### Network Security * ✅ **Firewall Rules**: Restrict SSH access to Pylar IP only * ✅ **VPN Option**: Consider VPN instead of public IP * ✅ **Private Networks**: Keep database in private network * ✅ **Access Logs**: Monitor all network access ## Benefits of SSH Connections ### Enhanced Security * **Encrypted Tunnel**: All traffic encrypted through SSH * **Network Isolation**: Database never directly exposed * **Additional Authentication**: SSH key + database credentials * **Audit Trail**: Separate logs for SSH and database access ### Compliance * **Regulatory Requirements**: Meets strict compliance needs * **Audit Trails**: Complete logging of all access * **Access Controls**: Multiple layers of security * **Data Privacy**: Maximum protection for sensitive data ## Troubleshooting ### Issue: SSH connection fails **Solutions**: * Verify SSH public key is in authorized\_keys * Check bastion VM is accessible * Verify port 22 is open * Check SSH service is running on bastion ### Issue: Database connection through proxy fails **Solutions**: * Verify proxy is running on bastion * Check proxy can reach database * Verify database credentials * Review proxy logs ### Issue: Connection timeout **Solutions**: * Check network connectivity to bastion * Verify firewall rules * Review SSH connection logs * Test SSH connection manually ## Best Practices ### Bastion VM * ✅ Use minimal VM size needed * ✅ Apply security patches regularly * ✅ Monitor VM resource usage * ✅ Have backup/recovery plan ### SSH Keys * ✅ Rotate keys periodically * ✅ Use strong key types (RSA 4096 or Ed25519) * ✅ Monitor key usage * ✅ Revoke keys when no longer needed ### Database Proxy * ✅ Keep proxy software updated * ✅ Monitor proxy logs * ✅ Configure proxy for performance * ✅ Test proxy connectivity regularly ## Alternative: Dedicated User Account If you choose the dedicated user account approach without SSH: 1. Create dedicated database user for Pylar 2. Grant limited permissions (read-only if possible) 3. Use audit logging to monitor access 4. Establish limited database views accessible by Pylar user This provides good security without the complexity of SSH tunnels. ## Next Steps * [Connection Security](/learn/making-connections/connection-security) - General security practices * [Managing Connections](/learn/making-connections/managing-connections) - Manage your SSH connections * [Creating Data Views](/learn/creating-data-views/overview) - Use your secure connections Learn more security best practices # Connection Security Source: https://docs.pylar.ai/learn/making-connections/connection-security Learn about data security in Pylar and best practices for securing your database connections ## Data Security at Pylar At Pylar, we understand the importance of data security. Our platform employs multiple layers of security to protect your data and credentials. ### Default Encryption Pylar servers employ **default encryption** to safeguard your data: * Data at rest is encrypted * Data in transit is encrypted via HTTPS * All API interactions use HTTPS protocol ### Secret Management Sensitive information is stored securely: * **Database Credentials**: Stored in Google Cloud Platform's (GCP) Secret Key Manager * **SQL Query Outputs**: Protected with robust access controls * **Stringent Access Control**: Multiple layers of security ### HTTPS Protocol All API interactions are fortified with HTTPS: * **Encryption in Transit**: Data is encrypted during transmission * **Protection Against Unauthorized Access**: Prevents interception and tampering * **Secure Communication**: All connections use industry-standard encryption Pylar uses Google Cloud Platform's Secret Key Manager, which provides enterprise-grade security for storing and managing sensitive credentials. ## Enhancing Your Data Privacy While Pylar provides a secure environment, you can take additional steps to further boost your data privacy. ### Creating a Dedicated User Account For more granular control, consider setting up a **dedicated Pylar user account** in your database environment. **Benefits**: * ✅ **Assign Specific Access Rights**: Give Pylar only the permissions it needs * ✅ **Establish Limited Views**: Control exactly what data Pylar can access * ✅ **Utilize Audit Logging**: Monitor all queries executed by Pylar **How to implement**: 1. Create a new database user specifically for Pylar 2. Grant only necessary permissions: ```sql theme={null} -- Example for PostgreSQL CREATE USER pylar_user WITH PASSWORD 'secure_password'; GRANT SELECT ON specific_schema.specific_table TO pylar_user; ``` 3. Use this dedicated user when connecting to Pylar 4. Set up audit logging to track all Pylar queries A dedicated user account with limited permissions is a security best practice. It follows the principle of least privilege—giving only the minimum access needed. ## IP Whitelisting ### Pylar IP Address **Pylar IP Address**: `34.122.205.142` This is a permanently assigned IP address. Whitelist it in your database firewall settings. ### Why Whitelist? * **Security**: Restricts access to only Pylar's IP * **Stability**: Ensures reliable connectivity * **Control**: You control who can access your database ### How to Whitelist The process varies by database provider: * **AWS RDS**: Add to security group inbound rules * **Google Cloud SQL**: Add to authorized networks * **Azure Database**: Add to firewall rules * **Self-hosted**: Configure server firewall (iptables, ufw, etc.) Whitelisting the IP address is crucial for most database connections. Without it, Pylar may not be able to connect, and you may encounter network or security blocks. ## Network Security Best Practices ### Firewall Configuration * ✅ **Whitelist Only**: Only allow Pylar's IP address * ✅ **Restrict Ports**: Only open necessary database ports * ✅ **Review Regularly**: Periodically review firewall rules * ✅ **Monitor Access**: Log and monitor connection attempts ### VPN and Private Networks For enhanced security: * Use VPN connections when possible * Configure private network access * Use SSH tunnels for additional security (see SSH Connections guide) ## Credential Management ### Secure Storage * ✅ **Never Share**: Don't share credentials publicly * ✅ **Use Password Managers**: Store credentials securely * ✅ **Rotate Regularly**: Change passwords periodically * ✅ **Limit Access**: Only share with authorized team members ### Service Account Best Practices For cloud databases (BigQuery, etc.): * ✅ **Dedicated Accounts**: Create service accounts specifically for Pylar * ✅ **Minimal Permissions**: Grant only necessary permissions * ✅ **Key Rotation**: Rotate service account keys regularly * ✅ **Monitor Usage**: Review service account activity logs ## Access Control ### Database-Level Security * ✅ **User Permissions**: Use dedicated users with limited permissions * ✅ **Schema-Level Access**: Restrict access to specific schemas * ✅ **Table-Level Access**: Grant access only to necessary tables * ✅ **View-Based Access**: Use database views to limit data exposure ### Audit Logging Enable audit logging to monitor: * **All Queries**: Track every query Pylar executes * **Access Patterns**: Understand how data is being accessed * **Security Events**: Identify suspicious activity * **Compliance**: Maintain audit trails for compliance ## Views as Security Layer ### Views Are the Only Access Level Remember: **Views are the only access level agents get**. This means: * ✅ **No Raw Access**: Agents never access raw database tables * ✅ **Controlled Data**: You define exactly what data is available * ✅ **Additional Security Layer**: Views provide an extra security boundary ### Best Practices for Views * ✅ **Filter Sensitive Data**: Exclude PII, financial data, etc. * ✅ **Row-Level Security**: Implement filters based on context * ✅ **Column-Level Security**: Select only necessary columns * ✅ **Documentation**: Document what each view exposes ## Compliance and Auditing ### Compliance Requirements Pylar helps you meet regulatory requirements: * **SOC 2**: Security controls and audit trails * **GDPR**: Data access controls and logging * **HIPAA**: Protected health information controls * **Other Regulations**: Customizable access controls ### Audit Trails Pylar provides: * **Query Logs**: Every query is logged * **Access Logs**: Who accessed what and when * **Evals**: Comprehensive usage analytics * **Export Capabilities**: Export logs for compliance reviews ## Security Checklist Before connecting databases: * ✅ Create dedicated user account for Pylar * ✅ Grant only necessary permissions (read-only if possible) * ✅ Whitelist Pylar IP address (`34.122.205.142`) * ✅ Enable audit logging in your database * ✅ Use strong passwords * ✅ Store credentials securely * ✅ Review access regularly After connecting: * ✅ Monitor connection logs * ✅ Review Evals for usage patterns * ✅ Update credentials if compromised * ✅ Audit user permissions periodically * ✅ Review firewall rules regularly ## Next Steps * [Managing Connections](/learn/making-connections/managing-connections) - Manage and monitor your connections * [SSH Connections](/learn/making-connections/connecting-via-ssh) - Enhanced security with SSH tunnels * [Troubleshooting Connections](/learn/making-connections/troubleshooting-connections) - Resolve connection issues Learn about SSH tunnel connections for enhanced security # Managing Connections Source: https://docs.pylar.ai/learn/making-connections/managing-connections Learn how to view, edit, test, and manage your database connections in Pylar ## Overview Once you've created connections in Pylar, you can manage them from the Connections page. This includes viewing connection details, testing connections, editing configurations, and removing connections when no longer needed. ## Accessing Connections 1. In your Pylar workspace, click on the **"Connections"** tab in the sidebar 2. You'll see a list of all your connections 3. Each connection shows its status and basic information ## Viewing Connections ### Connection List The Connections page displays: * **Connection Name**: The schema name you assigned * **Type**: Database type (BigQuery, Snowflake, PostgreSQL, etc.) * **Status**: Connection status (Active, Indexing, Error, etc.) * **Last Sync**: When data was last synced (for Business Applications) * **Last Indexed**: When data was last indexed (for Databases) ### Connection Details Click on a connection to view: * **Connection Information**: Host, database name, credentials (masked) * **Sync Status**: Current sync/indexing progress * **Data Statistics**: Number of tables, schemas indexed * **Usage Information**: How often the connection is used ## Testing Connections ### Test Existing Connection 1. Go to the Connections page 2. Find the connection you want to test 3. Click **"Test Connection"** or similar button 4. Pylar will verify the connection is working ### What Gets Tested * **Network Connectivity**: Can Pylar reach your database? * **Authentication**: Are credentials valid? * **Permissions**: Does the user have necessary access? * **Database Access**: Can Pylar query the database? Regular testing helps identify connection issues before they affect your workflows. Test connections periodically or after making changes. ## Editing Connections ### When to Edit You may need to edit connections to: * Update credentials (password changed) * Modify connection settings * Change database name * Update host or port information ### How to Edit 1. Go to the Connections page 2. Find the connection you want to edit 3. Click **"Edit"** or the connection name 4. Modify the settings you need to change 5. **Test the connection** after making changes 6. Save your changes Editing connection credentials may temporarily interrupt data access. Test the connection after making changes to ensure it still works. ## Connection Health Monitoring ### Status Indicators Connections show status indicators: * ✅ **Active**: Connection is working correctly * ⏳ **Indexing**: Data is being indexed (for databases) * ⏳ **Syncing**: Data is being synced (for Business Applications) * ⚠️ **Warning**: Connection has issues but still works * ❌ **Error**: Connection has failed ### Monitoring Health * **Regular Checks**: Pylar periodically checks connection health * **Notifications**: You'll be notified if connections fail * **Status Updates**: Connection status updates automatically * **Logs**: Review connection logs for issues ## Removing Connections ### When to Remove Remove connections when: * You no longer need the data source * The database has been decommissioned * You're consolidating connections * Cleaning up unused connections ### How to Remove 1. Go to the Connections page 2. Find the connection you want to remove 3. Click **"Delete"** or **"Remove"** 4. Confirm the deletion Removing a connection will: * Break any views that depend on it * Remove the connection from your workspace * Stop all syncing/indexing Make sure you no longer need the connection before removing it. ## Connection Status ### Active Connections * **Working correctly**: Can query data * **Synced/Indexed**: Data is available * **Ready to use**: Can be used in views and queries ### Indexing/Syncing * **In progress**: Data is being processed * **Wait for completion**: You'll be notified when done * **Can't query yet**: Wait for process to complete ### Error Status * **Connection failed**: Check credentials and network * **Authentication error**: Verify username/password * **Network error**: Check IP whitelisting and firewall ## Best Practices ### Regular Monitoring * ✅ Check connection status regularly * ✅ Test connections after credential changes * ✅ Monitor connection health * ✅ Review error notifications promptly ### Connection Organization * ✅ Use descriptive names * ✅ Include environment (prod, staging, dev) * ✅ Group related connections * ✅ Document connection purposes ### Maintenance * ✅ Update credentials before they expire * ✅ Test connections after infrastructure changes * ✅ Remove unused connections * ✅ Review connection permissions periodically ## Troubleshooting Connection Issues ### Connection Appears Offline **Solutions**: * Test the connection * Check network connectivity * Verify credentials haven't changed * Review connection logs ### Sync/Index Never Completes **Solutions**: * Check for very large datasets * Verify connection is still active * Review error messages * Contact support if needed ### Can't Query Data **Solutions**: * Verify connection status is "Active" * Check if indexing/syncing is complete * Review database permissions * Test connection manually ## Next Steps * [Connection Security](/learn/making-connections/connection-security) - Secure your connections * [Troubleshooting Connections](/learn/making-connections/troubleshooting-connections) - Resolve connection issues * [Creating Data Views](/learn/creating-data-views/overview) - Use your connections to create views Learn security best practices for your connections # Overview Source: https://docs.pylar.ai/learn/making-connections/overview Introduction to connecting data sources to Pylar - learn about connection types and the connection process ## What Are Connections? Connections in Pylar link your data sources to the platform, enabling you to query and analyze data from multiple sources in one place. Connections are the foundation of creating views and building MCP tools. ## Accessing Connections To connect data sources: 1. In the left sidebar, under your current workspace, find the **"Connections"** page 2. Click on **"Connections"** to open it 3. You'll see a list of connect cards, each representing an available data source ## Types of Data Sources Pylar supports two types of data sources: ### Business Applications **What they are**: Applications like Google Sheets, HubSpot, Salesforce, etc. **How they work**: * Data is **synced to Pylar Warehouse** * Data is copied to Pylar's infrastructure * Fast querying with Pylar's optimized storage * Regular syncs keep data up to date **Examples**: Google Sheets, HubSpot, Salesforce, etc. ### Databases and Data Warehouses **What they are**: Databases like Snowflake, PostgreSQL, BigQuery, etc. **How they work**: * Data is **indexed for easier querying** and autocompletion * Your data **remains in its original location** * Queries are **executed on your infrastructure** * Can be joined with any other sources (including Business Applications) * No data copying—direct query access **Examples**: Snowflake, BigQuery, PostgreSQL, MySQL, Redshift, etc. The key difference: Business Applications sync data to Pylar, while Databases/Data Warehouses are queried directly where they live. ## Connection Process Overview ### For Business Applications 1. Click on the relevant connection card 2. Provide a unique name for the connection 3. Complete the authentication process (varies by source) 4. Wait for data sync to complete **Naming Requirements**: * Must not contain capital letters * No special characters * No spaces (use underscores instead) * This name will be used to reference the source in SQL queries **Multiple Instances**: You can connect multiple instances of the same Business Application (e.g., multiple Google Sheets), as long as each has a unique name. ### For Databases/Data Warehouses 1. Click on the database/data warehouse card 2. Provide connection credentials 3. Whitelist Pylar's IP address (if required) 4. Test the connection 5. Wait for indexing to complete **IP Address**: Pylar's IP address is **34.122.205.142** (permanently assigned). Whitelist this IP in your database firewall settings. If you don't have database credentials, you can invite a team member who does have access to complete the connection. ## After Connection ### Waiting Period After completing the connection process: * **Business Applications**: Data syncs to Pylar Warehouse * **Databases**: Data is indexed for querying **Processing Time**: * Sources with large amounts of historical data may take longer * Pylar will notify you via **email** and **in-app notification** when the sync/indexing is complete ### You're Ready to Query Once the connection is established and processing is complete: * Use the connection name in your SQL queries * Join data across different sources * Create views using connected data * Build MCP tools on your views ## Prerequisites ### Required Role To connect data sources, you must have at least **Analyst role privileges** in Pylar. ### Credentials For databases and data warehouses, you need: * Access to connection credentials * Database/warehouse administrator access (to whitelist IPs if needed) * Or invite a team member who has these credentials ## Security ### How Pylar Protects Your Data * **Encryption**: Default encryption for all data * **Secret Management**: Credentials stored in Google Cloud Platform's Secret Key Manager * **HTTPS**: All API interactions use HTTPS * **Access Control**: Stringent access controls on all data ### Additional Security Options * **Dedicated User Accounts**: Create database users specifically for Pylar * **Limited Views**: Grant access only to specific database views * **Audit Logging**: Monitor all queries executed by Pylar * **SSH Tunnels**: Use SSH connections for enhanced security (see SSH Connections guide) ## Next Steps Ready to connect your first data source? * [Supported Data Sources](/learn/making-connections/supported-data-sources) - See all available connections * [Connecting BigQuery](/learn/making-connections/connecting-bigquery) - Connect to BigQuery * [Connecting Snowflake](/learn/making-connections/connecting-snowflake) - Connect to Snowflake * [Connecting PostgreSQL](/learn/making-connections/connecting-postgresql) - Connect to PostgreSQL See all available data sources you can connect # Supported Data Sources Source: https://docs.pylar.ai/learn/making-connections/supported-data-sources Complete list of data sources supported by Pylar, including databases, data warehouses, and business applications ## Overview Pylar supports a wide range of data sources, from databases and data warehouses to business applications. This page provides a comprehensive list of all supported sources. ## Databases and Data Warehouses These sources are indexed for querying while your data remains in its original location: ### Cloud Data Warehouses * **BigQuery** - Google's serverless data warehouse * **Snowflake** - Cloud data platform * **Amazon Redshift** - AWS data warehouse * **MotherDuck** - Serverless analytics platform * **Databricks** - Unified analytics platform ### Relational Databases * **PostgreSQL** - Open-source relational database * **MySQL** - Popular open-source database * **AlloyDB** - Google Cloud's PostgreSQL-compatible database * **Supabase** - Hosted PostgreSQL service ### Additional Databases * **Microsoft SQL Server** * **Oracle Database** * And more... For databases and data warehouses, your data stays in its original location. Pylar indexes it for easier querying and executes queries on your infrastructure. ## Business Applications These sources sync data to Pylar Warehouse: ### CRM and Sales * **Salesforce** - Customer relationship management * **HubSpot** - Marketing and sales platform ### Collaboration and Productivity * **Google Sheets** - Spreadsheet application * **Airtable** - Database and collaboration platform ### Analytics and Marketing * **Amplitude** - Product analytics * **Mixpanel** - Product analytics * **Segment** - Customer data platform ### Additional Applications * And many more business applications... Business Applications sync their data to Pylar Warehouse, enabling fast querying and analysis within Pylar's infrastructure. ## Connection Types Comparison | Feature | Business Applications | Databases/Data Warehouses | | ------------------ | ------------------------- | -------------------------- | | Data Location | Synced to Pylar Warehouse | Stays in original location | | Query Execution | On Pylar infrastructure | On your infrastructure | | Data Freshness | Periodic syncs | Real-time queries | | Cross-Source Joins | Supported | Supported | | Setup Complexity | Simple (OAuth usually) | Requires credentials | | IP Whitelisting | Usually not required | Often required | ## IP Address for Whitelisting For databases and data warehouses that require IP whitelisting: **Pylar IP Address**: `34.122.205.142` This is a permanently assigned IP address. Whitelist it in your database firewall settings to allow Pylar to connect. Most databases and data warehouses require whitelisting Pylar's IP address (34.122.205.142) in your firewall settings. This is crucial for establishing a secure connection. ## Connection Guides ### Databases and Data Warehouses * [BigQuery](/learn/making-connections/connecting-bigquery) - Google Cloud data warehouse * [Snowflake](/learn/making-connections/connecting-snowflake) - Cloud data platform * [PostgreSQL](/learn/making-connections/connecting-postgresql) - Open-source database * [MySQL](/learn/making-connections/connecting-mysql) - Popular database * [Redshift](/learn/making-connections/connecting-redshift) - AWS data warehouse * [MotherDuck](/learn/making-connections/connecting-motherduck) - Serverless analytics * [Supabase](/learn/making-connections/connecting-supabase) - Hosted PostgreSQL ### Advanced Connections * [SSH Connections](/learn/making-connections/connecting-via-ssh) - Secure SSH tunnel connections ## Choosing the Right Source Type ### Use Business Applications When * You want data synced to Pylar for fast querying * You need simple, OAuth-based authentication * You're working with SaaS application data * You want automated data refreshes ### Use Databases/Data Warehouses When * You want to query data in place * You need real-time data access * You have existing database infrastructure * You want to avoid data duplication * You need to join across multiple sources ## Connection Naming When connecting sources, follow these naming rules: * ✅ **Allowed**: Lowercase letters, numbers, underscores * ❌ **Not Allowed**: Capital letters, special characters, spaces **Examples**: * ✅ `production_db` * ✅ `snowflake_analytics` * ✅ `customer_data_v2` * ❌ `Production DB` * ❌ `snowflake-analytics` * ❌ `Customer Data` Use descriptive names that indicate the source and purpose. This name will be used in SQL queries to reference the connection. ## Multiple Connections You can connect: * **Multiple instances** of the same source type (e.g., multiple Google Sheets) * **Different sources** to the same workspace * **Same source** to different workspaces Each connection must have a **unique name** within your workspace. ## Next Steps Ready to connect a specific source? * [Connecting BigQuery](/learn/making-connections/connecting-bigquery) - Step-by-step BigQuery guide * [Connecting Snowflake](/learn/making-connections/connecting-snowflake) - Step-by-step Snowflake guide * [Connecting PostgreSQL](/learn/making-connections/connecting-postgresql) - Step-by-step PostgreSQL guide * [Connection Security](/learn/making-connections/connection-security) - Security best practices Get started with connecting your first database # Troubleshooting Connections Source: https://docs.pylar.ai/learn/making-connections/troubleshooting-connections Common connection issues and solutions for connecting data sources to Pylar ## Overview This guide helps you troubleshoot common issues when connecting data sources to Pylar. Follow these solutions to resolve connection problems quickly. ## Common Connection Issues ### Connection Timeout Errors **Symptoms**: Connection attempts timeout or fail to connect **Common Causes**: * IP address not whitelisted * Firewall blocking connections * Network connectivity issues * Database server not accessible **Solutions**: 1. **Verify IP Whitelisting**: * Ensure Pylar IP `34.122.205.142` is whitelisted * Check firewall rules allow the database port * Verify security group settings (for cloud databases) 2. **Check Network Connectivity**: * Verify database server is running * Test connection from your local machine * Check if database is publicly accessible * Review network routing 3. **Verify Port Configuration**: * Check port number is correct * Ensure port is open in firewall * Verify database is listening on the port ### Authentication Failures **Symptoms**: "Authentication failed" or "Access denied" errors **Common Causes**: * Incorrect username or password * User account locked or disabled * Insufficient permissions * Credentials expired **Solutions**: 1. **Verify Credentials**: * Double-check username spelling * Verify password is correct (no extra spaces) * Test credentials in database client * Reset password if needed 2. **Check User Status**: * Verify user account is active * Check if account is locked * Review user permissions * Ensure user has database access 3. **Review Permissions**: * Verify user has SELECT permissions * Check schema-level permissions * Review table-level access * Grant necessary permissions ### Network Issues **Symptoms**: "Connection refused" or "Network unreachable" errors **Common Causes**: * Database not publicly accessible * VPN or private network restrictions * DNS resolution issues * Network security policies **Solutions**: 1. **Database Accessibility**: * Verify database is publicly accessible * Check if database is in private VPC * Configure network access if needed * Use SSH tunnel for private databases 2. **DNS Issues**: * Verify hostname resolves correctly * Try using IP address instead of hostname * Check DNS configuration * Review network settings 3. **Network Policies**: * Review security group rules * Check firewall configurations * Verify network routing * Review cloud provider network settings ### Permission Errors **Symptoms**: "Permission denied" or "Access denied" when querying **Common Causes**: * User lacks necessary permissions * Database-level restrictions * Schema-level access controls * Table-level permissions **Solutions**: 1. **Grant Permissions**: ```sql theme={null} -- Example for PostgreSQL GRANT SELECT ON schema_name.table_name TO pylar_user; GRANT USAGE ON SCHEMA schema_name TO pylar_user; ``` 2. **Review Access Controls**: * Check database user permissions * Review schema access * Verify table-level permissions * Check row-level security policies 3. **Test Permissions**: * Test queries directly in database * Verify user can access tables * Check for any access restrictions ## Database-Specific Issues ### BigQuery Issues **Issue**: Service account JSON invalid **Solutions**: * Verify JSON is complete and valid * Check service account has proper roles * Ensure JSON key hasn't expired * Regenerate JSON key if needed **Issue**: Project ID not found **Solutions**: * Verify Project ID is correct * Check project exists in Google Cloud * Ensure service account has project access * Review project permissions ### Snowflake Issues **Issue**: Account URL format incorrect **Solutions**: * Remove `https://` prefix * Remove everything after `.snowflakecomputing.com` * Verify account identifier is correct * Check URL format matches requirements **Issue**: Network policy blocking **Solutions**: * Add IP `34.122.205.142` to network policy * Verify network policy is applied * Check account-level network settings * Review user network restrictions ### PostgreSQL/MySQL Issues **Issue**: Connection refused **Solutions**: * Verify database is publicly accessible * Check `pg_hba.conf` or MySQL user hosts * Ensure IP is whitelisted * Review firewall rules **Issue**: Port not accessible **Solutions**: * Verify port number (5432 for PostgreSQL, 3306 for MySQL) * Check firewall allows port * Ensure database is listening on port * Review security group settings ### Redshift Issues **Issue**: Endpoint URL format **Solutions**: * Remove port from endpoint (everything after `:`) * Enter port separately (default 5439) * Verify endpoint format is correct * Check cluster is publicly accessible **Issue**: Security group blocking **Solutions**: * Add IP `34.122.205.142` to security group * Allow Redshift protocol (TCP port 5439) * Verify security group is attached to cluster * Review VPC network settings ## Debugging Tips ### Test Connection Manually Before troubleshooting in Pylar, test the connection manually: **PostgreSQL/MySQL**: ```bash theme={null} psql -h hostname -p port -U username -d database_name # or mysql -h hostname -P port -u username -p database_name ``` **BigQuery**: ```bash theme={null} bq query --use_legacy_sql=false "SELECT 1" ``` ### Check Connection Logs * Review Pylar connection logs * Check database server logs * Review firewall/security group logs * Look for specific error messages ### Verify Network Connectivity ```bash theme={null} # Test if port is accessible telnet hostname port # or nc -zv hostname port ``` ### Test Credentials * Test credentials in database client * Verify credentials work from command line * Check if credentials have necessary permissions ## Getting Help If you've tried troubleshooting and still have issues: 1. **Check Documentation**: Review specific connection guides 2. **Review Error Messages**: Look for specific error codes 3. **Contact Support**: Reach out with: * Connection type * Error message * Steps you've tried * Relevant logs ## Prevention Tips ### Before Connecting * ✅ Verify you have correct credentials * ✅ Check IP whitelisting requirements * ✅ Ensure database is accessible * ✅ Review permission requirements ### After Connecting * ✅ Test connection immediately * ✅ Verify data appears correctly * ✅ Monitor connection health * ✅ Set up alerts for failures ## Next Steps * [Connection Security](/learn/making-connections/connection-security) - Secure your connections * [Managing Connections](/learn/making-connections/managing-connections) - Manage your connections * [SSH Connections](/learn/making-connections/connecting-via-ssh) - Enhanced security option Learn security best practices # Overview Source: https://docs.pylar.ai/learn/publishing-tools/overview Introduction to publishing MCP tools - make your tools available to AI agents through secure connection details ## What Is Publishing? Publishing your MCP tools makes them available to AI agents. When you publish, Pylar generates secure connection credentials that you can use to connect your tools to any agent builder or LLM workflow. ```mermaid theme={null} graph LR TOOLS[MCP Tools
Built on Views] PUBLISH[Publish
Generate Token] ENDPOINT[MCP HTTP Stream URL
+ Bearer Token] AG1[Claude Desktop] AG2[Cursor] AG3[LangGraph] AG4[Zapier] TOOLS --> PUBLISH PUBLISH --> ENDPOINT ENDPOINT --> AG1 ENDPOINT --> AG2 ENDPOINT --> AG3 ENDPOINT --> AG4 style PUBLISH fill:#FF4017,stroke:#CC3300,color:#fff style ENDPOINT fill:#FF4017,stroke:#CC3300,color:#fff ``` ## The Publishing Process ### Step 1: Publish Your Tools Click the **"Publish"** button in the right sidebar to make your tools available. ### Step 2: Generate Access Credentials Pylar generates secure authentication tokens for your tools. ### Step 3: Copy Connection Details You'll receive: * **MCP HTTP Stream URL**: The endpoint agents use to connect * **Authorization Bearer Token**: Secure authentication credential ### Step 4: Connect to Agent Builders Paste these credentials into your agent builder (Claude Desktop, Cursor, Windsurf, etc.) ## What You Get ### MCP HTTP Stream URL The URL where your MCP server is accessible: ``` https://mcp.publish.pylar.ai/mcp ``` This is the endpoint that agent builders connect to. ### Authorization Bearer Token A secure token that authenticates access to your tools: ``` Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` This token provides secure access to your published tools. Keep your Bearer Token secure. Never share it publicly or commit it to version control. It provides access to your data. ## Security ### Token Security * Tokens are unique to your project * Regenerate tokens if compromised * Tokens provide access to your published tools * Store tokens securely ### Access Control * Only published tools are accessible * Views remain secure (agents only access through tools) * All queries are logged and auditable * You control what data is exposed ## After Publishing ### Automatic Updates When you update your tools: * Changes reflect automatically * No need to republish * Agents see updates immediately * No downtime required ### Monitoring Use Evals to see: * How agents use your tools * Query patterns and performance * Errors and successes * Usage analytics ## Next Steps Ready to publish your tools? * [Publishing Your Tools](/learn/publishing-tools/publishing-your-tools) - Step-by-step publishing guide * [Getting Your Credentials](/learn/publishing-tools/getting-your-credentials) - Understanding connection details * [Connecting to Agent Builders](/learn/publishing-tools/connecting-claude-desktop) - Connect to your agent Step-by-step guide to publishing your MCP tools # Publishing Your Tools Source: https://docs.pylar.ai/learn/publishing-tools/publishing-your-tools Step-by-step guide to publishing your MCP tools and generating secure access credentials ## Prerequisites Before publishing, ensure: * ✅ Your MCP tools are created and tested * ✅ Tools work correctly (tested successfully) * ✅ You're ready to make tools available to agents Only publish tools that have been tested and verified to work correctly. Publishing untested tools can lead to agent errors. ## Step 1: Publish Your Tools ### Access the Publish Button 1. Navigate to your project in Pylar 2. Look for the **"Publish"** button in the right sidebar 3. Click **"Publish"** to begin Publish MCP tools screen in Pylar showing publish button and tool list ### What Happens When you click Publish: * Pylar prepares your tools for deployment * Validates all tool configurations * Generates secure access credentials * Makes tools available via MCP server ## Step 2: Generate Access Credentials After clicking Publish, a popup window appears. ### Generate Token 1. In the popup, click **"Generate Token"** 2. Pylar creates a secure authorization token 3. The token is unique to your project 4. Token provides secure access to your tools Authorization Bearer Token generation screen showing MCP HTTP Stream URL and token Tokens are generated securely and can be regenerated if needed. Store them safely and never share publicly. ## Step 3: Copy Connection Details Once the token is generated, you'll see two critical values: ### MCP HTTP Stream URL The URL where your MCP server is accessible: ``` https://mcp.publish.pylar.ai/mcp ``` **What it's for**: Agent builders use this URL to connect to your MCP server. ### Authorization Bearer Token The authentication token for secure access: ``` Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` **What it's for**: Provides secure authentication when agents connect to your tools. Copy both values carefully. You'll need both to connect your tools to agent builders. The Bearer Token should be kept secure. ## Step 4: Store Credentials Safely ### Security Best Practices * ✅ **Store Securely**: Use password managers or secure storage * ✅ **Don't Share Publicly**: Never commit tokens to version control * ✅ **Regenerate if Compromised**: Generate new tokens if exposed * ✅ **Limit Access**: Only share with authorized team members ### Where to Store * Password manager (1Password, LastPass, etc.) * Secure team documentation (with access controls) * Environment variables (for programmatic access) * Secure configuration files (never commit to git) ## Understanding Your Credentials ### MCP HTTP Stream URL This is the standard endpoint for MCP servers: * **Format**: `https://mcp.publish.pylar.ai/mcp` * **Purpose**: Agent builders connect here * **Protocol**: Uses MCP (Model Context Protocol) * **Security**: Protected by Bearer Token authentication The MCP HTTP Stream URL is the same for all Pylar projects. Your Bearer Token is what makes your connection unique and secure. ### Authorization Bearer Token This token authenticates your connection: * **Format**: `Bearer ` * **Purpose**: Proves authorized access * **Scope**: Provides access to your published tools * **Security**: Keep it secret and secure ### How They Work Together 1. Agent builder connects to MCP HTTP Stream URL 2. Sends Authorization Bearer Token in request headers 3. Pylar validates the token 4. Grants access to your published tools 5. Agent can now call your tools ## What Gets Published When you publish: * ✅ **All MCP Tools**: All tools in your project become available * ✅ **Underlying Views**: Tools can query their associated views * ✅ **Real-time Access**: Tools are immediately accessible * ✅ **Automatic Updates**: Changes to tools reflect automatically After publishing, your tools are live and ready for agents to use. You can update tools anytime without republishing. ## Next Steps Now that your tools are published: * [Getting Your Credentials](/learn/publishing-tools/getting-your-credentials) - Detailed guide to connection details * [Connecting to Claude Desktop](/learn/publishing-tools/connecting-claude-desktop) - Connect to Claude Desktop * [Connecting to Cursor](/learn/publishing-tools/connecting-cursor) - Connect to Cursor * [Connecting to Windsurf](/learn/publishing-tools/connecting-windsurf) - Connect to Windsurf Learn how to connect your tools to agent builders