Navigation
guides
Credential Leasing in Agents
The agent credential lifecycle
When an AI agent needs a credential, the interaction follows a predictable pattern: request, use, release. Vault’s leasing model maps onto this lifecycle naturally. The agent requests a lease, uses the credential value during its task, and either lets the lease expire or revokes it when done.
This guide covers practical patterns for managing this lifecycle in agent code.
Pattern 1: Request and forget
The simplest pattern. The agent requests a short-lived lease and uses the credential immediately. The lease expires on its own.
const lease = await vault.leases.create({
credentialName: "openai-api-key",
ttl: "5m",
});
const response = await fetch("https://api.openai.com/v1/chat/completions", {
headers: { Authorization: `Bearer ${lease.value}` },
body: JSON.stringify({ model: "gpt-4", messages: [...] }),
});
This works well for one-shot tasks where the agent makes a single API call and moves on. The 5-minute TTL provides enough buffer for retries without holding the credential longer than necessary.
Pattern 2: Scoped lease block
Wrap credential usage in a try/finally block that revokes the lease when done, regardless of success or failure:
const lease = await vault.leases.create({
credentialName: 'prod-db-url',
ttl: '30m',
});
try {
const pool = new Pool({ connectionString: lease.value });
await pool.query('BEGIN');
await pool.query('ALTER TABLE users ADD COLUMN preferences jsonb');
await pool.query('COMMIT');
await pool.end();
} finally {
await vault.leases.revoke({ leaseId: lease.id });
}
This pattern is better for longer operations where you want to release the credential as soon as the work is done, rather than waiting for the TTL to expire.
Pattern 3: Renewable lease for long tasks
Some agent tasks run for extended periods: large data migrations, multi-step deployments, batch processing. Use lease renewal to keep the credential available without requesting an excessively long initial TTL:
const lease = await vault.leases.create({
credentialName: 'warehouse-db-url',
ttl: '30m',
});
const renewalInterval = setInterval(
async () => {
try {
await vault.leases.renew({ leaseId: lease.id, ttl: '30m' });
} catch {
clearInterval(renewalInterval);
}
},
25 * 60 * 1000,
); // Renew at 25 minutes (5 min before expiry)
try {
await runLongMigration(lease.value);
} finally {
clearInterval(renewalInterval);
await vault.leases.revoke({ leaseId: lease.id });
}
This pattern keeps each lease window short (30 minutes) while allowing the total operation to run longer. Each renewal is logged, providing a breadcrumb trail of the operation’s duration.
Pattern 4: Multiple credentials
Agents sometimes need multiple credentials for a single task. Request all leases upfront and revoke them together:
const [dbLease, apiLease] = await Promise.all([
vault.leases.create({
credentialName: 'prod-db-url',
ttl: '15m',
}),
vault.leases.create({
credentialName: 'stripe-api-key',
ttl: '15m',
}),
]);
try {
// Use both credentials
const orders = await fetchStripeOrders(apiLease.value);
await syncToDatabase(dbLease.value, orders);
} finally {
await Promise.all([
vault.leases.revoke({ leaseId: dbLease.id }),
vault.leases.revoke({ leaseId: apiLease.id }),
]);
}
Choosing TTL values
TTL selection depends on the task:
| Task type | Suggested TTL | Reasoning |
|---|---|---|
| Single API call | 5m | Enough for retries, minimal exposure |
| Database query | 15m | Covers connection setup and query execution |
| Migration or deployment | 30m + renewal | Short windows with extension as needed |
| Batch processing | 1h + renewal | Longer baseline for throughput-oriented work |
Err on the side of shorter TTLs. It is easy to renew a lease; it is impossible to un-expose a credential.
MCP-based leasing
When using the MCP server with Claude Code or Cortex agents, leasing is handled automatically by the MCP server. The agent does not call the SDK directly. Instead, the MCP server creates and manages leases based on its configuration:
{
"defaultTTL": "15m",
"maxTTL": "2h",
"autoRenew": true,
"renewBeforeExpiry": "5m"
}
See MCP with Claude Code and MCP with Cortex Agents for setup details.
Audit trail
Every pattern described here produces audit log entries for lease creation, renewal, and revocation. The audit log records the identity, credential name, TTL, and purpose for each event, providing a complete picture of credential usage across your agent fleet.