Variables & secrets
Configuration an agent needs but should not hard-code — a shop's base URL, a region, the login for a scraping service — lives with the organization, not in the agent's code. An admin sets it up once; each agent is granted only what it uses.
There are two kinds, and they behave differently on purpose:
Variable (var) | Secret (secret) | |
|---|---|---|
| Value readable by the agent | yes — core.vars["KEY"] | never |
| Used for | URLs, regions, IDs, settings | passwords, tokens, keys |
| Shown in the Portal after saving | yes | no — write-only |
| Reaches a connected service | if your code sends it | through the gateway only — see Secrets |
Setting them up (admins)
- Org Settings → Variables → Add variable. Pick a key (
UPPER_SNAKE_CASE, unique in the organization), the type, and the value. Optionally limit it to some workspaces. - For a secret, also choose its allowed services — the connected services it may ever be sent to. A secret with none cannot be used in any call.
- Agents → the agent → Manifest → Variables & secrets. Switch on what this agent may use and save. Only variables available in the agent's workspace are offered.
The grant takes effect on the agent's next run. Revoking it, or limiting the variable to another workspace, takes it away from the next run too.
Reading variables — core.vars
The values of the agent's granted variables arrive when the client authorizes, and are fixed for the rest of the run.
from im_sdk import ImCore, im_agent
@im_agent("shop-scraper")
async def main(core: ImCore, data: dict) -> dict:
base_url = core.vars["SHOP_URL"] # KeyError if not granted
region = core.vars.get("REGION", "eu-west-1") # default when not granted
everything = core.vars.all() # a plain dict (a copy)
...core.vars["KEY"]raisesKeyErrornaming the key when the variable is not granted to this agent, or does not exist.core.vars.get("KEY", default=None),"KEY" in core.varsandcore.vars.all()never raise.core.varsis empty until the client has authorized —@im_agentandasync with core:do that before your code runs.- Values are strings, exactly as they were entered —
core.vars["MAX_PAGES"]is"25", not25. The typed reads below parse them for you. - There is no
.envfallback. A local run authorizes the same way a deployed one does, so it sees exactly what the agent was granted.
Typed reads
A variable is always stored as text. When your code needs a number, a flag or structured data, read it with the matching helper instead of parsing it yourself:
pages = core.vars.get_int("MAX_PAGES", 10) # int — 10 when not granted
rate = core.vars.get_float("SAMPLE_RATE") # float
dry_run = core.vars.get_bool("DRY_RUN", False) # bool
config = core.vars.get_json("SCRAPER_CONFIG") # dict, list, … — whatever the JSON holds| Helper | Returns | Accepts |
|---|---|---|
get_int(key, default) | int | whole numbers; surrounding spaces are ignored |
get_float(key, default) | float | any number (0.25, 1e3) |
get_bool(key, default) | bool | true/false, 1/0, yes/no, on/off — any case |
get_json(key, default) | any | valid JSON — an object, a list, a number, … |
- Not granted: you get
defaultwhen you pass one (returned as you gave it,Noneincluded), otherwise the sameKeyErrorascore.vars["KEY"]. - Doesn't parse: a
ValueErrornaming the key and what was expected — for examplevariable DRY_RUN is not a boolean (true/false, 1/0, yes/no, on/off). It never repeats the value. core.vars["KEY"]is unchanged: it always returns the string.
core.vars, its typed reads included, needs im-sdk 1.2.0 or newer.
Don't log the values or put them in your output unless that is the point — they are the organization's configuration.
Secrets
A secret's value never reaches agent code — not through core.vars, not in the run's
environment, not in a trace, not in a response. The agent names it with core.secret("KEY"),
and the gateway puts the value in on the way out:
result = await core.web_crawler.run_actor(
"apify",
"apify/website-content-crawler",
input={
"startUrls": [{"url": core.vars["SHOP_URL"]}],
"loginUsername": core.secret("SHOP_LOGIN"),
"loginPassword": core.secret("SHOP_PASSWORD"),
},
)This call needs the apify connection to list apify/website-content-crawler in its allowed
actors — see Where a secret can go.
core.secret("SHOP_PASSWORD") returns a placeholder, not the value: a SecretRef, which is an
ordinary string of the form "{{secret:SHOP_PASSWORD:<nonce>}}". The nonce belongs to this
session — drawn when the client authorized, and known only to it and the gateway. Before the call is
sent, the SDK notes where in the call each placeholder sits; the gateway checks the nonce at those
places, fetches the value from the Portal and puts it into the request it sends to the connected
service — on a copy, after the call was logged and audited, so neither ever sees the value. Your
code never holds it: the value goes from the Portal to the service. What the service does with it
afterwards is up to the service — see What masking cannot do.
The rules
- Write
core.secret("KEY"), with the key as it was created (UPPER_SNAKE_CASE). It is a string, so it goes anywhere a string does — inside an f-string (f"Bearer {core.secret('API_TOKEN')}"), with+or"%s" %, a header, a body field, a list, a nested object, and more than one per string. Printing the reference itself, or a dict holding it, showsSecretRef('KEY'); a string you built from it carries the placeholder, so log throughlog(), which hides the nonce, rather thanprint. Dictionary keys are never substituted: a placeholder in one refuses the call (in_key). - Never in a path. A custom-HTTP connection that can carry a secret has an endpoint list, and
its endpoints match the path exactly — no endpoint names a secret's value, so a path that carries
a placeholder is refused (
POLICY_CONSTRAINT_PATH). Put the secret in a header, the query or the body. - Only placeholders built in this session work. A placeholder typed by hand —
"{{secret:KEY}}"— carries no nonce; one with any other nonce came from another session or from content the agent received. In a call tohttp_capabilityorweb_crawlereither refuses the call before it is sent (POLICY_SECRET_NOT_SUBSTITUTED, see Errors). Anywhere else — an LLM prompt, aguardrail()check — nothing is substituted, so it is plain text and is sent as written. A near miss such as{{ secret:KEY }}or{{secret:key}}is not a placeholder and is sent as written. - Build it again in a new session. A placeholder is valid only in the session that built it:
after the run resumes from a pause, in a second
ImCore, or after a manualauthorize(), callcore.secret("KEY")again rather than reusing one you saved. - Where: calls to a connected service —
http_capabilityandweb_crawler— whose service is one of the secret's allowed services and pins where its calls go (below). - When: only in a deployed run (or a Playground / API /
im-cli runexecution). A session that belongs to no execution — an SDK example started by hand against a local stack — gets no secret, andcore.secretraises there. - At most 32 places to substitute in one call.
core.secret raises before any call is made in two cases: ValueError when the key is not
UPPER_SNAKE_CASE, and ImForbiddenError (POLICY_SECRET_NOT_SUBSTITUTED) when there is no nonce
to give — context["reason"] is not_authorized (the client has not authorized yet),
no_execution (the session is bound to no run) or gateway_unsupported (the gateway predates
core.secret). That is the code and context a refused call carries, so the same except handles
both. It does not check the grant: a key that is not granted is refused when the call is made
(POLICY_SECRET_NOT_GRANTED, see Errors). SecretRef and core.secret need
im-sdk 1.2.0 or newer.
Where a secret can go
Your code decides what it sends within a connection, so a secret goes only where an admin pinned the destination on that connection:
| Connection | Pinned by | What your code still chooses |
|---|---|---|
Custom HTTP (http_capability) | the service's endpoint list | headers, query and body of a listed endpoint — not a header that would send the call elsewhere |
Apify (web_crawler) | the connection's allowed actors | the actor's input |
A secret can only be allowed for a pinned service, and a call carrying one to an Apify actor the
connection does not list — or to a custom-HTTP service whose endpoint list was removed — is
refused (destination_not_pinned). A secret can never name the actor or
dataset a call goes to. A custom-HTTP call may not set Host, Forwarded, X-Forwarded-*, a
method or path override (X-HTTP-Method-Override, X-Original-URL, X-Rewrite-URL) or a
hop-by-hop header, with or without a secret: any of them could route the call past its endpoint
list (POLICY_FORBIDDEN, context["kind"] is header_not_allowed). Allowing an actor means trusting it with whatever input your code gives
it: a crawler fetches any URL it is handed, so a secret in its input can reach any site the input
names.
Never substituted
| Where | Why | What happens |
|---|---|---|
llm and embedding calls, streamed or not, and the texts of a guardrail() check | a model can repeat its prompt back | the call is refused |
web_fetch | the agent picks the destination, so the value could go anywhere | the call is refused |
data, object_store, vector | they store what they are sent and hand it back to the agent on the next read | the call is refused |
web_search, document_parse | their credentials already come from the connection | the call is refused |
file_store | there is no connected service to send it to | the call is refused |
| An uploaded file's contents, a run's input, a resume answer, anything the gateway returns | only what your code wrote with core.secret is substituted | a placeholder in that text carries no nonce of this session; forwarded into an http_capability or web_crawler call it refuses the call, anywhere else it is text |
A refused call is never sent. Nothing is ever sent with the placeholder left in by mistake.
Content the agent receives — an uploaded file, a fetched page, model output, a service's response,
a run's input — cannot know this session's nonce. So a placeholder planted in it never becomes a
working one, even after your code decodes it: a file read back as base64 content_b64, HTML
entities, URL- or JSON-escaped braces, markup your code strips. The flip side: text that contains
a literal {{secret:…}} makes an http_capability or web_crawler call that forwards it fail,
whether it got there by accident or on purpose. If you forward third-party text — a page, a search
result, a model's answer — into such a call, remove or escape such markers first. Forwarding it to a
model is fine.
Errors
A placeholder the gateway will not fill raises a typed error naming the key and the reason in
exc.context["key"] and exc.context["reason"] — never the value or a nonce.
POLICY_SECRET_NOT_SUBSTITUTED also lists the keys involved in exc.context["keys"]:
| Code | Exception | Meaning |
|---|---|---|
POLICY_SECRET_NOT_GRANTED | ImForbiddenError | No secret by that key is granted to this agent, or it is not available in the agent's workspace. A granted variable of that name does not count. |
POLICY_SECRET_SERVICE_NOT_ALLOWED | ImForbiddenError | The secret is granted, but the service this call addresses is not one of its allowed services (service_not_allowed), or no longer pins its destination (service_not_pinned). |
SECRET_VALUE_NOT_SET | ImManifestError | Granted and allowed, but no value has been stored. An admin fixes it in Org Settings → Variables. |
POLICY_SECRET_NOT_SUBSTITUTED | ImForbiddenError | This call cannot carry a secret: context["reason"] is resource (see the table above), no_execution, execution_not_active (the run has finished or is paused), destination_not_pinned (an Apify actor the connection does not list, or a custom-HTTP service without an endpoint list), undeclared (an older SDK sent this session's nonce without saying where — upgrade the SDK), or one of the reasons below. core.secret itself raises it with not_authorized, no_execution or gateway_unsupported. |
The reasons that are about the placeholder itself — raised by the SDK before the call is sent:
reason | Meaning | What to do |
|---|---|---|
unsigned | The placeholder has no nonce — "{{secret:KEY}}" written by hand, or text that arrived in content | Write core.secret("KEY") instead of the string; remove the marker from text you forward. |
foreign_nonce | The placeholder carries a nonce that is not this session's — one kept from an earlier session, or text that arrived in content | Call core.secret("KEY") in this session, and don't forward received content into a call unchanged. |
in_key | The placeholder is a dictionary key, which is never substituted | Move it into a value. |
malformed | This session's nonce outside an intact placeholder — one cut short or edited after core.secret() built it | Use the value core.secret("KEY") returns as it is; don't slice it or rebuild it from parts. |
from im_sdk import ImForbiddenError
from im_sdk.exceptions import ImErrorCode
try:
await core.http_capability.request("shop", "/login", body={"pw": core.secret("SHOP_PASSWORD")})
except ImForbiddenError as exc:
if exc.code == ImErrorCode.POLICY_SECRET_SERVICE_NOT_ALLOWED:
... # ask an admin to allow the `shop` service on SHOP_PASSWORD
raiseThe codes are in im-sdk 1.2.0. An older SDK raises the same exception
class with exc.code set to None, so except ImForbiddenError works either way.
What comes back is masked
A service that echoes its request — or an error that quotes it — would hand the value straight
back to your code. So the gateway masks the values a call carried out of that call's answer:
the output, the raw upstream payload, metadata, and the error message and context. A value of 8
characters or more is replaced with [REDACTED] wherever it appears; a shorter one only where it
stands as a whole word, since "1234" inside another number is more likely a coincidence than an
echo. Its URL- and JSON-escaped spellings are masked too, and a value echoed back as a JSON number
becomes the string [REDACTED]. An answer to a call that carried no secret is returned exactly as
the service sent it.
Masking is visible, so code in the agent can test guesses against it: send a candidate value
through an allowed service and see whether it comes back [REDACTED]. A short or low-entropy
secret — a PIN, a short password — can be recovered that way by anyone who can push code to a
granted agent. Use high-entropy secrets.
Observability follows the same rule: an org's Langfuse trace keeps the placeholder with its nonce
replaced by [nonce] on the request side (the platform's default masking may show it as
{{[REDACTED]}}) and
sees the masked answer on the response side of the call that carried the value. The run's audit
record holds no request parameters at all.
What masking cannot do
Allowing a secret for a service means trusting every developer who can push to a granted agent, within the destinations the admin pinned: the code decides what it sends there.
The value is sent to the service — that is the point — so the service, and anyone who can read what it stores, can see it. An Apify run's input, for example, is kept in that Apify account's run history in clear text. Allow a secret only for services you trust with it, and prefer credentials scoped to the one job.
Masking covers the call that carried the secret, and nothing after it. A service that keeps what it was sent and lets the agent read it back — a CRM note, a document an Apify actor saved — returns the value unmasked to a later call — and with it to everything that records that call: the org's Langfuse trace, and, if the call fails with an error quoting the value, the run's audit record and the platform's logs. So treat every allowed service the agent can also read from as one that gives the value to the agent and to everyone who can read its traces.
Masking also only recognises the value as it was stored. A service that transforms it — hashes it, base64-encodes it inside a larger string, prints every other character — can return something masking does not catch.
Finding out what an agent has
The Manifest tab lists the variables and secrets an agent is granted. Org Settings → Variables shows, per variable, how many agents hold it — and, to admins, which ones.
From a project directory, im-cli agent variables lists the same grants
for the linked agent, with the line to use each one in its USE column. A secret's value is
never shown there either.