Tool authorization and API token handling must be isolated per agent instance and never logged or transmitted in plain text.
Step‑by‑step implementation
1. Generate a scoped token – Use the provider’s short‑lived token endpoint (e.g., POST /oauth2/token with grant_type=client_credentials and scope=agent:run). Set expires_in ≤ 300 s.
2. Inject via environment variable – At agent startup, set AGENT_API_KEY=${TOKEN} in the process environment. Do not write the variable to .env files.
3. Configure LangChain/AutoGen – Pass the variable through the tool wrapper:
from langchain.tools import RequestsGetTool
import os
api_key = os.getenv("AGENT_API_KEY")
tool = RequestsGetTool(headers={"Authorization": f"Bearer {api_key}"})4. Enforce runtime checks – Add a middleware that aborts any outbound request lacking the Authorization header or containing the placeholder string {{TOKEN}}.
5. Audit and redaction – Hook the logging framework to mask any occurrence of the token pattern ([A-Za-z0-9\-_]{30,}) before writing to logs or stdout.
6. Rotate automatically – Schedule a background coroutine that refreshes the token before expiry and overwrites the environment variable in‑place.
Storage comparison
| Method | Persistence | Exposure risk | Revocation speed |
|-------------------|-------------|---------------|------------------|
| In‑memory env var | None | Low (process only) | Instant |
| Vault secret engine | Disk (encrypted) | Medium (API call) | < 1 s |
| Plain file .env | Disk | High | Manual |
Checklist
- [ ] Token TTL ≤ 5 min.
- [ ] No token appears in any log line.
- [ ] All tool wrappers receive the token via header injection, not URL query.
- [ ] Rotation job runs at 80 % of TTL.
Follow these controls to keep autonomous agents secure while preserving seamless tool use.