
Kibana Agent Builder
- 2 installs
- 31 repo stars
- Updated May 28, 2026
- elastic/cursor-plugins
This is a copy of kibana-agent-builder by elastic - installs and ranking accrue to the original listing.
Helps with ai & agent building tasks.
About
kibana-agent-builder is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- kibana-agent-builder
- AI & Agent Building
- AI-coding skill
Kibana Agent Builder by the numbers
- 2 all-time installs (skills.sh)
- Data as of Jul 24, 2026 (Skillselion catalog sync)
npx skills add https://github.com/elastic/cursor-plugins --skill kibana-agent-builderAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 31 |
| Last updated | May 28, 2026 |
| Repository | elastic/cursor-plugins ↗ |
What it does
Helps with ai & agent building tasks.
Files
Manage Agent Builder Agents and Tools in Kibana
Create, update, delete, inspect, and chat with Agent Builder agents. Create, update, delete, list, and test custom tools (ES|QL, index search, workflow). If the user provided a name, use $ARGUMENTS as the default agent name.
Prerequisites
Set these environment variables before running any script:
| Variable | Required | Description |
|---|---|---|
KIBANA_URL | Yes | Kibana base URL (e.g., https://my-deployment.kb.us-east-1.aws.elastic.cloud) |
KIBANA_API_KEY | No | API key for authentication (preferred) |
KIBANA_USERNAME | No | Username for basic auth (falls back to ELASTICSEARCH_USERNAME) |
KIBANA_PASSWORD | No | Password for basic auth (falls back to ELASTICSEARCH_PASSWORD) |
KIBANA_SPACE_ID | No | Kibana space ID (omit for default space) |
KIBANA_INSECURE | No | Set to true to skip TLS verification |
Provide either KIBANA_API_KEY or KIBANA_USERNAME + KIBANA_PASSWORD.
Agent Management
Create an Agent
Step 1: List available tools
node skills/kibana/agent-builder/scripts/agent-builder.js list-toolsIf the script reports a connection error, stop and tell the user to verify their KIBANA_URL and authentication environment variables.
Review the list of available tools. Tools prefixed with platform.core. are built-in. Other tools are custom or connector-provided.
Step 2: List existing agents
node skills/kibana/agent-builder/scripts/agent-builder.js list-agentsThis helps avoid name conflicts and shows what is already configured.
Step 3: Gather agent details
Using $ARGUMENTS as the default name, confirm or collect from the user:
1. Name (required) — The agent's display name. Default: $ARGUMENTS. 2. Description (optional) — Brief description of what the agent does. Default: same as name. 3. System instructions (optional) — Custom system prompt for the agent. Default: none.
Step 4: Select tools
Present the available tools from Step 1 and ask the user which ones to include. Suggest a reasonable default based on the agent's purpose. Let the user add or remove tools from the suggested list.
Step 5: Create the agent
node skills/kibana/agent-builder/scripts/agent-builder.js create-agent \
--name "<agent_name>" \
--description "<description>" \
--instructions "<system_instructions>" \
--tool-ids "<tool_id_1>,<tool_id_2>,<tool_id_3>"Where:
--nameis required--tool-idsis a comma-separated list of tool IDs from Step 4--descriptiondefaults to the name if omitted--instructionscan be omitted if the user did not provide any
Step 6: Verify creation
node skills/kibana/agent-builder/scripts/agent-builder.js list-agentsShow the user the newly created agent entry. If it appears, report success. If not, show any error output from Step 5.
Get an Agent
node skills/kibana/agent-builder/scripts/agent-builder.js get-agent --id "<agent_id>"Update an Agent
node skills/kibana/agent-builder/scripts/agent-builder.js update-agent \
--id "<agent_id>" \
--description "<new_description>" \
--instructions "<new_instructions>" \
--tool-ids "<tool_id_1>,<tool_id_2>"All flags except --id are optional — only provided fields are updated. The agent's id and name are immutable.
API constraint: PUT only acceptsdescription,configuration, andtags. Includingid,name, ortype
causes a 400 error.
Delete an Agent
node skills/kibana/agent-builder/scripts/agent-builder.js delete-agent --id "<agent_id>"Always confirm with the user before deleting. Deletion is permanent.
Chat with an Agent
node skills/kibana/agent-builder/scripts/agent-builder.js chat \
--id "<agent_id>" \
--message "<user_message>"Uses the streaming endpoint POST /api/agent_builder/converse/async with agent_id and input in the request body. Output shows [Reasoning], [Tool Call], [Tool Result], and [Response] as events arrive. Pass --conversation-id to continue an existing conversation.
Note: This command may take 30-60 seconds as the agent reasons and calls tools. Use a longer timeout (e.g., 120s or 180s) when running via Bash.
Tool Management
Custom tools extend what agents can do beyond the built-in platform tools.
Tool Types
ES|QL Tools
Pre-defined, parameterized ES|QL queries. Use when you need guaranteed query correctness, enforced business rules, analytics aggregations, or fine-grained data access control.
Parameter syntax: Use ?param_name in the query. Define each parameter with type and description only. Valid types: string, integer, float, boolean, date, array.
{
"id": "campaign_revenue_by_region",
"type": "esql",
"description": "Calculates confirmed revenue for a region by quarter.",
"configuration": {
"query": "FROM finance-orders-* | WHERE order_status == \"completed\" AND region == ?region | STATS total_revenue = SUM(amount) BY quarter | LIMIT 10",
"params": {
"region": {
"type": "string",
"description": "Region code, e.g. 'US', 'EU', 'APAC'"
}
}
}
}Index Search Tools
Scope the built-in search capability to a specific index pattern. The LLM decides how to query; you control which indices are accessible.
{
"id": "customer_feedback_search",
"type": "index_search",
"description": "Searches customer feedback and support tickets.",
"configuration": {
"pattern": "customer-feedback-*"
}
}Workflow Tools
Connect an agent to an Elastic Workflow — a YAML-defined multi-step automation. Use when the agent needs to take action beyond data retrieval (send notifications, create tickets, call external APIs).
{
"id": "investigate-alert-workflow",
"type": "workflow",
"description": "Triggers automated alert investigation.",
"configuration": {
"workflow_id": "security-alert-investigation"
}
}Parameters are auto-detected from the workflow's inputs section.
Tool API Constraints
Read these before creating tools — violations cause 400 errors.
- POST body fields: Only
id,type,description,configuration, andtagsare accepted.nameis not a
valid field — omit it entirely.
- `params` is always required for ES|QL tools, even when empty — use
"params": {}. - Param fields: Only
typeanddescriptionare accepted per parameter.defaultandoptionalare not valid
and cause 400 errors. Hard-code sensible defaults in the query instead.
- Index search config: Use
"pattern", not"index". Using"index"causes a validation error. - PUT restrictions: Only
description,configuration, andtagsare accepted. Includingidortypecauses a
400 error — these fields are immutable after creation.
Tool Script Commands
List all tools
node skills/kibana/agent-builder/scripts/agent-builder.js list-custom-toolsGet a specific tool
node skills/kibana/agent-builder/scripts/agent-builder.js get-tool --id "<tool_id>"Create a tool
node skills/kibana/agent-builder/scripts/agent-builder.js create-tool \
--id "<tool_id>" \
--type "esql" \
--description "<description>" \
--query "<esql_query>" \
--params '{"region": {"type": "string", "description": "Region code"}}'For index search tools:
node skills/kibana/agent-builder/scripts/agent-builder.js create-tool \
--id "<tool_id>" \
--type "index_search" \
--description "<description>" \
--pattern "my-index-*"For workflow tools:
node skills/kibana/agent-builder/scripts/agent-builder.js create-tool \
--id "<tool_id>" \
--type "workflow" \
--description "<description>" \
--workflow-id "my-workflow-name"Update a tool
node skills/kibana/agent-builder/scripts/agent-builder.js update-tool \
--id "<tool_id>" \
--description "<new_description>" \
--query "<new_query>"Only description, configuration, and tags can be updated. id and type are immutable.
Delete a tool
node skills/kibana/agent-builder/scripts/agent-builder.js delete-tool --id "<tool_id>"Test a tool
node skills/kibana/agent-builder/scripts/agent-builder.js test-tool \
--id "<tool_id>" \
--params '{"region": "US"}'Executes the tool via POST /api/agent_builder/tools/_execute and displays column names and row counts for ES|QL results.
Examples
Create an agent
User: /kibana-agent-builder sales-helper1. List tools — finds platform.core.search, platform.core.list_indices, and a custom esql-sales-data tool 2. List agents — no conflicts 3. Name: "sales-helper", Description: "Helps query sales data" 4. Tools: esql-sales-data, platform.core.search, platform.core.list_indices 5. Create with --name "sales-helper" --tool-ids "esql-sales-data,platform.core.search,platform.core.list_indices" 6. Verify — agent appears in list
Update an agent's instructions
User: Update the sales-helper agent to focus on the APAC region1. Get agent — get-agent --id "sales-helper" to see current config 2. Update — update-agent --id "sales-helper" --instructions "Focus on APAC sales data. Use esql-sales-data for queries." 3. Verify — get-agent --id "sales-helper" to confirm new instructions
Chat with an agent
User: Ask sales-helper what the top revenue products are1. Chat — chat --id "sales-helper" --message "What are the top revenue products?" 2. Display the agent's response
Create an ES|QL tool with parameters
User: Create a tool that shows billing complaints by category for the last N days1. Consult the elasticsearch-esql skill for ES|QL syntax 2. Create tool:
node skills/kibana/agent-builder/scripts/agent-builder.js create-tool \
--id "billing_complaint_summary" \
--type "esql" \
--description "Returns billing complaints grouped by sub-category for the last N days." \
--query "FROM customer-feedback-* | WHERE @timestamp >= NOW() - ?days::integer * 1d AND MATCH(feedback_text, 'billing') | STATS count = COUNT(*) BY sub_category | SORT count DESC | LIMIT 10" \
--params '{"days": {"type": "integer", "description": "Number of days to look back"}}'3. Test: test-tool --id "billing_complaint_summary" --params '{"days": 30}'
Create an index search tool
User: Create a tool to search support transcriptsnode skills/kibana/agent-builder/scripts/agent-builder.js create-tool \
--id "transcript_search" \
--type "index_search" \
--description "Searches support call transcripts by topic, agent, or customer issue." \
--pattern "support-transcripts"References
Read these for detailed guidance:
references/architecture-guide.md— Core concepts, built-in tools, context engineering, best practices, token
optimization, REST API endpoints, MCP/A2A integration, permissions
references/use-cases.md— Full playbooks for Customer Feedback Analysis, Marketing Campaign Analysis, and Contract
Analysis agents
For ES|QL syntax, functions, operators, and parameter rules, use the elasticsearch-esql skill. For workflow YAML structure, trigger types, step types, and agent-workflow patterns, use the security-workflows skill.
Guidelines
- Always run
list-toolsbefore creating an agent so the user can choose from real, available tools. - Always run
list-agentsbefore and after creation to detect conflicts and verify success. - Do not invent tool IDs — only use IDs returned by
list-tools. - If no custom tools exist yet, suggest creating one or using the built-in platform tools.
- The agent ID is auto-generated from the name (lowercased, hyphens, alphanumeric only).
- For non-default Kibana spaces, set
KIBANA_SPACE_IDbefore running the script. - Confirm with the user before running
delete-agentordelete-tool— deletion is permanent. - Always include
| LIMIT Nin ES|QL queries to prevent context window overflow. - Write descriptive tool descriptions — the agent decides which tool to call based solely on the description.
- Scope index search tools narrowly (e.g.,
customer-feedback-*not*). - Use
KEEPto return only needed columns and reduce token consumption. - Validate ES|QL queries with
test-toolbefore assigning to an agent. - For ES|QL tools with no parameters, still include
"params": {}.
{
"type": "module"
}
Elastic Agent Builder Architecture Guide
Elastic Agent Builder is a framework built into Elasticsearch/Kibana that creates AI agents grounded in your Elasticsearch data. It combines LLMs with Elasticsearch's search, analytics, and relevance capabilities into a unified platform — no separate vector database, RAG pipeline, or tool orchestrator needed.
Docs: Elastic Agent Builder
Core Concepts
Three Building Blocks
1. Chat UI — A real-time conversational interface (in Kibana or via API) to interact with agents.
2. Agents — LLM-powered entities that follow custom instructions and use tools to answer questions, run analytics, or drive workflows. Two flavors:
- Built-in agents — Pre-configured, ready to chat with your data immediately
- Custom agents — User-defined system prompt + curated toolset + security profile
3. Tools — Modular, reusable functions agents invoke to retrieve or manipulate data. Two flavors:
- Built-in tools (prefixed
platform.core.*) — Ship out of the box - Custom tools — ES|QL tools, index search tools, or workflow tools you define
Built-in Tools Reference
| Tool ID | Purpose |
|---|---|
platform.core.search | Translates natural language into hybrid/semantic/structured queries |
platform.core.list_indices | Lists available indices |
platform.core.get_index_mapping | Retrieves field mappings for an index |
platform.core.get_document_by_id | Fetches a specific document by ID |
platform.core.execute_esql | Generates and executes ES\ |
platform.core.generate_esql | Generates ES\ |
platform.core.index_explorer | Selects the most relevant index from multiple candidates |
platform.core.create_visualization | Creates Kibana visualizations from ES\ |
platform.core.integration_knowledge | Retrieves knowledge from Fleet-installed integrations |
platform.core.product_documentation | Searches Elastic product documentation |
platform.core.search is the primary context retrieval tool — it handles hybrid search automatically (lexical + semantic via ELSER/dense vectors), selecting the right index and query type.
Elasticsearch as a Context Engine
Agent Builder leverages Elasticsearch natively for three context engineering patterns:
1. Improving Context Management
platform.core.searchauto-selects the best index and translates natural language into optimized queries, preventing
context window overflow
- Use index search tools scoped to specific indices to restrict the agent's surface area and reduce noise
- Use
platform.core.index_explorerin multi-index environments to route queries to the right data source - Instruct agents explicitly in their system prompt to use tools rather than rely on training knowledge
2. Persistent Memory Layer
Elasticsearch naturally acts as long-term memory:
- Short-term memory: Agent Builder's built-in chat session tracks conversation history automatically
- Long-term memory: Store agent outputs back to Elasticsearch indices for retrieval in future sessions
- Cross-session context: Index tool outputs to a dedicated memory index, then give the agent an index search tool
scoped to that index to retrieve past reasoning
- Elastic Workflows can automate the write-back of outputs to memory indices
3. Hybrid Search for Relevance
platform.core.search and custom index search tools use Elasticsearch's full hybrid search stack:
- Lexical (BM25) for keyword precision
- Semantic/vector (ELSER sparse vectors or dense embeddings) for conceptual matching
- FORK/FUSE in ES|QL combines multiple search strategies using Reciprocal Rank Fusion (RRF)
- Reranking with Elastic Rerank or third-party models (Cohere, Vertex) for final relevance scoring
- Use
semantic_textfield type to enable out-of-the-box semantic search without managing embeddings manually
Best Practices
Tool Design
- Write descriptive tool descriptions — The agent decides which tool to call based solely on the description. Be
explicit about when to use each tool and include example trigger phrases.
- Scope index search tools narrowly — Prefer
customer-feedback-*over*to reduce noise and limit token
consumption from oversized result sets.
- Include LIMIT in every ES|QL query — The implicit default is 1000 rows, which consumes tokens rapidly and can
trigger context_length_exceeded errors.
- Validate ES|QL before deploying — Use the "Infer parameters from query" button in Kibana UI to auto-detect
parameters and test with sample values.
- Add `_meta.description` to index mappings — Helps
platform.core.searchandplatform.core.index_explorerselect
the right index without calling list_indices first.
Agent Prompt Design
- Explicitly instruct tool use — LLMs sometimes answer from training data instead of calling tools. Add: "Always use
tools to retrieve data. Never answer data questions from memory."
- Name which tool to use for which intent — Vague instructions lead to wrong tool selection. Be specific: "For
sentiment trends, use feedback_sentiment_trend. For individual feedback, use customer_feedback_search."
- Instruct the agent to ask for clarification — Prevents broad queries when a targeted tool would suffice: "If the
user's question is ambiguous about time range, ask for clarification before querying."
Token Optimization
Token costs accumulate from conversation history, tool response payloads, and the number of tool calls per turn.
- Replace broad built-in tools with focused custom tools — Custom tools pre-define the query logic and scope, so the
LLM only controls parameters, not the query shape. This produces smaller, more relevant result sets.
- Limit the toolset assigned to each agent — Every tool in an agent's toolset is included in the system prompt as a
function definition, consuming input tokens on every call — even unused tools. Design agents with the minimum viable toolset.
- Use agent instructions to enforce tool discipline — Even with a focused toolset, an agent may call tools
redundantly. Use the system prompt to create explicit call rules: "For trend questions, ALWAYS use billing_complaint_summary. Do NOT call more than one tool per user question unless the question explicitly asks for two things."
- Keep tool responses small — Use
KEEPto return only needed columns. Prefer aggregations over raw document
retrieval for summary questions.
- Monitor token usage — Agent Builder displays input and output token counts after each response in the Chat UI. Use
the "View JSON" button to inspect the raw usage breakdown per tool call.
Docs: Monitor usage
Troubleshooting:
Context length exceeded
Programmatic Access
REST API Base Path
/api/agent_builder/For Kibana Spaces: /s/<space_name>/api/agent_builder/
Key Endpoints
| Action | Method | Path |
|---|---|---|
| List tools | GET | /api/agent_builder/tools |
| Create tool | POST | /api/agent_builder/tools |
| Update tool | PUT | /api/agent_builder/tools/{toolId} |
| Delete tool | DELETE | /api/agent_builder/tools/{toolId} |
| Execute tool (testing) | POST | /api/agent_builder/tools/_execute |
| List agents | GET | /api/agent_builder/agents |
| Create agent | POST | /api/agent_builder/agents |
| Get agent | GET | /api/agent_builder/agents/{agentId} |
| Update agent | PUT | /api/agent_builder/agents/{agentId} |
| Delete agent | DELETE | /api/agent_builder/agents/{agentId} |
| Chat with agent | POST | /api/agent_builder/converse/async |
MCP & A2A Integration
- MCP server: Exposes all built-in and custom tools to any MCP client (Claude Desktop, Cursor, VS Code). Provide
your Kibana URL + API key in the client config.
- A2A server: Exposes agents to external agent frameworks, services, and apps — enabling reuse of your Elastic
context engineering logic across integrations.
Permissions & Security
- Tools and agents respect Elasticsearch RBAC — the API key used scopes what data is accessible
- MCP and A2A support OAuth and custom authentication mechanisms
- Custom ES|QL tools provide guardrails by pre-defining query structure — only parameters are LLM-controlled, not query
logic
Elastic Agent Builder — Use Case Playbooks
---
1. Customer Feedback Analysis Agent
Goal: Analyze customer feedback, identify sentiment trends, surface policy-related mentions, and generate analytics.
Key Tools:
platform.core.search— semantic search over feedback indices for open-ended queries- Custom Index Search tool scoped to
customer-feedback-*— focused retrieval - Custom ES|QL tool for sentiment aggregations and trend analytics
Custom Index Search Tool
POST /api/agent_builder/tools
{
"id": "customer_feedback_search",
"type": "index_search",
"description": "Searches customer feedback, support tickets, and NPS responses. Use this to find sentiment, product complaints, praise, or policy mentions. Supports semantic and keyword search.",
"configuration": {
"pattern": "customer-feedback-*"
}
}Custom ES|QL Tool — Sentiment Trend by Product
POST /api/agent_builder/tools
{
"id": "feedback_sentiment_trend",
"type": "esql",
"description": "Returns a breakdown of positive vs. negative feedback counts by product category over a given number of days. Use for trend analysis, not for reading individual feedback.",
"configuration": {
"query": "FROM customer-feedback-* | WHERE @timestamp >= NOW() - ?lookback_days::integer * 1d | STATS positive = COUNT(*) WHERE sentiment == \"positive\", negative = COUNT(*) WHERE sentiment == \"negative\", total = COUNT(*) BY product_category | SORT negative DESC | LIMIT 20",
"params": {
"lookback_days": {
"type": "integer",
"description": "Number of days to look back, e.g. 7, 30, 90"
}
}
}
}Custom ES|QL Tool — Policy Compliance Check
POST /api/agent_builder/tools
{
"id": "policy_mention_search",
"type": "esql",
"description": "Counts how many feedback items mention a specific policy keyword. Use for compliance monitoring or to understand which policies generate the most customer friction.",
"configuration": {
"query": "FROM customer-feedback-* | WHERE MATCH(feedback_text, ?policy_keyword) | STATS mention_count = COUNT(*), avg_sentiment_score = AVG(sentiment_score) BY product_category | SORT mention_count DESC | LIMIT 15",
"params": {
"policy_keyword": {
"type": "string",
"description": "Policy term or keyword to search for, e.g. 'refund policy', 'cancellation', 'data privacy'"
}
}
}
}Agent Definition
POST /api/agent_builder/agents
{
"id": "customer-feedback-agent",
"name": "Customer Feedback Analyst",
"description": "Analyzes customer sentiment, surfaces policy friction points, and provides product feedback trends.",
"configuration": {
"instructions": "You are a customer intelligence analyst. Always use tools to ground your responses in real data — do not answer from memory. For open questions about specific feedback, use customer_feedback_search. For trend analytics or policy mentions, use the ES|QL tools. When presenting findings, include counts and percentages where available.",
"tools": [
{
"tool_ids": [
"customer_feedback_search",
"feedback_sentiment_trend",
"policy_mention_search",
"platform.core.search"
]
}
]
}
}---
2. Marketing Campaign Analysis Agent
Goal: Analyze campaign performance, compare results across campaigns, and join campaign metadata with outcome data using ES|QL LOOKUP JOIN.
Key Tools:
platform.core.search— broad semantic retrieval across marketing indices- Custom Index Search tool scoped to campaign description indices
- Custom ES|QL tools that join campaign description + results indices
Custom Index Search Tool — Campaign Descriptions
POST /api/agent_builder/tools
{
"id": "campaign_description_search",
"type": "index_search",
"description": "Search marketing campaign descriptions, objectives, target audiences, and creative briefs. Use to understand what a campaign was about or find campaigns matching specific criteria.",
"configuration": {
"pattern": "marketing-campaigns-*"
}
}Custom ES|QL Tool — Campaign Performance Join
POST /api/agent_builder/tools
{
"id": "campaign_performance_analysis",
"type": "esql",
"description": "Joins campaign descriptions with performance results to analyze ROI, conversion rates, and spend efficiency for campaigns in a given channel over a lookback period. Use when the user asks about campaign effectiveness, ROI, or performance comparisons.",
"configuration": {
"query": "FROM marketing-campaign-results-* | WHERE channel == ?channel AND @timestamp >= NOW() - ?lookback_days::integer * 1d | STATS total_spend = SUM(spend), total_conversions = SUM(conversions), total_impressions = SUM(impressions), avg_ctr = AVG(click_through_rate) BY campaign_id | LOOKUP JOIN marketing-campaigns-* ON campaign_id | EVAL roi = (total_conversions * ?revenue_per_conversion - total_spend) / total_spend * 100 | SORT roi DESC | LIMIT 10",
"params": {
"channel": {
"type": "string",
"description": "Marketing channel, e.g. 'email', 'social', 'paid_search', 'display'"
},
"lookback_days": {
"type": "integer",
"description": "Number of days to look back, e.g. 30, 90, 365"
},
"revenue_per_conversion": {
"type": "float",
"description": "Assumed revenue value per conversion for ROI calculation"
}
}
}
}Custom ES|QL Tool — Audience Segment Performance
POST /api/agent_builder/tools
{
"id": "audience_segment_performance",
"type": "esql",
"description": "Analyzes which audience segments perform best for a given campaign. Use when the user asks about targeting effectiveness or audience insights.",
"configuration": {
"query": "FROM marketing-campaign-results-* | WHERE campaign_id == ?campaign_id | STATS conversions = SUM(conversions), spend = SUM(spend), impressions = SUM(impressions) BY audience_segment | EVAL cost_per_conversion = spend / conversions | SORT conversions DESC | LIMIT 15",
"params": {
"campaign_id": {
"type": "string",
"description": "The campaign ID to analyze"
}
}
}
}Agent Definition
POST /api/agent_builder/agents
{
"id": "marketing-campaign-agent",
"name": "Marketing Campaign Analyst",
"description": "Analyzes marketing campaign effectiveness, compares ROI across campaigns and channels, and surfaces audience insights.",
"configuration": {
"instructions": "You are a marketing analytics expert. Always call tools for data — never answer from memory. For qualitative questions about what a campaign was about, use campaign_description_search. For performance metrics and ROI, use campaign_performance_analysis. For audience breakdowns, use audience_segment_performance. When showing results, present a concise summary with the most important metrics highlighted, then offer to drill down further.",
"tools": [
{
"tool_ids": [
"campaign_description_search",
"campaign_performance_analysis",
"audience_segment_performance",
"platform.core.search"
]
}
]
}
}---
3. Contract Analysis Agent
Goal: Search a large corpus of contracts for specific clause mentions, identify non-standard terms, and surface risk patterns using hybrid search + ES|QL analytics.
Key Design: Hybrid search finds contracts with relevant clauses (using semantic + lexical matching). ES|QL tools then extract and analyze specific term patterns across the corpus.
Custom Index Search Tool — Contract Hybrid Search
POST /api/agent_builder/tools
{
"id": "contract_search",
"type": "index_search",
"description": "Searches the full contract corpus using hybrid search (semantic + keyword). Use to find contracts mentioning specific clauses, obligations, parties, or terms.",
"configuration": {
"pattern": "contracts-*"
}
}Custom ES|QL Tool — Clause Frequency Analysis
POST /api/agent_builder/tools
{
"id": "clause_frequency_analysis",
"type": "esql",
"description": "Counts how many contracts contain a specific clause or term keyword, grouped by contract type or counterparty category. Use for corpus-wide analysis of how common a clause is.",
"configuration": {
"query": "FROM contracts-* | WHERE MATCH(contract_text, ?clause_keyword) | STATS contract_count = COUNT(*), counterparty_types = COUNT_DISTINCT(counterparty_category) BY contract_type | SORT contract_count DESC | LIMIT 20",
"params": {
"clause_keyword": {
"type": "string",
"description": "Clause or term to search for, e.g. 'limitation of liability', 'force majeure', 'auto-renewal'"
}
}
}
}Custom ES|QL Tool — Liability Cap Outlier Detection
POST /api/agent_builder/tools
{
"id": "liability_cap_outliers",
"type": "esql",
"description": "Identifies contracts where the liability cap falls significantly above or below the norm for a given contract type. Use to find non-standard commercial terms that may need review.",
"configuration": {
"query": "FROM contracts-* | WHERE contract_type == ?contract_type | STATS median_val = MEDIAN(liability_cap_usd), p25 = PERCENTILE(liability_cap_usd, 25), p75 = PERCENTILE(liability_cap_usd, 75) BY contract_type | ENRICH contracts-stats ON contract_type | EVAL low_threshold = p25 * 0.5, high_threshold = p75 * 2.0 | KEEP contract_type, median_val, low_threshold, high_threshold | LIMIT 20",
"params": {
"contract_type": {
"type": "string",
"description": "Type of contract, e.g. 'vendor', 'customer', 'employment', 'nda'"
}
}
}
}Note on outlier detection in ES|QL: ES|QL parameters are values only — they cannot be used as dynamic field
references. Design separate tools for each numeric field you want to analyze (e.g., liability_cap_outliers,payment_terms_outliers). For dynamic outlier detection, use two separate queries (first to compute stats, then tofilter outliers) or pre-compute thresholds into a lookup index.
Custom ES|QL Tool — Expiry & Renewal Risk
POST /api/agent_builder/tools
{
"id": "contract_expiry_risk",
"type": "esql",
"description": "Lists contracts expiring within a specified number of days, including renewal terms and responsible owners. Use for contract lifecycle management or renewal risk analysis.",
"configuration": {
"query": "FROM contracts-* | WHERE expiry_date <= NOW() + ?days_ahead::integer * 1d AND expiry_date >= NOW() | STATS count = COUNT(*) BY contract_owner, auto_renewal, contract_type | SORT count DESC | LIMIT 50",
"params": {
"days_ahead": {
"type": "integer",
"description": "Number of days to look ahead for expiring contracts, e.g. 30, 60, 90"
}
}
}
}Agent Definition
POST /api/agent_builder/agents
{
"id": "contract-analysis-agent",
"name": "Contract Analysis Agent",
"description": "Searches contract corpus for clause mentions, identifies non-standard terms, and surfaces renewal and risk patterns.",
"configuration": {
"instructions": "You are a contract intelligence analyst. Always use tools — never answer from your training data. For finding specific contracts or clauses, use contract_search (hybrid search). For understanding how common a clause is across the corpus, use clause_frequency_analysis. For identifying unusual liability caps, use liability_cap_outliers. For renewal risk, use contract_expiry_risk. When presenting findings, be precise: cite counts, percentages, and specific contract IDs where relevant.",
"tools": [
{
"tool_ids": [
"contract_search",
"clause_frequency_analysis",
"liability_cap_outliers",
"contract_expiry_risk",
"platform.core.search"
]
}
]
}
}#!/usr/bin/env node
/**
* Agent Builder CLI wrapping the Kibana Agent Builder REST API.
* Manages agents and custom tools: list, get, create, update, delete, test, and chat.
*/
import { kibanaGet, kibanaPost, kibanaPut, kibanaDelete, getKibanaConfig } from "./kibana-client.js";
function parseArgs(argv) {
const result = {};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg.startsWith("--")) {
const key = arg.slice(2).replace(/-/g, "_");
const next = argv[i + 1];
if (next !== undefined && !next.startsWith("--")) {
result[key] = next;
i++;
} else {
result[key] = true;
}
}
}
return result;
}
const API_BASE = "/api/agent_builder";
async function listTools() {
const data = await kibanaGet(`${API_BASE}/tools`);
const tools = data.results || data;
console.log(`Available tools (${tools.length}):`);
console.log("");
for (const tool of tools) {
const tags = (tool.tags || []).length > 0 ? ` [${tool.tags.join(", ")}]` : "";
const desc = tool.description ? ` — ${tool.description}` : "";
console.log(` ${tool.id}${tags}${desc}`);
}
}
async function listAgents() {
const data = await kibanaGet(`${API_BASE}/agents`);
const agents = data.results || data;
console.log(`Existing agents (${agents.length}):`);
console.log("");
if (agents.length === 0) {
console.log(" (none)");
return;
}
for (const agent of agents) {
const toolCount = agent.configuration?.tools?.[0]?.tool_ids?.length || 0;
const readonly = agent.readonly ? "readonly" : "editable";
console.log(` ${agent.id}\t${agent.name}\t${toolCount} tools\t${readonly}`);
}
}
async function getAgent(args) {
const id = args.id;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
const data = await kibanaGet(`${API_BASE}/agents/${encodeURIComponent(id)}`);
console.log(JSON.stringify(data, null, 2));
}
async function createAgent(args) {
const name = args.name;
if (!name) {
console.error("Error: --name is required.");
process.exit(1);
}
const toolIds = args.tool_ids;
if (!toolIds) {
console.error("Error: --tool-ids is required.");
process.exit(1);
}
const description = args.description || name;
const instructions = args.instructions || "";
// Generate an ID from the name: lowercase, replace spaces/underscores with hyphens, strip non-alphanumeric
const agentId = name
.toLowerCase()
.replace(/[\s_]+/g, "-")
.replace(/[^a-z0-9-]/g, "");
const toolIdList = toolIds
.split(",")
.map((id) => id.trim())
.filter(Boolean);
if (toolIdList.length === 0) {
console.error("Error: --tool-ids must contain at least one non-empty tool ID.");
process.exit(1);
}
const payload = {
id: agentId,
name,
description,
configuration: {
instructions,
tools: [{ tool_ids: toolIdList }],
},
};
const result = await kibanaPost(`${API_BASE}/agents`, payload);
console.log("Agent created successfully!");
console.log(JSON.stringify(result, null, 2));
}
async function updateAgent(args) {
const id = args.id;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
// Fetch current agent to merge with updates
const current = await kibanaGet(`${API_BASE}/agents/${encodeURIComponent(id)}`);
// Build payload — only description, configuration, and tags are accepted by PUT
const payload = {};
if (args.description) {
payload.description = args.description;
}
const config = { ...current.configuration };
if (args.instructions) {
config.instructions = args.instructions;
}
if (args.tool_ids) {
const toolIdList = args.tool_ids
.split(",")
.map((tid) => tid.trim())
.filter(Boolean);
config.tools = [{ tool_ids: toolIdList }];
}
payload.configuration = config;
const result = await kibanaPut(`${API_BASE}/agents/${encodeURIComponent(id)}`, payload);
console.log("Agent updated successfully!");
console.log(JSON.stringify(result, null, 2));
}
async function deleteAgent(args) {
const id = args.id;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
await kibanaDelete(`${API_BASE}/agents/${encodeURIComponent(id)}`);
console.log(`Agent "${id}" deleted successfully.`);
}
async function chat(args) {
const id = args.id;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
const message = args.message;
if (!message) {
console.error("Error: --message is required.");
process.exit(1);
}
const payload = { agent_id: id, input: message };
if (args.conversation_id) {
payload.conversation_id = args.conversation_id;
}
const config = getKibanaConfig();
let baseUrl = config.url.replace(/\/$/, "");
if (config.spaceId && config.spaceId !== "default") {
baseUrl += `/s/${config.spaceId}`;
}
const headers = { "Content-Type": "application/json", "kbn-xsrf": "true", "User-Agent": "elastic-agentic" };
if (config.apiKey) {
headers["Authorization"] = `ApiKey ${config.apiKey}`;
} else if (config.username && config.password) {
const auth = Buffer.from(`${config.username}:${config.password}`).toString("base64");
headers["Authorization"] = `Basic ${auth}`;
}
if (config.insecure) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
}
const response = await fetch(`${baseUrl}${API_BASE}/converse/async`, {
method: "POST",
headers,
body: JSON.stringify(payload),
});
if (!response.ok) {
const text = await response.text();
throw new Error(`HTTP ${response.status}: ${text}`);
}
let eventType = "";
let buffer = "";
for await (const chunk of response.body) {
buffer += new TextDecoder().decode(chunk);
const lines = buffer.split("\n");
buffer = lines.pop();
for (const raw of lines) {
const line = raw.replace(/\r$/, "");
if (line.startsWith(":") || line === "") continue;
if (line.startsWith("event: ")) {
eventType = line.slice(7);
continue;
}
if (line.startsWith("data: ")) {
const data = JSON.parse(line.slice(6)).data;
switch (eventType) {
case "conversation_id_set":
console.log(`[Conversation] ${data.conversation_id}`);
console.log("");
break;
case "reasoning":
if (data.reasoning) {
console.log(`[Reasoning] ${data.reasoning}`);
}
break;
case "tool_call":
console.log(`[Tool Call] ${data.tool_id} ${JSON.stringify(data.params || {})}`);
break;
case "tool_result": {
let summary = JSON.stringify(data.results || []);
if (summary.length > 500) {
summary = summary.slice(0, 500) + "... (truncated)";
}
console.log(`[Tool Result] ${data.tool_id} -> ${summary}`);
break;
}
case "tool_progress":
if (data.message) {
console.log(`[Tool Progress] ${data.message}`);
}
break;
case "thinking_complete":
console.log("");
break;
case "message_complete":
console.log("[Response]");
console.log(data.message_content);
break;
case "round_complete":
console.log("");
console.log(`[Round Complete] Status: ${data.round?.status || "unknown"}`);
break;
}
eventType = "";
}
}
}
}
async function listCustomTools() {
const data = await kibanaGet(`${API_BASE}/tools`);
const tools = data.results || data;
const platformTools = [];
const customTools = [];
for (const tool of tools) {
if (tool.id.startsWith("platform.core.")) {
platformTools.push(tool);
} else {
customTools.push(tool);
}
}
console.log(`Platform tools (${platformTools.length}):`);
console.log("");
for (const tool of platformTools) {
const desc = tool.description ? ` — ${tool.description}` : "";
console.log(` ${tool.id}${desc}`);
}
console.log("");
console.log(`Custom tools (${customTools.length}):`);
console.log("");
for (const tool of customTools) {
const type = tool.type ? `[${tool.type}]` : "";
const desc = tool.description ? ` — ${tool.description}` : "";
console.log(` ${tool.id} ${type}${desc}`);
}
}
async function getTool(args) {
const id = args.id;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
const data = await kibanaGet(`${API_BASE}/tools/${encodeURIComponent(id)}`);
console.log(JSON.stringify(data, null, 2));
}
async function createTool(args) {
const id = args.id;
const type = args.type;
const description = args.description;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
if (!type) {
console.error("Error: --type is required (esql, index_search, or workflow).");
process.exit(1);
}
if (!description) {
console.error("Error: --description is required.");
process.exit(1);
}
const payload = { id, type, description, configuration: {} };
if (type === "esql") {
if (!args.query) {
console.error("Error: --query is required for esql tools.");
process.exit(1);
}
payload.configuration.query = args.query;
payload.configuration.params = args.params ? JSON.parse(args.params) : {};
} else if (type === "index_search") {
if (!args.pattern) {
console.error("Error: --pattern is required for index_search tools.");
process.exit(1);
}
payload.configuration.pattern = args.pattern;
} else if (type === "workflow") {
if (!args.workflow_id) {
console.error("Error: --workflow-id is required for workflow tools.");
process.exit(1);
}
payload.configuration.workflow_id = args.workflow_id;
} else {
console.error(`Error: Unsupported --type "${type}". Allowed values: esql, index_search, workflow.`);
process.exit(1);
}
if (args.tags) {
payload.tags = args.tags.split(",").map((t) => t.trim());
}
const result = await kibanaPost(`${API_BASE}/tools`, payload);
console.log("Tool created successfully!");
console.log(JSON.stringify(result, null, 2));
}
async function updateTool(args) {
const id = args.id;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
// Fetch current tool to merge configuration
const current = await kibanaGet(`${API_BASE}/tools/${encodeURIComponent(id)}`);
// Only description, configuration, and tags are accepted by PUT
const payload = {};
if (args.description) {
payload.description = args.description;
}
const config = { ...current.configuration };
if (args.query) {
config.query = args.query;
}
if (args.params) {
config.params = JSON.parse(args.params);
}
if (args.pattern) {
config.pattern = args.pattern;
}
if (args.workflow_id) {
config.workflow_id = args.workflow_id;
}
payload.configuration = config;
if (args.tags) {
payload.tags = args.tags.split(",").map((t) => t.trim());
}
const result = await kibanaPut(`${API_BASE}/tools/${encodeURIComponent(id)}`, payload);
console.log("Tool updated successfully!");
console.log(JSON.stringify(result, null, 2));
}
async function deleteTool(args) {
const id = args.id;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
await kibanaDelete(`${API_BASE}/tools/${encodeURIComponent(id)}`);
console.log(`Tool "${id}" deleted successfully.`);
}
async function testTool(args) {
const id = args.id;
if (!id) {
console.error("Error: --id is required.");
process.exit(1);
}
const payload = {
tool_id: id,
tool_params: args.params ? JSON.parse(args.params) : {},
};
const result = await kibanaPost(`${API_BASE}/tools/_execute`, payload);
for (const r of result.results || []) {
if (r.type === "esql_results" && r.data) {
const cols = (r.data.columns || []).map((c) => c.name);
const rows = r.data.values || [];
console.log(`Columns: ${cols.join(", ")}`);
console.log(`Rows returned: ${rows.length}`);
if (rows.length > 0) {
console.log("");
console.log("Sample (first 3 rows):");
for (const row of rows.slice(0, 3)) {
const obj = {};
cols.forEach((col, i) => {
obj[col] = row[i];
});
console.log(` ${JSON.stringify(obj)}`);
}
}
} else {
console.log(JSON.stringify(r, null, 2));
}
}
}
async function main() {
const [command, ...rest] = process.argv.slice(2);
const args = parseArgs(rest);
switch (command) {
case "list-tools":
await listTools();
break;
case "list-agents":
await listAgents();
break;
case "get-agent":
await getAgent(args);
break;
case "create-agent":
await createAgent(args);
break;
case "update-agent":
await updateAgent(args);
break;
case "delete-agent":
await deleteAgent(args);
break;
case "chat":
await chat(args);
break;
case "list-custom-tools":
await listCustomTools();
break;
case "get-tool":
await getTool(args);
break;
case "create-tool":
await createTool(args);
break;
case "update-tool":
await updateTool(args);
break;
case "delete-tool":
await deleteTool(args);
break;
case "test-tool":
await testTool(args);
break;
default:
console.error("Usage: agent-builder.js <command> [options]");
console.error("");
console.error("Agent commands:");
console.error(" list-tools List available tools");
console.error(" list-agents List existing agents");
console.error(" get-agent --id <id> Get agent details");
console.error(" create-agent --name <n> --tool-ids <ids> Create an agent");
console.error(" update-agent --id <id> [--description ...] Update an agent");
console.error(" delete-agent --id <id> Delete an agent");
console.error(" chat --id <id> --message <msg> Chat with an agent");
console.error("");
console.error("Tool commands:");
console.error(" list-custom-tools List tools by platform/custom");
console.error(" get-tool --id <id> Get tool details");
console.error(" create-tool --id <id> --type <t> Create a tool");
console.error(" update-tool --id <id> [...] Update a tool");
console.error(" delete-tool --id <id> Delete a tool");
console.error(" test-tool --id <id> Execute a tool for testing");
console.error("");
console.error("Agent create options:");
console.error(" --name Agent display name (required)");
console.error(" --tool-ids Comma-separated tool IDs (required)");
console.error(" --description Agent description (defaults to name)");
console.error(" --instructions System instructions for the agent");
console.error("");
console.error("Agent update options:");
console.error(" --id Agent ID (required)");
console.error(" --description New description");
console.error(" --instructions New system instructions");
console.error(" --tool-ids New comma-separated tool IDs");
console.error("");
console.error("Chat options:");
console.error(" --id Agent ID (required)");
console.error(" --message Message to send (required)");
console.error(" --conversation-id Continue an existing conversation");
console.error("");
console.error("Tool create options:");
console.error(" --id Tool ID (required)");
console.error(" --type Tool type: esql, index_search, workflow (required)");
console.error(" --description Tool description (required)");
console.error(" --query ES|QL query (esql type)");
console.error(" --params JSON params object (esql type)");
console.error(" --pattern Index pattern (index_search type)");
console.error(" --workflow-id Workflow ID (workflow type)");
console.error(" --tags Comma-separated tags");
console.error("");
console.error("Tool test options:");
console.error(" --id Tool ID (required)");
console.error(" --params JSON params for execution");
process.exit(1);
}
}
main().catch((err) => {
console.error(`Error: ${err.message}`);
process.exit(1);
});
/**
* Lightweight HTTP client for the Kibana REST API.
* Uses native fetch() with auth, retry on 429, and space support.
*/
try {
process.loadEnvFile();
} catch {}
const RETRY_DELAYS = [5, 10, 20];
export function getKibanaConfig() {
const url = process.env.KIBANA_URL;
const apiKey = process.env.KIBANA_API_KEY;
const username = process.env.KIBANA_USERNAME || process.env.ELASTICSEARCH_USERNAME;
const password = process.env.KIBANA_PASSWORD || process.env.ELASTICSEARCH_PASSWORD;
const spaceId = process.env.KIBANA_SPACE_ID;
const insecure = process.env.KIBANA_INSECURE === "true";
if (!url) {
console.error("Error: No Kibana connection configured.");
console.error("Set KIBANA_URL environment variable.");
process.exit(1);
}
if (!apiKey && !username && !password && process.env.KIBANA_NO_AUTH !== "true") {
console.error("Error: No Kibana authentication configured.");
console.error("Set KIBANA_API_KEY or KIBANA_USERNAME + KIBANA_PASSWORD.");
console.error("Or set KIBANA_NO_AUTH=true for clusters with security disabled.");
process.exit(1);
}
if (!apiKey && ((username && !password) || (!username && password))) {
console.error("Error: Both username and password must be set for basic auth.");
console.error("Set KIBANA_USERNAME + KIBANA_PASSWORD (or ELASTICSEARCH_USERNAME + ELASTICSEARCH_PASSWORD).");
process.exit(1);
}
return { url, apiKey, username, password, spaceId, insecure };
}
function getHeaders(config) {
const headers = {
"Content-Type": "application/json",
"kbn-xsrf": "true",
"User-Agent": "elastic-agentic",
};
if (config.apiKey) {
headers["Authorization"] = `ApiKey ${config.apiKey}`;
} else if (config.username && config.password) {
const auth = Buffer.from(`${config.username}:${config.password}`).toString("base64");
headers["Authorization"] = `Basic ${auth}`;
}
return headers;
}
function getBasePath(config, space) {
let basePath = config.url.replace(/\/$/, "");
const effectiveSpace = space || config.spaceId;
if (effectiveSpace && effectiveSpace !== "default") {
basePath += `/s/${effectiveSpace}`;
}
return basePath;
}
/**
* Make an HTTP request to the Kibana API with automatic 429 retry.
*
* @param {string} path - API path (e.g. "/api/cases")
* @param {object} [options] - fetch options (method, body, headers, params)
* @param {string} [options.space] - Override Kibana space for this request
* @returns {{ success: boolean, data?: any, status?: number, error?: string }}
*/
export async function kibanaFetch(path, options = {}) {
const config = getKibanaConfig();
const { space, params, ...fetchOpts } = options;
const basePath = getBasePath(config, space);
let url = `${basePath}${path}`;
if (params) {
const searchParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null) {
if (Array.isArray(value)) {
for (const v of value) searchParams.append(key, v);
} else {
searchParams.append(key, String(value));
}
}
}
const qs = searchParams.toString();
if (qs) url += `?${qs}`;
}
const requestOptions = {
...fetchOpts,
headers: {
...getHeaders(config),
...fetchOpts.headers,
},
};
if (config.insecure) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
}
for (let attempt = 0; attempt <= RETRY_DELAYS.length; attempt++) {
try {
const response = await fetch(url, requestOptions);
if (response.status === 429 && attempt < RETRY_DELAYS.length) {
const delay = RETRY_DELAYS[attempt];
console.error(`Rate limited, retrying in ${delay}s (attempt ${attempt + 1}/${RETRY_DELAYS.length + 1})...`);
await new Promise((r) => setTimeout(r, delay * 1000));
continue;
}
const contentType = response.headers.get("content-type");
let data;
if (contentType && contentType.includes("application/json")) {
data = await response.json();
} else {
data = await response.text();
}
if (!response.ok) {
return {
success: false,
status: response.status,
error: data?.message || data?.error || `HTTP ${response.status}`,
details: data,
};
}
return { success: true, data };
} catch (error) {
if (attempt < RETRY_DELAYS.length && error.message?.includes("429")) {
const delay = RETRY_DELAYS[attempt];
console.error(`Rate limited, retrying in ${delay}s...`);
await new Promise((r) => setTimeout(r, delay * 1000));
continue;
}
return { success: false, error: error.message, details: error };
}
}
}
/**
* Convenience wrappers matching the Python KibanaClient interface.
* These throw on HTTP errors (matching the old behavior where scripts
* relied on exceptions for error handling).
*/
export async function kibanaGet(path, params, space) {
const result = await kibanaFetch(path, { method: "GET", params, space });
if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
return result.data;
}
export async function kibanaPost(path, body, space) {
const result = await kibanaFetch(path, {
method: "POST",
body: body !== undefined ? JSON.stringify(body) : undefined,
space,
});
if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
return result.data;
}
export async function kibanaPatch(path, body, space) {
const result = await kibanaFetch(path, {
method: "PATCH",
body: body !== undefined ? JSON.stringify(body) : undefined,
space,
});
if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
return result.data;
}
export async function kibanaPut(path, body, space) {
const result = await kibanaFetch(path, {
method: "PUT",
body: body !== undefined ? JSON.stringify(body) : undefined,
space,
});
if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
return result.data;
}
export async function kibanaDelete(path, space) {
const result = await kibanaFetch(path, { method: "DELETE", space });
if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
return result.data;
}
export async function testConnection(space) {
try {
const status = await kibanaGet("/api/status", undefined, space);
const version = status?.version;
const versionStr = typeof version === "object" ? version?.number : version;
console.log(`Connected to Kibana: ${status?.name || "unknown"}`);
console.log(`Version: ${versionStr || "unknown"}`);
return true;
} catch (error) {
console.error(`Connection failed: ${error.message}`);
return false;
}
}