Guides
Security context
Let an agent call your MCP servers and APIs as your signed-in user. Your backend passes that user's tokens with the invocation, each under a name. Each one is sent, unmodified, only to the tools whose code names it — and never appears in the agent's code, the model's prompt, the conversation or the event stream.
| Who | Writes | So that |
|---|---|---|
| Your agent | credentials= and ToolAuth, in agent.py | Each credential name is declared, and each tool names the one it uses |
| Your backend | security_context, on the invoke call | One run carries one user's tokens |
| Your MCP server | Token verification | It accepts only tokens issued for it, and acts as their user |
You never write Runner code or construct a credential service. The platform builds both from your manifest. For a scenario rather than a mechanism — your user's OAuth 2 token from your app, your own key, your own server — see MCP authentication by example.
How it works
| Steps | What happens |
|---|---|
| 1–2 | Your user asks something. Your backend invokes the agent and passes that user's credentials, each under a name. |
| 3–5 | The platform validates the context, seals it for the run, and queues the run carrying only a random claim. The token never rides the queue. A refused context stops here with 400, 501 or 503, and nothing is queued. |
| 6–8 | The first time a tool names a credential, the pod collects the context, proving itself with the claim and its own workload identity. It is held in memory for this run only. |
| 9–11 | That one credential is attached, unmodified, to that tool's request and to nothing else. Your server verifies it as its own and acts as the user. |
| 12–13 | The reply reaches you as events, which never carry a credential. When the run finishes or fails, the sealed copy is deleted. A paused run keeps it until its ttl_seconds, so a tool approved later can still use it. |
1. Declare it in your agent
Two things, both in agent.py:
- the manifest's
credentials=block says what each credential name is, and who owns it; - each tool says which name it uses.
What each name is
from agentkit_core.manifest import AgentManifest, Credentials, FromEnv
MANIFEST = AgentManifest(
slug="notes-assistant",
version="0.1.0",
credentials=Credentials(
# The invoking user's, sent in each invocation's security context.
caller=["notes", "weather"],
# This agent's own, read from a variable a secret fills.
own={"maps": FromEnv(env="MAPS_API_KEY", kind="api_key",
header="X-Maps-Key",
resource="https://maps.acme.example")},
# Optional: your own BaseCredentialService, for anything minted in code.
service=".creds.BackOfficeTokens",
),
...
)targets:
notes-assistant:
egress:
- host: notes.acme.example
- host: maps.acme.example
secrets:
- {name: maps-api-key, env: MAPS_API_KEY} # fills credentials.own["maps"]A name is the caller's or the agent's — never both, and nothing falls back
- A caller credential named like one of the agent's own is ignored.
- A missing caller credential is never replaced by the agent's own. Doing so would hand a user who sent nothing your agent's access.
- The deploy refuses an
owncredential whose variable no secret fills.
On an MCP server
Name the credential on the binding. That is the whole integration.
from agentkit_core.manifest import ToolAuth, ToolBinding
tools=[
ToolBinding(
kind="mcp", ref="notes",
url="https://notes.acme.example/mcp",
tool_filter=["list_notes", "add_note"],
auth=ToolAuth(credential="notes"), # required=True by default
),
],- It is attached to
tools/listand to every call this binding makes, and to nothing else. - The binding must be https. The deploy refuses one that would send a credential over plain HTTP.
ToolAuth(credential="notes", required=False)calls the server with no credential when the caller sent none.
In a function tool
Through ADK's own credential API. auth_config(name) addresses a declared credential, and ADK hides the credential parameter from the model.
from agentkit_runtime import security
from agentkit_runtime.security import auth_config
from fastapi.openapi.models import APIKey, APIKeyIn
from google.adk.tools import FunctionTool, ToolContext
from google.adk.tools.authenticated_function_tool import AuthenticatedFunctionTool
# The caller's key, handed in as `credential`:
async def forecast(city: str, credential) -> dict:
return await weather.get(city, key=credential.api_key)
# The agent's own key, with the whole reach rule applied for you:
async def nearby(place: str, tool_context: ToolContext) -> dict:
sent = await security.headers("maps", url=MAPS_URL, context=tool_context)
return await http.get(MAPS_URL, params={"near": place}, headers=sent)
def build(ctx):
return LlmAgent(
...,
tools=[
*ctx.tools(),
AuthenticatedFunctionTool(
func=forecast,
auth_config=auth_config("weather",
scheme=APIKey(**{"in": APIKeyIn.header}, name="X-Weather-Key")),
),
FunctionTool(nearby),
],
)tool_context.load_credential(auth_config(name))answersNonefor a caller credential that was not sent, for a tool that treats it as optional.security.getandsecurity.requirereturn the credential itself.- Pass the
tool_contextyou were given ascontext.
2. Pass it when you invoke
From your backend, on the same call that names your end user. The SDKs validate it first, so a refusal names the field before anything is sent.
from elan_sdk import Elan
from elan_sdk.security import ApiKey, Bearer, SecurityContext
elan = Elan.from_env()
context = SecurityContext(credentials=[
# The user's own token for the notes MCP server, bound to it.
Bearer(name="notes", token=user_notes_token,
resource="https://notes.acme.example/mcp"),
# A per-user key for another API, sent as one header.
ApiKey(name="weather", key=user_weather_key, header="X-Weather-Key"),
], ttl_seconds=900)
accepted = elan.runtime.invoke(
"notes-assistant",
"What did I write about the launch?",
project="salmon",
session_id="sess-ada-1",
end_user_id="ada",
security_context=context,
)
print(accepted.invocation_id)Over HTTP
One more field on the invoke body:
POST /v1/invocations
{
"target_slug": "notes-assistant",
"project": "salmon",
"session_id": "sess-ada-1",
"end_user_id": "ada",
"text": "What did I write about the launch?",
"security_context": {
"credentials": [
{"kind": "bearer", "name": "notes", "token": "eyJ…",
"resource": "https://notes.acme.example/mcp"}
],
"ttl_seconds": 900
}
}From the CLI
Read from a file, or - for stdin. Never from the command line, which shell history and ps can read.
elan invoke notes-assistant --text "What did I write?" --security-context ctx.jsonIn the Playground
The run options take test credentials, one for each name your agent's bindings use. Choose + Credential and give its name, its kind, the token or key (and, for a key, its header) and, optionally, the one URL it is for.
- Up to 16, as in any security context. Each name can be added once; edit or remove it from its row.
- They are kept on the page only, never saved, and gone on reload.
- They are sent with every message until you remove them.
- Minimize the panel and they stay applied, each shown as a chip beside the message box.
Credential kinds
| Kind | Fields | Sent as |
|---|---|---|
bearer | token | Authorization: Bearer … — a JWT or any opaque token |
oauth2 | access_token, scopes | Authorization: Bearer …, and an OAuth2-typed credential for ADK tools that expect one |
api_key | key, header | One header, X-API-Key unless you name another |
basic | username, password | Authorization: Basic … |
headers | headers | Each header exactly as given, for a scheme none of the others name |
- Every credential also takes a
name, an optionalresource(the only URL it may be sent to) and an optionalexpires_atin Unix seconds. - A context holds at most 16 credentials and 32 KiB.
ttl_secondsruns from 60 to 86400 and defaults to 900. - Refused by name, without the value ever being quoted back:
refresh_tokenandclient_secret(the platform never holds a long-lived user credential), an API key in a query string, and headers that frame a request rather than authorize it —Host,Content-*, hop-by-hop headers andMcp-*.
3. Accept it in your MCP server
Your server is an OAuth resource server, exactly as the MCP authorization spec describes one. It should:
- verify every token's signature, issuer, expiry and audience, and refuse a token issued for another server;
- serve its Protected Resource Metadata, so a client can discover where to get a token;
- answer
401with aWWW-Authenticatechallenge, and403 insufficient_scopefor a valid token without the scope; - act as the token's verified
sub, never as anyone a request body names; - never pass the token on. Calling another API needs a token issued for that API.
The repository's agent-pipeline/applications/notes is a complete one, with a throwaway local issuer to test against.
The reach rule
Checked in this order, at the moment a request is about to go out. The first check that fails decides:
- Agent code names itor nothing
A ToolAuth on the MCP binding, or auth_config(name) in a tool. A credential no code names is never sent anywhere — nothing is broadcast.
- The manifest declares itrefused
As one of credentials.caller or credentials.own. An undeclared name fails the import for a binding and the call for a tool.
- It was suppliederror
A caller name in the invocation's security context, an own name in its variable. A required one that is missing ends the run naming it.
- It has not expirederror
An expired credential is never attached; refresh it and resume, or invoke again.
- The destination may receive itnot sent
https, or plain HTTP only to this machine or the cluster — and within its resource, when one is set.
- Attachedsent
Unmodified, to that one request.
Set resource whenever a token is for one server
The MCP authorization spec says a server must not accept a token that was not issued for it, which is why nothing is broadcast. With resource set, not even a mistake in agent code can send the token anywhere else.
ElanCredentialService
The platform's ADK BaseCredentialService, configured by the credentials= block. Every run of your agent has one: in a deployed pod, under elan adk, and in your own tests. So the same agent code runs in all three. It answers a key in this order:
- A caller namethe invocation
From the run's security context. Never stored, and never replaced by anything else.
- An own nameyour secret
From the variable its FromEnv names. A caller sending that name is ignored.
- Any other keyyour service
credentials.service, your own BaseCredentialService — or ADK's in-memory one when you declare none.
Your own service
Only for a credential that has to be obtained in code, such as a client-credentials token for your back office, minted and cached. A fixed key needs no code: declare it under own.
- Yours is composed behind the platform's, so it never sees a caller's credential and cannot be asked to store one.
- The path is resolved like a plugin's, and checked inside the built image at deploy.
credentials=Credentials(..., service=".creds.BackOfficeTokens"),from fastapi.openapi.models import HTTPBearer
from google.adk.auth.auth_tool import AuthConfig
from google.adk.auth.credential_service.base_credential_service import BaseCredentialService
# What a tool asks with. Any key that is not a caller or own name reaches this.
BACKOFFICE = AuthConfig(auth_scheme=HTTPBearer(), credential_key="backoffice")
class BackOfficeTokens(BaseCredentialService):
async def load_credential(self, auth_config, callback_context):
if auth_config.credential_key != "backoffice":
return None
return await self._cached_client_credentials_token()
async def save_credential(self, auth_config, callback_context):
return None # re-minted on demand; nothing is persistedfrom .creds import BACKOFFICE
async def open_ticket(summary: str, tool_context: ToolContext) -> dict:
credential = await tool_context.load_credential(BACKOFFICE)
...Running it locally
Give elan adk a context file:
{"credentials": [{"kind": "bearer", "name": "notes", "token": "eyJ…"}]}elan adk web --security-context ctx.json
elan adk run notes-assistant --security-context ctx.json- It is validated before ADK starts and handed to the run by path, so the values are in no process listing. Outside local development it is ignored.
- In a test written as in Building an agent, pass the same thing to
build_app:build_app(target, settings, security_context={"credentials": [...]}). - To point it at a real protected server, the repository's notes example runs one locally:
make notes-issuer,make mcp-notesandmake notes-token AS=ada.
What fails, and how
| Situation | What happens |
|---|---|
| A required credential was not sent | The run ends with an error naming it. The tool is never called without it. |
| A tool names a credential the manifest does not declare | A binding fails the import; a function tool's call ends the run naming it. |
An own credential's variable is unset | The deploy refuses it when no secret fills the variable; at run time the run ends naming the variable. |
The destination is outside the credential's resource | The run ends with an error saying it is not for that server. Nothing is sent. |
| The credential expired | The run ends with an error naming it. Refresh it and resume, or invoke again. |
| An optional binding's credential was not sent | The binding is called with none. If its server refuses, ADK runs that turn without the server's tools. |
| A tool asks ADK's interactive credential flow with your own OAuth client | The run ends with an error. As ADK ships it, that flow writes your client secret and the user's answer into the stored conversation, so the platform empties them and does not run it. For an end user's own account, use connected accounts, which pause the run for a sign-in instead. |
| The agent was built before security contexts existed | It runs without the credentials and your server answers 401. Redeploy it. |
| The platform has no sealing key configured | The invoke is refused with 501 — never accepted and dropped. |
Paused runs
A run waiting for approval keeps its credentials until ttl_seconds passes. If an approval may take longer, replace them before deciding.
- Only a run started with a security context has one to replace.
- Its own user or a tenant admin may replace it; a run for one of your end users needs an admin.
from elan_sdk import Elan
from elan_sdk.security import Bearer, SecurityContext
elan = Elan.from_env()
elan.runtime.refresh_security_context(
"inv-7f3a",
SecurityContext(credentials=[Bearer(name="notes", token=fresh_token)]),
)What is never stored
- Never written to the invocation envelope, the queue, session state, a conversation event, a published event, a log line or the model's context.
- Sealed at rest for the length of the run, and deleted when it ends.
- Seen by your server, of course, when it is sent there — which is why the reach rule decides which server that is.
- Shared within a grouped pod. Agents grouped into one pod share a process, and therefore one another's credentials. An agent that must not should be deployed on its own.
For the values your agent's own credentials are read from, see Secrets.