Give your AI agent an API key with the least access it needs
If your agent’s MCP config holds the MCPProxy admin API key, the agent has unscoped access: it can call any approved tool on any server behind the proxy, add and remove servers, read the config and mint credentials. A config with no key at all is not much better. require_mcp_auth is off by default, and a keyless client then gets almost the same view on the MCP endpoint.
This guide replaces that with a token that reaches only the servers and operations one agent needs. It takes about ten minutes. At the end you will have:
- a profile that lists the servers and caps the tool tier;
- a token pinned to that profile, sent as an
X-API-Keyheader; - a check that the boundary holds, an audit trail per token, and a one-line revoke.
The steps below were run on MCPProxy v0.76.0 against a throwaway proxy with four reference servers (filesystem, time, everything, memory). Profiles with a tier cap arrived in v0.70.0; on an older build some of the flags are missing. The last section has a skill for Claude Code and Codex that walks an agent through the same steps. The Codex CLI 0.173.0 runs reported there used a second, fresh v0.76.0 proxy with the same four servers.
What the admin key gives an agent
On the demo proxy, a session that sends the admin key lists 17 built-in tools, among them upstream_servers (add, change and remove servers), credentials (issue tokens), profiles and code_execution. Behind retrieve_tools it finds all 44 upstream tools: 29 read, 9 write and 6 destructive. On the REST API the same key reads GET /api/v1/config, which contains the key itself and every server’s settings.
A session that sends no credential while require_mcp_auth is off, and with no anonymous_profile set, listed 15 of those 17 tools on /mcp: everything except credentials and profiles. It still reaches every server and can still manage them. It does not get the REST API.
mcpproxy tools list -o json and mcpproxy profile show notes-reader --effective.To see whether one of your clients still holds the admin key, run mcpproxy doctor. Its connect.admin_key_in_client_config line lists the client configs it knows that do.
Step 1: list what the task needs
The example agent summarises markdown notes in a project folder and needs the current time. That is two servers.
mcpproxy upstream list
mcpproxy tools list --server filesystem
Each tool has a tier: read, write or destructive. MCPProxy takes it from the tool’s own MCP annotations (readOnlyHint, destructiveHint); a tool that declares neither is unannotated. mcpproxy tools list --server filesystem -o json prints the tier of each tool. On the demo, filesystem has 10 read tools, 3 write tools and 3 destructive ones (write_file, edit_file, move_file).
Write down two things: the servers, and the highest tier among the tools the task uses. For a summariser that is read.
One limit to know before you start: a profile scopes servers and tools, not arguments. It cannot say “only this folder”. That stays the job of the server’s own configuration. Here the filesystem server was started with the project folder as its only allowed directory.
Step 2: put the scope in a profile
A profile is a named list of servers with a tool policy. Create one with only what you wrote down:
mcpproxy profile create notes-reader \
--title "Notes · Read-only" \
--servers filesystem,time \
--max-tier read \
--management-tools off
With a read or write cap, two defaults close the usual side doors: unannotated tools are hidden, and code_execution is off. --management-tools off removes upstream_servers and quarantine_security from the agent’s tool list. An agent token can never change servers through them, but while upstream_servers is listed it can list the servers in its scope and tail their logs. Turning the tools off does not close that door completely: see the note on REST in step 5.
Now look at what the profile admits:
mcpproxy profile show notes-reader --effective
Profile: notes-reader (allowed by profile 13, hidden 31, callable 13, held 0)
SERVER TOOL TIER ACCESS REASON
everything echo read hidden server_not_in_profile
filesystem append_file write hidden above_tier_cap
filesystem read_text_file read callable -
filesystem write_file destructive hidden above_tier_cap
memory delete_entities destructive hidden server_not_in_profile
time get_current_time read callable -
...
(Shortened: the real table has 44 rows and two more columns, PROFILE TIER and NOTE.) Thirteen tools are callable and 31 are hidden, each with the reason. Read the callable rows as carefully as the hidden ones: they are the upstream tools the agent gets. (MCPProxy’s own built-in tools are separate; step 6 lists them.) The Web UI shows the same table on Profiles, with the server list and the tier cap beside it.
Two rules adjust the result tool by tool:
- Allow lifts one tool past the cap:
mcpproxy profile update notes-reader --add-allow filesystem:append_file. Use it when the task needs a single write tool; raising the cap towritewould admit every write tool on both servers. Allow hides nothing, and it also admits a tool that has no annotations, so name exact tools. - Deny hides a tool that the cap would admit:
--add-deny filesystem:read_media_file. Deny wins over allow.
Step 3: mint a token pinned to the profile
mcpproxy token create --name notes-agent --profile notes-reader --expires 7d
Agent token created successfully.
Token: mcp_agt_87ab…
IMPORTANT: Save this token now. It cannot be retrieved again.
Name: notes-agent
Servers: *
Permissions: read, write, destructive
Profile: notes-reader
Expires: 2026-12-08T17:34:43.501972Z
The secret is printed once. MCPProxy stores only an HMAC-SHA256 hash of it.
Servers: * and all three permissions look wrong at first. They are the token’s own grant, and for a profile-pinned token the profile is the bound: a request has to pass the token’s grant and the pinned profile, and the token cannot leave the profile. On the demo, set_profile to another existing profile answered unknown profile and /mcp/p/<other> answered 404, the same as for a profile that does not exist.
Three choices here are worth a moment:
- One token per agent. Two agents on one token share one identity: they can only be stopped together. The client name they report and an
X-MCPProxy-Runlabel can separate their records in the activity log, but both are labels the agent chooses, not proof of who made a call. - Short expiry. The default is 30 days, and a duration can be at most 365 days.
--expires neverexists, but an agent’s token should run out on its own. Use hours for a one-off job (--expires 2h). - Keep the secret out of your terminal scrollback. The command above prints it. The skill at the end of this post ships a small script to use instead. Run it from the skill’s
scripts/folder instead oftoken create, not after it. It writes the secret to a mode-600 file, prints only the token’s prefix, refuses to overwrite an existing file, and revokes the token if it could not be saved:
python3 mint_token.py --name notes-agent --profile notes-reader --expires 7d \
--out ~/.config/mcpproxy/tokens/notes-agent
The Web UI does the same from Clients → Agent tokens → Create Token: a name, a profile and an expiry.
Step 4: require a credential
This is the step people skip. With require_mcp_auth off, a token narrows only the client that sends it. A client that leaves the header out is still let in.
The fix is to require a credential on every MCP request. Every other MCP client then needs its own credential, so plan for a short gap: a client that sends none gets 401 until you reconnect it. Turn the setting on in the config file of the running proxy (~/.mcpproxy/mcp_config.json unless you start it with another one; mcpproxy status -o json prints config_path):
{
"require_mcp_auth": true
}
On v0.76.0 the running proxy picked this up when the file was saved. A request without a credential to the HTTP MCP endpoints then gets 401. The local socket that the CLI and the tray use stays trusted; see the last section for what that means.
Now reconnect the other clients. mcpproxy connect <client> --profile <name> --force writes a per-client credential locked to that profile and replaces the old entry. Without --profile, a new credential reaches all servers. (While auth is off, MCPProxy refuses to bind a client to a profile if a keyless caller could reach more than that profile, because the client could walk around the binding by dropping its credential. Turning auth on removes that refusal; so does confining keyless callers to a profile that is no wider, described below.) For clients that hold the admin key, mcpproxy client upgrade-admin-key-holders previews each change and replaces the key once you confirm. Restart or reload each client and confirm it reconnects. Check that no entry still carries the old key, including entries under another name that point at the same proxy. The old admin key keeps working, and may sit in a config backup, until you rotate it (end of step 5).
If you cannot do that yet, there is a weaker option: keep /mcp open and confine the callers that send nothing.
mcpproxy profile anonymous # show the current setting
mcpproxy profile anonymous notes-reader
This authenticates nobody. It changes what every keyless caller gets, and those calls are not attributed to anyone. On a test proxy a keyless session then listed 12 built-in tools and was limited to the profile’s servers and tier.
Once every client sends its credential in a header, consider "mcp_reject_query_apikey": true. It makes the MCP endpoints refuse a credential passed as ?apikey= in the URL, where it would be written to access logs. A credential that has already travelled in a URL should be rotated.
Step 5: put the token in the client config
Send the token as an X-API-Key header. Do not put it in the URL. If the config file is committed, reference an environment variable instead of the value.
Claude Code, in the project’s .mcp.json:
{
"mcpServers": {
"mcpproxy": {
"type": "http",
"url": "http://127.0.0.1:8080/mcp",
"headers": { "X-API-Key": "${MCPPROXY_TOKEN}" }
}
}
}
Codex, in ~/.codex/config.toml:
[mcp_servers.mcpproxy]
url = "http://127.0.0.1:8080/mcp"
env_http_headers = { "X-API-Key" = "MCPPROXY_TOKEN" }
Then start the client from a shell that has the variable:
export MCPPROXY_TOKEN="$(cat ~/.config/mcpproxy/tokens/notes-agent)"
Do not run that line in a traced shell (set -x) or a CI step that echoes commands; in CI, inject the variable from the runner’s secret store. Both shapes were used in the demo runs below. Anything else that speaks HTTP can send X-API-Key: <token> or Authorization: Bearer <token>. Use plain http only for a proxy on the same machine.
You do not have to hand-write the config for every case:
- For Cursor, Windsurf and the other clients in
mcpproxy connect --list,mcpproxy connect cursor --profile notes-readerwrites the client’s config for you with a per-client credential (mcp_cli_…) that is locked to the profile. It writes the literal credential into that file. - For a script or a CI job that only needs MCP,
mcpproxy client add ci-bot --profile notes-readerissues the same kind of credential without writing any config. - A token (
mcp_agt_…) is the one to use when the caller also reads the scoped REST API. Client credentials are refused there.
That REST access cuts both ways. On the demo, the notes-agent token could read GET /api/v1/servers (the launch command and arguments of filesystem and time), GET /api/v1/servers/filesystem/logs and GET /api/v1/activity, all limited to its two servers. memory answered 404. The activity records are scoped by server, not by caller, so they include calls other clients made to those servers. If a server’s arguments, logs or recorded calls can contain secrets and the agent only needs MCP, give it a client credential instead of a token.
If the admin key was in a client config before, removing it from the file does not make it safe. When no client or script uses it any more, rotate it: mcpproxy status --reset-key. The command prints the new key, so run it yourself in your own terminal, not through an agent or a logged CI step.
Step 6: check that the boundary holds
Do not test a denial by firing a destructive tool and hoping. Two checks cover it without running anything upstream.
From the admin side, access explain walks the gates a real call would meet and prints the verdict:
mcpproxy access explain --token notes-agent --tool filesystem:write_file
Tool: filesystem:write_file
Subject: token notes-agent
Profile: notes-reader (pin)
STEP STATUS DETAIL FIX
credential pass - -
profile pass - -
server_in_scope pass - -
tool_rule pass - -
tier_cap fail above_tier_cap Allow filesystem:write_file in Notes · Read-only
token_permission pass - -
global_gate pass - -
server_state pass - -
tool_approval pass - -
VERDICT: hidden at tier_cap
From the agent’s side, connect with the token itself. verify_scope.py from the skill does this with describe_tool, a built-in tool that returns a definition for a tool the caller may use and not_found for one it may not:
python3 verify_scope.py --url http://127.0.0.1:8080/mcp \
--token-file ~/.config/mcpproxy/tokens/notes-agent \
--allowed filesystem:read_text_file --allowed time:get_current_time \
--denied filesystem:write_file --denied everything:echo
PASS no credential -> 401 (a credential is required)
PASS credential accepted
PASS 12 built-in tools, no administrator tools
PASS allowed filesystem:read_text_file is visible
PASS allowed time:get_current_time is visible
PASS denied filesystem:write_file is not found for this credential
PASS denied everything:echo is not found for this credential
PASS GET /api/v1/config -> 403
note a misspelled tool name also reads 'not found': check that each --denied name exists
with `mcpproxy tools list --server <server>`
RESULT OK
The script fails on anything it cannot confirm: a keyless request that is accepted, a listed management tool, a status other than 403 on the config document. With --allow-anonymous it runs against a proxy that admits keyless callers, but then ends in RESULT NOT VERIFIED, because it cannot show that the proxy recognised the token. It probes the token, not your client. To confirm that the client really sends it, start the client and look for its calls under the token’s name (step 7).
MCPProxy also tells the agent its limits when it connects. This is the end of the instructions text the notes-agent session received:
YOUR ACCESS (this connection): profile 'notes-reader' is active — servers outside it are not
reachable. Connected upstream servers you can use: filesystem, time. Find their tools with
'retrieve_tools' (query: the server name plus the task). Allowed operations: read — write and
destructive tool calls will be refused (individual tools may also be restricted). Not available
here: 'code_execution', 'upstream_servers', 'quarantine_security'.
What the agent sees when it tries anyway
For a second token, memory-worker (server memory, tier cap write), I gave a Claude Code session four tasks: add an entity to the knowledge graph, read the graph, delete the entity, and read a file through filesystem. These are the calls it made and what came back:
Two details matter. The refusals are ordinary tool errors with a reason, so the agent can report them instead of retrying blindly. And in these calls a server outside the scope got the same answer as a server that does not exist (Server 'nosuchserver' is not in scope for this agent token), so the refusal does not confirm what else is behind the proxy.
mcpproxy access explain lists nine steps.Step 7: see what the token did
Tool calls and policy refusals made with a token are recorded under its name.
mcpproxy activity list --token memory-worker --status blocked
ID SRC TYPE SERVER TOOL CLIENT PROFILE STATUS
01M8SB91CE5AJWJ0WQR4RC1H3S MCP policy_decis filesystem read_file ~claude-code memory-worker (pin) blocked
01M8SB90RG85S52MSZP93FT58Y MCP policy_decis memory delete_entities ~claude-code memory-worker (pin) blocked
(Trailing columns removed.) Drop --status to see the successful calls too; the command returns the 50 most recent records unless you pass --limit. In the Web UI, each token row on Clients → Agent tokens has an Activity link that opens the log filtered to that token.
If a profile keeps blocking a call the agent needs, mcpproxy access suggest reads those refusals and prints the command that would allow each one. It never applies anything, and it does not offer to lift a deny rule.
Step 8: rotate, revoke, expire
mcpproxy token regenerate notes-agent # new secret (printed once), same name and profile
mcpproxy token revoke notes-agent # stops working, record kept
mcpproxy token delete notes-agent # removes the record, frees the name
A rotation kills the old secret at once, so the client needs the new one before its next call: save it, export the variable again and restart the client. python3 mint_token.py --regenerate --name notes-agent --out ~/.config/mcpproxy/tokens/notes-agent (run from the skill’s scripts/ folder) does the rotation without printing the new secret; the profile and the expiry stay as they were. Revocation does not wait for the agent to reconnect. On the demo, a session that was already open got this on its next request:
HTTP 401 {"error":"Agent token invalid: token has been revoked"}
An expired token is refused in the same way. Issue, rotate and revoke are themselves written to the activity log, without the secret.
To change what an agent may do, edit the profile. The token follows it on the next request and does not need to be reissued. That is convenient, and it means the profile is the thing to guard: every client and token on it changes together. mcpproxy profile list shows who uses each one in the USED BY column.
Let an agent do it: a skill for Claude Code and Codex
A skill is a folder with a SKILL.md file: a name, a description that tells the agent when to use it, and instructions. Claude Code reads skills from ~/.claude/skills/<name>/ and from .claude/skills/ in a project, and runs one when you type /<name> or when the request matches its description. Codex reads them from ~/.agents/skills/<name>/ and .agents/skills/ in a repository, and runs one with $<name> or by description. Both follow the open Agent Skills format, so a SKILL.md that uses only the name and description fields works in both unchanged.
MCPProxy does not ship a skill for this, so here is one: mcpproxy-least-privilege-token. It makes the agent do the steps above in order: inspect the servers and tool tiers, create or reuse a profile, mint a pinned token without printing it, write the client config with the header, verify, and report how to audit and revoke. It is three files:
SKILL.md, the instructions;scripts/mint_token.py, which creates or rotates a token and saves the secret to a mode-600 file (macOS and Linux);scripts/verify_scope.py, the check from step 6.
The agent that runs this skill acts as the proxy’s administrator, so treat the files like any script you would run as yourself. Download them to a scratch folder first:
base=https://mcpproxy.app/examples/blog/least-privilege-agent-token/mcpproxy-least-privilege-token
scratch="$(mktemp -d)" && mkdir "$scratch/scripts" && cd "$scratch"
curl -fsSLO "$base/SKILL.md"
(cd scripts && curl -fsSLO "$base/scripts/mint_token.py" && curl -fsSLO "$base/scripts/verify_scope.py")
Check that you have the files as published with this post, which are the ones the Codex run below used:
shasum -a 256 SKILL.md scripts/mint_token.py scripts/verify_scope.py # Linux: sha256sum
e529a3b496a255741a67a98a5cd0deefa83b3a09310bf465088cbbd87c461791 SKILL.md
937002b7df95942444e9ccb1a0c62d6af89b02c60e91e83429d34a1ff705ea78 scripts/mint_token.py
337b1674987d407fc89e9401ef857c78821eb8a3ebc115a18e87f0c7d52cfd27 scripts/verify_scope.py
A match shows that the download is complete and is this version. The checksums are served by the same site as the files, so it does not protect against someone who can change both. Read all three files, and only then move the folder where the agent finds it, from the same shell:
dest=~/.claude/skills/mcpproxy-least-privilege-token # Codex: ~/.agents/skills/...
mkdir -p "$(dirname "$dest")"
test ! -e "$dest" && mv "$scratch" "$dest" # to update, remove the old folder first
Then ask for what you need:
$mcpproxy-least-privilege-token I'm going to run a Codex worker that summarises the
markdown notes under /tmp/demo-project (the "filesystem" server) and needs the current
time (the "time" server). It must not be able to change anything. Name the token
notes-codex, valid for 7 days.
I ran the published skill in Codex, and an earlier draft in Claude Code against the demo proxy from the steps above.
Codex CLI 0.173.0 (codex exec -m gpt-6.2-sol) ran the three files exactly as they are published here, on a fresh proxy with the same four servers and no profiles yet. It read the tool tiers, previewed with profile try, and created a profile narrower than the one in step 2: list_directory, read_text_file and get_current_time callable, the other 41 tools hidden, ten of them by deny rules. It named that profile notes-reader too, with the title “Notes reader”. It minted notes-codex with mint_token.py, wrote the config with env_http_headers, got the six verdicts it expected from access explain, and ran the verifier. The output, minus one advisory line:
PASS no credential -> 401 (a credential is required)
PASS credential accepted
PASS 12 built-in tools, no administrator tools
PASS allowed filesystem:list_directory is visible
PASS allowed filesystem:read_text_file is visible
PASS allowed time:get_current_time is visible
PASS denied filesystem:write_file is not found for this credential
PASS denied time:convert_time is not found for this credential
PASS denied memory:read_graph is not found for this credential
PASS GET /api/v1/config -> 403
RESULT OK
The skill says that this probes the token, not the client. So Codex started a second Codex process with the config it had just written, had it make one retrieve_tools call, and found that call in the activity log under the token.
I then started a Codex worker with that config entry and the token in MCPPROXY_TOKEN. It listed and read both notes and got the time. Asked to append a line and to call everything:echo, it found no such tools and did not attempt either call. To see the refusals themselves, I sent four calls with the token directly. The first three got the refusals below; the fourth, time:get_current_time, succeeded.
Server 'everything' is not in scope for this agent token
blocked by profile: filesystem:append_file is a write tool; profile "Notes reader" (notes-reader) allows read tools only
blocked by profile: time:convert_time is denied by a rule in profile "Notes reader" (notes-reader)
One more codex exec run, with the skill again, closed the job. I asked it to show what the token had done, revoke it, and prove that the secret no longer works. It listed the worker’s reads and the three blocked calls from the activity log, ran mcpproxy token revoke notes-codex, and tested the saved secret before and after:
Before revocation: MCP initialize HTTP 200, REST servers HTTP 200
Token record revoked: True
After revocation: MCP initialize HTTP 401, REST servers HTTP 401
I searched all three transcripts for the token and for the admin key. Neither appears.
The verifier asks about one tool per call because of an earlier run. Codex CLI 0.172.0 ran the skill as it stood after the first review pass, and the verifier failed at its describe_tool check:
PASS no credential -> 401 (a credential is required)
PASS credential accepted
PASS 12 built-in tools, no administrator tools
FAIL describe_tool did not return a usable answer (HTTP 200)
PASS GET /api/v1/config -> 403
RESULT FAILED
The bug was mine. describe_tool takes at most five tool ids per call, and Codex had asked about six. Codex did what the skill tells it to do with a failed check:
Created the credential and config, but the final scope probe failed, so it is not verified
for use yet. [...] The worker should not be started until that probe issue is resolved.
To remove the unverified credential:
mcpproxy token revoke notes-codex
mcpproxy token delete notes-codex
Claude Code 2.1.318 (claude -p, headless, with a narrow tool allowlist) ran an earlier draft of the skill. From the request “reads the graph and adds to it, must never delete” it created the memory-worker profile with a write cap, minted the token, and confirmed three verdicts with access explain. It then stopped at two permission prompts that nobody was there to answer: writing .mcp.json, which Claude Code treats as a sensitive file, and reading the token file for the verify script. It reported both as not done. In an interactive session you approve those prompts. I wrote the file by hand, ran the script (all PASS), and then ran the worker session shown in step 6 with that config.
Claude Code has not run the published text, only that draft. Review of the draft found that the verifier passed too easily, for example on any config status other than 200, and that the token-saving shell one-liner could truncate an existing secret file. Later review rounds tightened the instructions further, mostly about keeping secrets out of the agent’s transcript. The Codex setup run and the revoke run above both used the published files.
One thing the runs taught me about testing skills: Codex runs commands in a login shell, which rebuilt PATH and found a different mcpproxy binary than the one I meant. The skill’s first step prints the address of the proxy it is talking to. Read that line before you let an agent continue.
What a scoped token does not protect
A token confines what an agent can do through MCPProxy. It is worth being exact about the edges.
- An agent that runs commands as the proxy’s OS user is not confined by it. The
mcpproxyCLI talks to the daemon over a local socket as an administrator, with no key. A coding agent with a shell under your account can runmcpproxy token createitself, or readmcp_config.json.mcpproxy doctorprints a warning about the same exposure for stdio servers. The token is a real boundary only when the agent cannot reach that socket or read the proxy’s data directory: it runs under another account or on another machine, or in a container that does not mount them, and none of its other tools can read them either. A sandbox that only confines writes is not enough. - Tiers come from the server’s own annotations. A tool that declares
readOnlyHint: trueand writes anyway passes areadcap. Quarantine and tool approval catch a definition that changes; they do not prove an annotation is honest. For a server you do not fully trust, go through the callable list inprofile show --effectiveand deny every tool the agent does not need. - Arguments are not scoped. The profile decides which tools can be called, not on what. Limit paths, repositories and accounts in the upstream server’s own configuration. A read-only filesystem server rooted at your home directory can read
~/.mcpproxy/mcp_config.json, admin key included, for any agent that may call it. - A token can read its servers’ metadata over REST. Launch arguments, logs and activity of the servers in scope are readable with an agent token, whatever the tier cap says. Use a client credential when that is too much.
- A profile is shared policy. Widening it widens every token on it.
- Tools only. A profile’s tier cap and rules apply to tools. Prompts are not filtered by tier.
- The secret sits where you put it. A token in a config file is readable by anything that can read the file. Short expiry and one token per agent limit what a leaked one is worth. A call budget (
--rate-limit 60) limits what a runaway loop can spend.
The short version
# 1. scope
mcpproxy profile create notes-reader --servers filesystem,time --max-tier read --management-tools off
mcpproxy profile show notes-reader --effective
# 2. credential, saved to a mode-600 file (plain `mcpproxy token create` prints it instead)
python3 mint_token.py --name notes-agent --profile notes-reader --expires 7d \
--out ~/.config/mcpproxy/tokens/notes-agent
# 3. set "require_mcp_auth": true in mcp_config.json, then send the token as X-API-Key
# 4. check, audit, stop
mcpproxy access explain --token notes-agent --tool filesystem:write_file
python3 verify_scope.py --url http://127.0.0.1:8080/mcp \
--token-file ~/.config/mcpproxy/tokens/notes-agent \
--allowed filesystem:read_text_file --denied filesystem:write_file
mcpproxy activity list --token notes-agent
mcpproxy token revoke notes-agent
Reference: Agent tokens, Profiles, Connect clients, Activity log.