一键导入
aiconfig-api
Access LaunchDarkly AI Configs through the REST API. Learn how to authenticate and perform operations not available through SDKs.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Access LaunchDarkly AI Configs through the REST API. Learn how to authenticate and perform operations not available through SDKs.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
| name | aiconfig-api |
| description | Access LaunchDarkly AI Configs through the REST API. Learn how to authenticate and perform operations not available through SDKs. |
| compatibility | Requires LaunchDarkly account and project with AI Configs enabled. |
| metadata | {"author":"launchdarkly","version":"0.1.0"} |
Access LaunchDarkly AI Configs through the REST API to perform operations not available through SDKs, including creating, updating, and managing AI Configs programmatically.
Before prompting the user for an API key, try to detect it automatically:
~/.claude/config.json and look for mcpServers.launchdarkly.env.LAUNCHDARKLY_API_KEYLAUNCHDARKLY_API_KEY, LAUNCHDARKLY_API_TOKEN, or LD_API_KEYimport os
import json
from pathlib import Path
def get_launchdarkly_api_key():
"""Auto-detect LaunchDarkly API key from Claude config or environment."""
# 1. Check Claude MCP config
claude_config = Path.home() / ".claude" / "config.json"
if claude_config.exists():
try:
config = json.load(open(claude_config))
api_key = config.get("mcpServers", {}).get("launchdarkly", {}).get("env", {}).get("LAUNCHDARKLY_API_KEY")
if api_key:
return api_key
except (json.JSONDecodeError, IOError):
pass
# 2. Check environment variables
for var in ["LAUNCHDARKLY_API_KEY", "LAUNCHDARKLY_API_TOKEN", "LD_API_KEY"]:
if os.environ.get(var):
return os.environ[var]
return None
The LaunchDarkly MCP server provides basic AI Config operations via natural language in AI clients (Claude, Cursor, etc.).
MCP tools available:
list-ai-configs, get-ai-config, create-ai-config, update-ai-config, delete-ai-configget-ai-config-variation, create-ai-config-variation, update-ai-config-variation, delete-ai-config-variationCurrent MCP limitations (see issue #40):
tools, model.parameters, customParameters, or judgeConfiguration on variations/ai-tools)Recommendation: Use the REST API (documented below) for full AI Config functionality. MCP is useful for basic listing and skeleton creation only.
If you want to use MCP for basic operations, configure it in your AI client:
Claude Code (~/.claude/mcp.json):
{
"mcpServers": {
"launchdarkly": {
"command": "npx",
"args": ["-y", "@launchdarkly/mcp-server", "start"],
"env": {
"LD_ACCESS_TOKEN": "your-api-token"
}
}
}
}
Cursor (.cursor/mcp.json):
{
"mcpServers": {
"launchdarkly": {
"command": "npx",
"args": ["-y", "@launchdarkly/mcp-server", "start"],
"env": {
"LD_ACCESS_TOKEN": "your-api-token"
}
}
}
}
Replace your-api-token with your LaunchDarkly API access token. After configuring, restart your AI client.
For more details, see the LaunchDarkly MCP Server Documentation.
ai-configs:write - Full access to AI Configsprojects:read - Read project informationenvironments:read - Read environment dataInclude your token in the Authorization header for all requests:
import requests
headers = {
"Authorization": "YOUR_API_TOKEN",
"Content-Type": "application/json",
"LD-API-Version": "beta" # Required for AI Config endpoints
}
The following operations can only be done through the API, not through SDKs:
SDKs can only read AI Configs. Creating new configs requires the API.
See: aiconfig-create skill
Modifying existing configs, variations, or settings requires the API.
See: aiconfig-update and aiconfig-variations skills
Removing configs entirely requires the API.
See: aiconfig-update skill
Creating, updating, and deleting tools for function calling requires the API.
See: aiconfig-tools skill
Setting up targeting rules for AI Configs requires the API.
See: aiconfig-targeting skill
Listing all AI Configs in a project requires the API:
def list_ai_configs(project_key, api_token):
"""List all AI Configs in a project"""
url = f"https://app.launchdarkly.com/api/v2/projects/{project_key}/ai-configs"
headers = {
"Authorization": api_token,
"LD-API-Version": "beta"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
configs = response.json()
for config in configs.get("items", []):
print(f"- {config['key']}: {config['name']}")
return configs
else:
print(f"Error: {response.status_code}")
return None
| Operation | API | SDK | Notes |
|---|---|---|---|
| Create AI Configs | ✅ | ❌ | API only |
| Read AI Config values | ✅ | ✅ | SDK optimized for runtime |
| Update configurations | ✅ | ❌ | API only |
| Delete AI Configs | ✅ | ❌ | API only |
| Evaluate variations | ❌ | ✅ | SDK only - determines which variation to serve |
| Track metrics | ❌ | ✅ | SDK only - sends usage data |
| Manage tools | ✅ | ❌ | API only |
| Configure targeting | ✅ | ❌ | API only |
def api_request(method, url, headers, json_data=None):
"""Make API request with error handling"""
try:
if method == "GET":
response = requests.get(url, headers=headers)
elif method == "POST":
response = requests.post(url, headers=headers, json=json_data)
elif method == "PATCH":
response = requests.patch(url, headers=headers, json=json_data)
elif method == "DELETE":
response = requests.delete(url, headers=headers)
if response.status_code in [200, 201, 204]:
return {"success": True, "data": response.json() if response.text else None}
elif response.status_code == 400:
return {"success": False, "error": "Bad request - check your data"}
elif response.status_code == 401:
return {"success": False, "error": "Invalid or missing API token"}
elif response.status_code == 403:
return {"success": False, "error": "Insufficient permissions"}
elif response.status_code == 404:
return {"success": False, "error": "Resource not found"}
elif response.status_code == 429:
return {"success": False, "error": "Rate limited - wait and retry"}
else:
return {"success": False, "error": f"HTTP {response.status_code}"}
except requests.exceptions.RequestException as e:
return {"success": False, "error": str(e)}
Many API endpoints return paginated results:
def get_all_configs(project_key, api_token):
"""Get all AI Configs with pagination"""
all_configs = []
limit = 20
offset = 0
while True:
url = f"https://app.launchdarkly.com/api/v2/projects/{project_key}/ai-configs"
url += f"?limit={limit}&offset={offset}"
result = api_request("GET", url, {"Authorization": api_token, "LD-API-Version": "beta"})
if not result["success"]:
break
items = result["data"].get("items", [])
all_configs.extend(items)
# Check if more pages exist
if len(items) < limit:
break
offset += limit
return all_configs
https://app.launchdarkly.com/api/v2
https://app.launchdarkly.us/api/v2
https://app.eu.launchdarkly.com/api/v2
LaunchDarkly API has rate limits to ensure availability:
Handle rate limits gracefully:
import time
def retry_with_backoff(func, max_retries=3):
"""Retry function with exponential backoff"""
for attempt in range(max_retries):
result = func()
if result.get("success"):
return result
if "rate limited" in result.get("error", "").lower():
wait_time = 2 ** attempt # Exponential backoff
print(f"Rate limited, waiting {wait_time} seconds...")
time.sleep(wait_time)
else:
return result
return {"success": False, "error": "Max retries exceeded"}
headers = {
"Authorization": "YOUR_API_TOKEN", # Required
"Content-Type": "application/json", # For POST/PATCH
"LD-API-Version": "beta" # For AI Config endpoints
}
# Choose based on your environment
BASE_URL = "https://app.launchdarkly.com/api/v2" # Production
# BASE_URL = "https://app.launchdarkly.us/api/v2" # Federal
# BASE_URL = "https://app.eu.launchdarkly.com/api/v2" # EU
# AI Configs
f"{BASE_URL}/projects/{project}/ai-configs" # List/Create
f"{BASE_URL}/projects/{project}/ai-configs/{key}" # Get/Update/Delete
# Variations
f"{BASE_URL}/projects/{project}/ai-configs/{key}/variations" # List/Create
f"{BASE_URL}/projects/{project}/ai-configs/{key}/variations/{var_key}" # Get/Update/Delete
# Tools
f"{BASE_URL}/projects/{project}/ai-tools" # List/Create
f"{BASE_URL}/projects/{project}/ai-tools/{key}" # Get/Update/Delete
# AI Config Metrics (read AI usage metrics)
f"{BASE_URL}/projects/{project}/ai-configs/{key}/metrics?from={start}&to={end}&env={env}" # Get
# Custom Metrics (manage metric definitions)
f"{BASE_URL}/metrics/{project}" # List/Create
f"{BASE_URL}/metrics/{project}/{metric_key}" # Get/Update/Delete
# Segments (for targeting)
f"{BASE_URL}/segments/{project}/{env}" # List/Create
f"{BASE_URL}/segments/{project}/{env}/{segment_key}" # Get/Update/Delete
# Projects
f"{BASE_URL}/projects" # List/Create
f"{BASE_URL}/projects/{project}" # Get/Update/Delete
f"{BASE_URL}/projects/{project}/environments" # List environments
After setting up API access:
aiconfig-createaiconfig-variationsaiconfig-toolsaiconfig-targetingaiconfig-sdkaiconfig-create - Create configs via APIaiconfig-update - Update configs via APIaiconfig-projects - Manage projects via APIaiconfig-sdk - SDK vs API usageaiconfig-variations - Manage variations via APIaiconfig-tools - Manage tools via APICreate a new LaunchDarkly AI Config with variations, model configurations, and targeting. Use this skill to programmatically create AI Configs for agent or completion mode.
Configure LaunchDarkly AI Config targeting rules via API to control which users receive specific variations. Enable A/B tests, percentage splits, segment targeting, and multi-context rules.
Create, manage, and attach tools (functions) to LaunchDarkly AI Configs. Tools enable AI agents to interact with external systems, APIs, and databases.
Manage AI Config variations - add, update, retrieve, and delete variations from existing configs. Test different models, prompts, parameters, and tools within a single AI Config.
Build safe, scalable contexts for LaunchDarkly AI Configs with cardinality controls, multi-context patterns, and agent graph attributes.
Build and manage user contexts for LaunchDarkly AI Config targeting. Use this skill to create contexts with attributes for personalization, segmentation, and experimentation.