hive-credentials 设置和安装代理的凭证。检测代理配置中缺失的凭证,从用户那里收集它们,并将它们安全地存储在本地加密存储中 ~/.hive/credentials。 许可协议:Apache-2.0 元数据: 作者:hive 版本:“2.3” 类型:实用工具
设置凭证
交互式凭证设置,适用于具有多种身份验证选项的代理。检测缺失的内容,提供认证方法选择,通过健康检查进行验证,并将凭证安全存储。
何时使用
- 在首次运行或测试代理之前
- 当
AgentRunner.run()因 “缺少必需的凭证” 失败时 - 当用户要求为代理配置凭证时
- 在构建使用需要API密钥的工具的新代理后
工作流程
第1步:识别代理
确定哪个代理需要凭证。用户将:
- 直接命名代理(例如,“为hubspot-agent设置凭证”)
- 打开代理目录(检查
exports/代理目录) - 在当前会话中使用代理
在 exports/{agent_name}/ 下找到代理的目录。
第2步:检测缺失的凭证
使用 check_missing_credentials MCP工具检测代理需要什么以及已经配置了什么。这个工具加载代理,检查其所需的工具和节点类型,通过 CREDENTIAL_SPECS 将它们映射到凭证,并检查加密存储和环境变量。
check_missing_credentials(agent_path="exports/{agent_name}")
该工具返回一个JSON响应:
{
"agent": "exports/{agent_name}",
"missing": [
{
"credential_name": "brave_search",
"env_var": "BRAVE_SEARCH_API_KEY",
"description": "Brave Search API key for web search",
"help_url": "https://brave.com/search/api/",
"tools": ["web_search"]
}
],
"available": [
{
"credential_name": "anthropic",
"env_var": "ANTHROPIC_API_KEY",
"source": "encrypted_store"
}
],
"total_missing": 1,
"ready": false
}
如果 ready 为真(没有缺失): 报告所有凭证已配置并跳过步骤3-5。示例:
所有必需的凭证都已配置:
✓ anthropic (ANTHROPIC_API_KEY)
✓ brave_search (BRAVE_SEARCH_API_KEY)
您的代理已准备好运行!
如果缺少凭证: 继续进行第3步,使用 missing 列表。
第3步:为每个缺失的凭证呈现认证选项
对于每个缺失的凭证,检查可用的认证方法:
from aden_tools.credentials import CREDENTIAL_SPECS
spec = CREDENTIAL_SPECS.get("hubspot")
if spec:
# 确定可用的认证选项
auth_options = []
if spec.aden_supported:
auth_options.append("aden")
if spec.direct_api_key_supported:
auth_options.append("direct")
auth_options.append("custom") # 始终可用
# 获取设置信息
setup_info = {
"env_var": spec.env_var,
"description": spec.description,
"help_url": spec.help_url,
"api_key_instructions": spec.api_key_instructions,
}
使用 AskUserQuestion 呈现可用选项:
选择如何配置 HUBSPOT_ACCESS_TOKEN:
1) Aden 平台 (OAuth)(推荐)
通过 hive.adenhq.com 安全的 OAuth2 流程
- 快速设置,自动刷新令牌
- 不需要手动管理API密钥
2) 直接API密钥
手动输入您自己的API密钥
- 需要创建HubSpot私有应用
- 对范围和权限有完全控制
3) 本地凭证设置(高级)
CI/CD的程序化配置
- 用于自动化部署
- 需要手动API调用
第4步:根据用户选择执行认证流程
先决条件:确保 HIVE_CREDENTIAL_KEY 可用
在存储任何凭证之前,验证是否设置了 HIVE_CREDENTIAL_KEY(需要加密/解密本地存储)。检查当前会话和shell配置:
# 检查当前会话
printenv HIVE_CREDENTIAL_KEY > /dev/null 2>&1 && echo "session: set" || echo "session: not set"
# 检查shell配置文件
for f in ~/.zshrc ~/.bashrc ~/.profile; do [ -f "$f" ] && grep -q 'HIVE_CREDENTIAL_KEY' "$f" && echo "$f"; done
- 在当前会话中 — 继续存储凭证
- 在shell配置中但不在当前会话中 — 先运行
source ~/.zshrc(或~/.bashrc),然后继续 - 任何地方都没有设置 —
EncryptedFileStorage会自动生成一个。存储后,告诉用户持久化它:export HIVE_CREDENTIAL_KEY="{generated_key}"在他们的shell配置文件中
⚠️ 重要: 在将
HIVE_CREDENTIAL_KEY添加到用户的shell配置后,始终显示:⚠️ 环境变量已添加到您的shell配置中。 在新终端中打开它们以在会话外生效。
选项1:Aden平台(OAuth)
这是支持集成(HubSpot等)的推荐流程。
Aden OAuth的工作方式:
ADEN_API_KEY代表一个用户,该用户已在Aden平台上完成OAuth授权。当用户在Aden上注册并连接集成(HubSpot等)时,这些OAuth令牌存储在服务器端。拥有ADEN_API_KEY意味着:
- 用户拥有Aden账户
- 用户已通过Aden上的OAuth授权集成(HubSpot等)
- 我们只需要将这些凭证同步到本地凭证存储
4.1a. 检查ADEN_API_KEY
import os
aden_key = os.environ.get("ADEN_API_KEY")
如果没有设置,引导用户从Aden获取一个(这是他们进行OAuth的地方):
from aden_tools.credentials import open_browser, get_aden_setup_url
# 打开浏览器到Aden — 用户将在那里注册并连接集成
url = get_aden_setup_url() # https://hive.adenhq.com
success, msg = open_browser(url)
print("请登录Aden并连接您的集成(HubSpot等)。")
print("完成后,复制您的API密钥并返回这里。")
要求用户提供他们收到的ADEN_API_KEY。
4.1b. 将ADEN_API_KEY保存到Shell配置
在用户同意的情况下,将其保存到他们的shell配置中:
from aden_tools.credentials import (
detect_shell,
add_env_var_to_shell_config,
get_shell_source_command,
)
shell_type = detect_shell() # 'bash', 'zsh', 或 'unknown'
# 询问用户在修改shell配置前的同意
# 如果同意:
success, config_path = add_env_var_to_shell_config(
"ADEN_API_KEY",
user_provided_key,
comment="Aden平台(OAuth)API密钥"
)
if success:
source_cmd = get_shell_source_command()
print(f"已保存到 {config_path}")
print(f"运行:{source_cmd}")
⚠️ 重要: 在将
ADEN_API_KEY添加到用户的shell配置后,始终显示:⚠️ 环境变量已添加到您的shell配置中。 在新终端中打开它们以在会话外生效。
同时保存到 ~/.hive/configuration.json 以供框架使用:
import json
from pathlib import Path
config_path = Path.home() / ".hive" / "configuration.json"
config = json.loads(config_path.read_text()) if config_path.exists() else {}
config["aden"] = {
"api_key_configured": True,
"api_url": "https://api.adenhq.com"
}
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(json.dumps(config, indent=2))
4.1c. 从Aden服务器同步凭证
由于用户已在Aden上授权集成,使用单行工厂方法:
from core.framework.credentials import CredentialStore
# 这个单一调用处理所有内容:
# - 在 ~/.hive/credentials 创建加密的本地存储
# - 从 ADEN_API_KEY 环境变量配置Aden客户端
# - 自动从Aden服务器同步所有凭证
store = CredentialStore.with_aden_sync(
base_url="https://api.adenhq.com",
auto_sync=True, # 创建时同步
)
# 检查同步了什么
synced = store.list_credentials()
print(f"同步凭证:{synced}")
# 如果所需的凭证没有同步,用户还没有在Aden上授权它
if "hubspot" not in synced:
print("您的Aden账户中没有找到HubSpot。")
print("请访问 https://hive.adenhq.com 连接HubSpot,然后再试一次。")
对于更多的同步控制:
from core.framework.credentials import CredentialStore
from core.framework.credentials.aden import (
AdenCredentialClient,
AdenClientConfig,
AdenSyncProvider,
)
# 创建客户端(从 ADEN_API_KEY 环境变量加载API密钥)
client = AdenCredentialClient(AdenClientConfig(
base_url="https://api.adenhq.com",
))
# 创建提供商和存储
provider = AdenSyncProvider(client=client)
store = CredentialStore.with_encrypted_storage()
# 手动同步
synced_count = provider.sync_all(store)
print(f"从Aden同步了 {synced_count} 个凭证")
4.1d. 运行健康检查
from aden_tools.credentials import check_credential_health
# 从存储中获取令牌
cred = store.get_credential("hubspot")
token = cred.keys["access_token"].value.get_secret_value()
result = check_credential_health("hubspot", token)
if result.valid:
print("HubSpot凭证验证成功!")
else:
print(f"验证失败:{result.message}")
# 提供重试OAuth流程的选项
选项2:直接API密钥
对于喜欢手动管理API密钥的用户。
4.2a. 显示设置说明
from aden_tools.credentials import CREDENTIAL_SPECS
spec = CREDENTIAL_SPECS.get("hubspot")
if spec and spec.api_key_instructions:
print(spec.api_key_instructions)
# 输出:
# 要获得HubSpot私有应用令牌:
# 1. 前往HubSpot设置>集成>私有应用
# 2. 点击"创建私有应用"
# 3. 为您的应用命名(例如,"Hive Agent")
# ...
if spec and spec.help_url:
print(f"更多信息:{spec.help_url}")
4.2b. 从用户那里收集API密钥
使用 AskUserQuestion 安全地收集API密钥:
请提供您的HubSpot访问令牌:
(这将被安全地存储在 ~/.hive/credentials 中)
4.2c. 在存储之前运行健康检查
from aden_tools.credentials import check_credential_health
result = check_credential_health("hubspot", user_provided_token)
if not result.valid:
print(f"警告:{result.message}")
# 询问用户是否想要:
# 1. 尝试不同的令牌
# 2. 无论如何继续(不推荐)
4.2d. 存储在本地加密存储中
from core.framework.credentials import CredentialStore, CredentialObject, CredentialKey
from pydantic import SecretStr
store = CredentialStore.with_encrypted_storage()
cred = CredentialObject(
id="hubspot",
name="HubSpot访问令牌",
keys={
"access_token": CredentialKey(
name="access_token",
value=SecretStr(user_provided_token),
)
},
)
store.save_credential(cred)
4.2e. 导出到当前会话
export HUBSPOT_ACCESS_TOKEN="the-value"
选项3:本地凭证设置(高级)
对于程序化/CI/CD设置。
4.3a. 显示文档
对于高级凭证管理,您可以直接使用CredentialStore API:
from core.framework.credentials import CredentialStore, CredentialObject, CredentialKey
from pydantic import SecretStr
store = CredentialStore.with_encrypted_storage()
cred = CredentialObject(
id="hubspot",
name="HubSpot访问令牌",
keys={"access_token": CredentialKey(name="access_token", value=SecretStr("..."))}
)
store.save_credential(cred)
对于CI/CD环境:
- 设置HIVE_CREDENTIAL_KEY用于加密
- 预先填充 ~/.hive/credentials程序化
- 或直接使用环境变量(HUBSPOT_ACCESS_TOKEN)
文档:请参阅core/framework/credentials/README.md
第5步:记录配置方法
在 ~/.hive/configuration.json 中跟踪每种凭证使用的认证方法:
import json
from pathlib import Path
from datetime import datetime
config_path = Path.home() / ".hive" / "configuration.json"
config = json.loads(config_path.read_text()) if config_path.exists() else {}
if "credential_methods" not in config:
config["credential_methods"] = {}
config["credential_methods"]["hubspot"] = {
"method": "aden", # 或 "direct" 或 "custom"
"configured_at": datetime.now().isoformat(),
}
config_path.write_text(json.dumps(config, indent=2))
第6步:验证所有凭证
使用 verify_credentials MCP工具确认所有内容都已正确配置:
verify_credentials(agent_path="exports/{agent_name}")
该工具返回:
{
"agent": "exports/{agent_name}",
"ready": true,
"missing_credentials": [],
"warnings": [],
"errors": []
}
如果 ready 为真,则报告成功。如果 missing_credentials 不为空,则识别失败的内容,并返回步骤3以设置剩余的凭证。
健康检查参考
健康检查通过进行轻量级API调用来验证凭证:
| 凭证 | 端点 | 它检查什么 |
|---|---|---|
anthropic |
POST /v1/messages |
API密钥有效性 |
brave_search |
GET /res/v1/web/search?q=test&count=1 |
API密钥有效性 |
google_search |
GET /customsearch/v1?q=test&num=1 |
API密钥 + CSE ID有效性 |
github |
GET /user |
令牌有效性,用户身份 |
hubspot |
GET /crm/v3/objects/contacts?limit=1 |
令牌有效性,CRM范围 |
resend |
GET /domains |
API密钥有效性 |
from aden_tools.credentials import check_credential_health, HealthCheckResult
result: HealthCheckResult = check_credential_health("hubspot", token_value)
# result.valid: bool
# result.message: str
# result.details: dict (status_code, rate_limited, etc.)
加密密钥(HIVE_CREDENTIAL_KEY)
本地加密存储需要 HIVE_CREDENTIAL_KEY 来加密/解密凭证。
- 如果用户没有,
EncryptedFileStorage会自动生成一个并记录 - 用户必须持久化这个密钥(例如,在
~/.bashrc/~/.zshrc或秘密管理器中) - 没有这个密钥,存储的凭证无法解密
Shell配置规则: 只有两个密钥属于shell配置(~/.zshrc/~/.bashrc):
HIVE_CREDENTIAL_KEY— 凭证存储的加密密钥ADEN_API_KEY— Aden平台认证密钥(存储可以同步之前需要)
所有其他API密钥(Brave、Google、HubSpot等)必须仅在加密存储中。永远不要提供将它们添加到shell配置的选项。
如果 HIVE_CREDENTIAL_KEY 没有设置:
- 让存储生成一个
- 告诉用户保存它:
export HIVE_CREDENTIAL_KEY="{generated_key}" - 建议添加到
~/.bashrc或他们的shell配置文件中
安全规则
- 永远不要 在工具输出中记录、打印或回显凭证值
- 永远不要 在纯文本文件、git跟踪的文件或代理配置中存储凭证
- 永远不要 在源代码中硬编码凭证
- 永远不要 提供将API密钥保存到shell配置的选项(
~/.zshrc/~/.bashrc)— 只有HIVE_CREDENTIAL_KEY和ADEN_API_KEY属于shell配置。所有其他凭证(Brave、Google、HubSpot、GitHub、Resend等)仅在加密存储中。 - 总是 使用Pydantic中的
SecretStr处理Python中的凭证值 - 总是 使用本地加密存储(
~/.hive/credentials)进行持久化 - 总是 在存储凭证之前运行健康检查(如果可能)
- 总是 通过重新运行验证来验证凭证是否已存储,而不是通过回读它们
- 修改
~/.bashrc或~/.zshrc时,先与用户确认
凭证来源参考
所有凭证规范都在 tools/src/aden_tools/credentials/ 中定义:
| 文件 | 类别 | 凭证 | Aden支持 |
|---|---|---|---|
llm.py |
LLM提供商 | anthropic |
否 |
search.py |
搜索工具 | brave_search, google_search, google_cse |
否 |
email.py |
电子邮件 | resend |
否 |
integrations.py |
集成 | github, hubspot, google_calendar_oauth |
否/是 |
注意: 其他LLM提供商(Cerebras、Groq、OpenAI)由LiteLLM通过环境变量(CEREBRAS_API_KEY、GROQ_API_KEY、OPENAI_API_KEY)处理,但尚未在CREDENTIAL_SPECS中。需要时将其添加到 llm.py。
要检查注册了什么:
from aden_tools.credentials import CREDENTIAL_SPECS
for name, spec in CREDENTIAL_SPECS.items():
print(f"{name}: aden={spec.aden_supported}, direct={spec.direct_api_key_supported}")
迁移:CredentialManager → CredentialStore
CredentialManager已弃用。 使用CredentialStore代替。
| 旧的(弃用) | 新的(推荐) |
|---|---|
CredentialManager() |
CredentialStore.with_encrypted_storage() |
creds.get("hubspot") |
store.get("hubspot") 或 store.get_key("hubspot", "access_token") |
creds.validate_for_tools(tools) |
使用 store.is_available(cred_id) 每个凭证 |
creds.get_auth_options("hubspot") |
检查 CREDENTIAL_SPECS["hubspot"].aden_supported |
creds.get_setup_instructions("hubspot") |
直接访问 CREDENTIAL_SPECS["hubspot"] |
为什么迁移?
- CredentialStore 支持加密存储,多密钥凭证,模板解析和自动令牌刷新
- CredentialManager 只从环境变量和.env文件中读取(无加密,无刷新)
- CredentialStoreAdapter 存在用于迁移期间的向后兼容性
# 旧方法(弃用)
from aden_tools.credentials import CredentialManager
creds = CredentialManager()
token = creds.get("hubspot")
# 新方法(推荐)
from core.framework.credentials import CredentialStore
store = CredentialStore.with_encrypted_storage()
token = store.get("hubspot")
# 与Aden同步(推荐用于OAuth集成)
store = CredentialStore.with_aden_sync()
token = store.get_key("hubspot", "access_token")
示例会话
用户:/hive-credentials 用于我的研究代理
代理:让我检查一下您的研究代理需要什么凭证。
[调用 check_missing_credentials(agent_path="exports/research-agent")]
→ 返回:
available: anthropic (encrypted_store), brave_search (encrypted_store)
missing: google_search (GOOGLE_API_KEY), google_cse (GOOGLE_CSE_ID)
ready: false
代理:4个必需的凭证中有2个已经配置好了。只需要设置Google自定义搜索(2个值)。
--- 设置Google自定义搜索(google_search + google_cse) ---
这需要两个一起工作的值。
[在存储之前检查 HIVE_CREDENTIAL_KEY]
$ printenv HIVE_CREDENTIAL_KEY > /dev/null 2>&1 && echo "set" || echo "not set"
set
首先,Google API密钥:
1. 前往 https://console.cloud.google.com/apis/credentials
2. 创建一个新项目(或选择一个现有的)
3. 在API库中启用"自定义搜索API"
4. 前往凭证>创建凭证>API密钥
5. 复制生成的API密钥
[AskUserQuestion:"请提供您的Google API密钥:"]
[用户提供密钥]
现在,自定义搜索引擎ID:
1. 前往 https://programmablesearchengine.google.com/controlpanel/all
2. 点击"添加"创建一个新的搜索引擎
3. 在"搜索什么"下,选择"搜索整个网络"
4. 给您的搜索引擎命名
5. 点击"创建"
6. 复制搜索引擎ID(cx值)
[AskUserQuestion:"请提供您的Google CSE ID:"]
[用户提供ID]
[使用两个值运行健康检查 - GET /customsearch/v1?q=test&num=1 → 200 OK]
[将两个值都存储在本地加密存储中,导出到环境变量]
✓ Google自定义搜索凭证有效
[调用 verify_credentials(agent_path="exports/research-agent")]
→ 返回:ready: true, missing_credentials: []
所有凭证都已配置:
✓ anthropic (ANTHROPIC_API_KEY) — 已在加密存储中
✓ brave_search (BRAVE_SEARCH_API_KEY) — 已在加密存储中
✓ google_search (GOOGLE_API_KEY) — 存储在加密存储中
✓ google_cse (GOOGLE_CSE_ID) — 存储在加密存储中
┌─────────────────────────────────────────────────────────────────────────────┐
│ ✅ 凭证配置完成 │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 打开一个新的终端,然后再运行下面的命令。 │
│ 环境变量已保存到您的shell配置中,但 │
│ 只在新终端会话中生效。 │
│ │
│ NEXT STEPS: │
│ │
│ 1. 运行您的代理: │
│ │
│ hive tui │
│ │
│ 2. 如果您遇到问题,请使用调试器: │
│ │
│ /hive-debugger │
│ │
│ 调试器分析运行时日志,识别重试循环,工具 │
│ 失败,执行停滞,并提供可操作的修复建议。 │
│ │
└─────────────────────────────────────────────────────────────────────────────┘